示例#1
0
文件: ui.py 项目: leohazy/FeelUOwn
class RightPanel_Container(FScrollArea):
    def __init__(self, app, parent=None):
        super().__init__(parent)
        self._app = app

        self.right_panel = RightPanel(self._app)
        self._layout = QVBoxLayout(self)
        self.setWidget(self.right_panel)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidgetResizable(True)

        self.setObjectName('c_left_panel')
        self.set_theme_style()
        self.setup_ui()

    def set_theme_style(self):
        theme = self._app.theme_manager.current_theme
        style_str = '''
            #{0} {{
                background: transparent;
                border: 0px;
            }}
        '''.format(self.objectName(),
                   theme.color5.name())
        self.setStyleSheet(style_str)

    def setup_ui(self):
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)
示例#2
0
    def __init__(self):
        super(RunWidget, self).__init__()
        vbox = QVBoxLayout(self)
        vbox.setSpacing(0)
        vbox.setContentsMargins(0, 0, 0, 0)
        self.output = OutputWidget(self)
        hbox = QHBoxLayout()
        self.input = QLineEdit()
        self.lblInput = QLabel(_translate("RunWidget", "Input:"))
        vbox.addWidget(self.output)
        hbox.addWidget(self.lblInput)
        hbox.addWidget(self.input)
        vbox.addLayout(hbox)

        self.set_font(settings.FONT_FAMILY, settings.FONT_SIZE)

        #process
        self.currentProcess = None
        self.__preScriptExecuted = False
        self._proc = QProcess(self)
        self._preExecScriptProc = QProcess(self)
        self._postExecScriptProc = QProcess(self)
        self._proc.readyReadStandardOutput.connect(self.output._refresh_output)
        self._proc.readyReadStandardError.connect(self.output._refresh_error)
        self._proc.finished[int, 'QProcess::ExitStatus'].connect(self.finish_execution)
        self._proc.error['QProcess::ProcessError'].connect(self.process_error)
        self.input.returnPressed.connect(self.insert_input)
        self._preExecScriptProc.finished[int, 'QProcess::ExitStatus'].connect(self.__main_execution)
        self._preExecScriptProc.readyReadStandardOutput.connect(self.output._refresh_output)
        self._preExecScriptProc.readyReadStandardError.connect(self.output._refresh_error)
        self._postExecScriptProc.finished[int, 'QProcess::ExitStatus'].connect(self.__post_execution_message)
        self._postExecScriptProc.readyReadStandardOutput.connect(self.output._refresh_output)
        self._postExecScriptProc.readyReadStandardError.connect(self.output._refresh_error)
示例#3
0
文件: window.py 项目: grsakea/pyt
    def initUI(self):
        self.setWindowTitle('Twitter Client')
        self.setWindowIcon(QIcon("twitter.svg"))
        QIcon.setThemeName("Adwaita")

        lay = QVBoxLayout(self)
        scr = QScrollArea(self)
        scr.setWidgetResizable(True)
        scr.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

        lay2 = QVBoxLayout()
        self.setLayout(lay)
        placehold = QWidget()
        lay.addWidget(scr)
        scr.setWidget(placehold)
        placehold.setLayout(lay2)
        self.lay = lay2

        lay2.setSpacing(0)
        lay.setSpacing(0)
        lay.setContentsMargins(0, 0, 0, 0)

        but = QPushButton("Refresh")
        lay.addWidget(but)
        but.pressed.connect(self.fetch_tweets)

        self.show()
示例#4
0
文件: ui.py 项目: leohazy/FeelUOwn
class LP_PlaylistsPanel(FFrame):
    def __init__(self, app, parent=None):
        super().__init__(parent)
        self._app = app

        self.header = LP_GroupHeader(self._app, '歌单')
        self._layout = QVBoxLayout(self)
        self.setObjectName('lp_playlists_panel')

        self.set_theme_style()
        self.setup_ui()

    def set_theme_style(self):
        theme = self._app.theme_manager.current_theme
        style_str = '''
            #{0} {{
                background: transparent;
            }}
        '''.format(self.objectName(),
                   theme.color5.name())
        self.setStyleSheet(style_str)

    def add_item(self, item):
        self._layout.addWidget(item)

    def setup_ui(self):
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)

        self._layout.addWidget(self.header)
示例#5
0
    def __init__(self, parent=None):
        super(LocatorWidget, self).__init__(
            parent, Qt.Dialog | Qt.FramelessWindowHint)
        self._parent = parent
        self.setModal(True)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setStyleSheet("background:transparent;")
        self.setFixedHeight(400)
        self.setFixedWidth(500)
        view = QQuickWidget()
        view.rootContext().setContextProperty("theme", resources.QML_COLORS)
        view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        view.setSource(ui_tools.get_qml_resource("Locator.qml"))
        self._root = view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(view)

        self.locate_symbols = locator.LocateSymbolsThread()
        self.locate_symbols.finished.connect(self._cleanup)
        # FIXME: invalid signal
        # self.locate_symbols.terminated.connect(self._cleanup)
        # Hide locator with Escape key
        shortEscMisc = QShortcut(QKeySequence(Qt.Key_Escape), self)
        shortEscMisc.activated.connect(self.hide)

        # Locator things
        self.filterPrefix = re.compile(r'(@|<|>|-|!|\.|/|:)')
        self.page_items_step = 10
        self._colors = {
            "@": "#5dade2",
            "<": "#4becc9",
            ">": "#ff555a",
            "-": "#66ff99",
            ".": "#a591c6",
            "/": "#f9d170",
            ":": "#18ffd6",
            "!": "#ff884d"}
        self._filters_list = [
            ("@", "Filename"),
            ("<", "Class"),
            (">", "Function"),
            ("-", "Attribute"),
            (".", "Current"),
            ("/", "Opened"),
            (":", "Line"),
            ("!", "NoPython")
        ]
        self._replace_symbol_type = {"<": "&lt;", ">": "&gt;"}
        self.reset_values()

        self._filter_actions = {
            '.': self._filter_this_file,
            '/': self._filter_tabs,
            ':': self._filter_lines
        }
        self._root.textChanged['QString'].connect(self.set_prefix)
        self._root.open['QString', int].connect(self._open_item)
        self._root.fetchMore.connect(self._fetch_more)
示例#6
0
class NavigationBar(QWidget):

    itemName = ['A', 'B', 'C', 'D', 'E']

    def __init__(self, parent):
        super().__init__(parent)

        self.initUI()

    def initUI(self):
        self.setObjectName("naviBar")

        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)

        self.vboxList = QVBoxLayout(self)
        self.vboxList.setContentsMargins(0, 0, 0, 0)
        self.vboxList.setSpacing(6)
        self.initBtnList(self.vboxList)

    def initBtnList(self, vBox):
        for name in self.itemName:
            btn = QPushButton(name, self)
            vBox.addWidget(btn)
示例#7
0
 def __init__(self, parent, name):
     QWidget.__init__(self, parent)
     self.setStyleSheet(get_stylesheet("ribbonPane"))
     horizontal_layout = QHBoxLayout()
     horizontal_layout.setSpacing(0)
     horizontal_layout.setContentsMargins(0, 0, 0, 0)
     self.setLayout(horizontal_layout)
     vertical_widget = QWidget(self)
     horizontal_layout.addWidget(vertical_widget)
     horizontal_layout.addWidget(RibbonSeparator(self))
     vertical_layout = QVBoxLayout()
     vertical_layout.setSpacing(0)
     vertical_layout.setContentsMargins(0, 0, 0, 0)
     vertical_widget.setLayout(vertical_layout)
     label = QLabel(name)
     label.setAlignment(Qt.AlignCenter)
     label.setStyleSheet("color:#666;")
     content_widget = QWidget(self)
     vertical_layout.addWidget(content_widget)
     vertical_layout.addWidget(label)
     content_layout = QHBoxLayout()
     content_layout.setAlignment(Qt.AlignLeft)
     content_layout.setSpacing(0)
     content_layout.setContentsMargins(0, 0, 0, 0)
     self.contentLayout = content_layout
     content_widget.setLayout(content_layout)
示例#8
0
    def __init__(self, parent=None):
        super(FilesHandler, self).__init__(
            None, Qt.FramelessWindowHint | Qt.Popup)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self._main_container = parent
        # Create the QML user interface.
        self.setFixedHeight(300)
        self.setFixedWidth(400)
        self.view = QQuickWidget()
        self.view.rootContext().setContextProperty(
            "theme", resources.QML_COLORS)
        self.view.setResizeMode(QQuickWidget.SizeRootObjectToView)
        self.view.setSource(ui_tools.get_qml_resource("FilesHandler.qml"))
        # self.view.setClearColor(Qt.transparent)
        self._root = self.view.rootObject()
        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        vbox.addWidget(self.view)

        self._model = {}
        self._temp_files = {}
        self._max_index = 0

        self._root.open.connect(self._open)
        self._root.close.connect(self._close)
        self._root.fuzzySearch.connect(self._fuzzy_search)
        self._root.hide.connect(self.hide)
示例#9
0
 def nestWidget(parent, child):
     l = QVBoxLayout()
     l.setContentsMargins(0,0,0,0)
     l.setSpacing(0)
     parent.setLayout(l)
     parent.layout().addWidget(child)
     return child
示例#10
0
文件: prefs.py 项目: freeaks/filer
class QCustomQWidget (QWidget):

    def __init__(self, parent=None):
        super(QCustomQWidget, self).__init__(parent)
        self.textQVBoxLayout = QVBoxLayout()
        self.textQVBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.textQVBoxLayout.setSpacing(0)

        self.textUpQLabel = QLabel()
        self.textDownQLabel = QLabel()
        self.textQVBoxLayout.addWidget(self.textUpQLabel)
        self.textQVBoxLayout.addWidget(self.textDownQLabel)
        self.allQHBoxLayout = QHBoxLayout()
        self.allQHBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.allQHBoxLayout.setSpacing(3)
        self.iconQLabel = QLabel()
        self.allQHBoxLayout.addWidget(self.iconQLabel, 0)
        self.allQHBoxLayout.addLayout(self.textQVBoxLayout, 1)
        self.setLayout(self.allQHBoxLayout)
        # setStyleSheet
        self.textUpQLabel.setStyleSheet('''color: rgb(0, 0, 255);''')
        self.textDownQLabel.setStyleSheet('''color: rgb(0, 0, 0);''')

    def setTextUp(self, text):
        self.textUpQLabel.setText(text)

    def setTextDown(self, text):
        self.textDownQLabel.setText(text)

    def setIcon(self, imagePath):
        self.iconQLabel.setPixmap(QPixmap(imagePath))
示例#11
0
class EditorWidget(QFrame):
    def __init__(self, parent=None, text=None, EditorSidebarClass=EditorSidebar, EditorViewClass=EditorView):
        QFrame.__init__(self, parent)
        self.view = EditorViewClass(self, text)
        self.sidebar = EditorSidebarClass(self)
        self.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken)
        self.setLineWidth(2)
        self.vlayout = QVBoxLayout()
        self.vlayout.setSpacing(0)
        self.setLayout(self.vlayout)
        self.hlayout = QHBoxLayout()
        self.vlayout.addLayout(self.hlayout)
        self.hlayout.addWidget(self.sidebar)
        self.hlayout.addWidget(self.view)
        self.vlayout.setContentsMargins(2, 2, 2, 2)

    def setPlainText(self, text):
        self.view.document().setPlainText(text)
        self.view.setModified(False)

    def isModified(self):
        return self.view.document().isModified()

    def toPlainText(self):
        return unicode(self.view.document().toPlainText())

    def setModified(self, flag):
        self.view.document().setModified(flag)
示例#12
0
    def __init__(self, parent=None):
        super(CentralWidget, self).__init__(parent)
        self.parent = parent
        main_container = QHBoxLayout(self)
        main_container.setContentsMargins(0, 0, 0, 0)
        main_container.setSpacing(0)
        # This variables are used to save the spliiter sizes
        self.lateral_panel = LateralPanel()

        self._add_functions = {
            "central": self._insert_widget_inside,
            "lateral": self._insert_widget_base
        }
        self._items = {}

        # Toolbar
        self._toolbar = ntoolbar.NToolBar(self)
        main_container.addWidget(self._toolbar)

        # Create Splitters to divide the UI 3 regions
        self._splitter_base = dynamic_splitter.DynamicSplitter(Qt.Horizontal)
        self._splitter_inside = dynamic_splitter.DynamicSplitter(Qt.Vertical)
        self._splitter_base.addWidget(self._splitter_inside)

        vbox = QVBoxLayout()
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)

        vbox.addWidget(self._splitter_base)
        tools_dock = IDE.get_service("tools_dock")
        vbox.addWidget(tools_dock.buttons_widget)
        main_container.addLayout(vbox)
        # main_container.addWidget(self._splitter_base)
        IDE.register_service("central_container", self)
示例#13
0
    def __init__(self, parent=None):
        super(QueryContainer, self).__init__(parent)
        self._parent = parent
        box = QVBoxLayout(self)
        self.setObjectName("query_container")
        box.setContentsMargins(0, 0, 0, 0)
        box.setSpacing(0)
        # Regex for validate variable name
        self.__validName = re.compile(r'^[a-z_]\w*$')

        self.__nquery = 1

        # Tab
        self._tabs = tab_widget.TabWidget()
        self._tabs.tabBar().setObjectName("tab_query")
        self._tabs.setAutoFillBackground(True)
        p = self._tabs.palette()
        p.setColor(p.Window, Qt.white)
        self._tabs.setPalette(p)
        box.addWidget(self._tabs)

        self.relations = {}

        self.__hide()

        # Connections
        self._tabs.tabCloseRequested.connect(self.__hide)
        self._tabs.saveEditor['PyQt_PyObject'].connect(
            self.__on_save_editor)
示例#14
0
class RightWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.layout = QVBoxLayout()
        self.webview = MusicWidget()

        self.set_me()
        self.set_widgets_prop()
        self.set_layouts_prop()

    def set_me(self):
        self.setLayout(self.layout)

    def paintEvent(self, event):
        """
        self is derived from QWidget, Stylesheets don't work unless \
        paintEvent is reimplemented.y
        at the same time, if self is derived from QFrame, this isn't needed.
        """
        option = QStyleOption()
        option.initFrom(self)
        painter = QPainter(self)
        style = self.style()
        style.drawPrimitive(QStyle.PE_Widget, option, painter, self)

    def set_widgets_prop(self):
        self.webview.setObjectName("webview")

    def set_layouts_prop(self):
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)

        self.layout.addWidget(self.webview)
示例#15
0
    def __init__(self, main_window, items):
        super().__init__()

        vbox = QVBoxLayout()
        vbox.setSpacing(0)
        vbox.setContentsMargins(0, 0, 0, 0)
        self.setLayout(vbox)

        top_system_buttons = TopSystemButtons(main_window)
        vbox.addWidget(top_system_buttons)
        vbox.addStretch()
        hbox = QHBoxLayout()
        hbox.addSpacing(25)
        hbox.setSpacing(0)
        hbox.setContentsMargins(0, 0, 0, 0)
        vbox.addLayout(hbox)

        l = QLabel()
        hbox.addWidget(l)
        vbox.addStretch()
        vbox.addWidget(SelectMenu(main_window, items))

        main_window.communication.input_changed_signal.connect(l.setText)
        self.resizeEvent = functools.partial(main_window.resized, self,
                                             top_system_buttons)

        self.setGraphicsEffect(utils.get_shadow())
示例#16
0
 def __init__(self, parent = None):
     super(ItemContent, self).__init__(parent)
     layout = QVBoxLayout(self)
     layout.setContentsMargins(0, 0, 0, 20)
     layout.setSpacing(0)
     self.content = ItemVContent(self)
     layout.addWidget(self.content)
示例#17
0
class DocWindow(QWidget):
    app = None

    def __init__(self, app):
        super(DocWindow, self).__init__()
        DocWindow.app = app
        self.vlayout  = QVBoxLayout()
        self.view     = DocView()
        self.backbtn  = QPushButton('Back')
        self.closebtn = QPushButton('Close')
        self.vlayout.setContentsMargins(1, 1, 1, 1)
        self.vlayout.setSpacing(1)
        self.vlayout.addWidget(self.view)
        hlayout = QHBoxLayout()
        buttonbox = QWidget()
        buttonbox.setLayout(hlayout)
        self.vlayout.addWidget(buttonbox)
        hlayout.addWidget(self.closebtn)
        hlayout.addWidget(self.backbtn)
        self.closebtn.clicked.connect(self.hide)
        self.backbtn.clicked.connect(self.view.back)
        self.setLayout(self.vlayout)
        self.setWindowTitle('BlueSky documentation')

    def show_cmd_doc(self, cmd):
        if not cmd:
            cmd = 'Command-Reference'
        self.view.load(QUrl.fromLocalFile(QFileInfo('data/html/' + cmd.lower() + '.html').absoluteFilePath()))
示例#18
0
class LP_LibraryPanel(FFrame):
    def __init__(self, app, parent=None):
        super().__init__(parent)
        self._app = app

        self.header = LP_GroupHeader(self._app, '我的音乐')
        self.current_playlist_item = LP_GroupItem(self._app, '当前播放列表')
        self.current_playlist_item.set_img_text('◎')
        self._layout = QVBoxLayout(self)

        self.setObjectName('lp_library_panel')
        self.set_theme_style()
        self.setup_ui()

    def set_theme_style(self):
        theme = self._app.theme_manager.current_theme
        style_str = '''
            #{0} {{
                background: transparent;
            }}
        '''.format(self.objectName(),
                   theme.color3.name())
        self.setStyleSheet(style_str)

    def setup_ui(self):
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)

        self._layout.addSpacing(3)
        self._layout.addWidget(self.header)
        self._layout.addWidget(self.current_playlist_item)
示例#19
0
    def _create_layout(self, main_window):
        """
        Create main layout of widget.
        """

        layout = QVBoxLayout()
        self.setLayout(layout)
        layout.setContentsMargins(30, 10, 30, 10)
        layout.setSpacing(0)

        l = QLabel(_(self.model.__table__.name))
        l.setObjectName('title')
        layout.addWidget(l)

        scrollable = QVBoxLayout()
        for row in self._get_rows(self.model, main_window):
            for w in row:
                scrollable.addWidget(w)

        scrollable = utils.get_scrollable(scrollable)

        controls_layout = self._get_controls_layout(layout)

        layout.addWidget(scrollable)
        layout.addLayout(controls_layout)

        self.show()
        self.raise_()
        self.move((main_window.width() - self.width()) / 2, (main_window.height() - self.height()) / 2)
示例#20
0
class IconWidget(QWidget):
    new_window = pyqtSignal(str)
    clipboard = pyqtSignal(object)

    def __init__(self, parent=None, name="None", path="None"):
        super().__init__(parent)
        self.path = path
        self.name = name
        self.drag_started = False 
        self.mimetext = "application/x-icon"
        self.mpixmap = None
        self.layout = QVBoxLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        self.kind = self.what_kind(path, name)
        self.text = ClickableLabel(path=path, name=name)
        self.icon = ClickableIcon(path=path, name=name, parent=self)
        self.icon.clicked.connect(self._on_drag_started)
        self.icon.double_clicked.connect(self.open_window)
        self.layout.addWidget(self.icon)
        self.layout.addWidget(self.text)

    def what_kind(self, path, name):
        if os.path.isdir(os.path.join(path, name)):
            return "directory"
        return "file"

    def reset_selection(self):
        self.icon.selected = False
        self.icon.setAutoFillBackground(False)

    def getIconWidget(self):
        return self

    def getIcon(self):
        return self.icon

    def getText(self):
        return self.text

    def mouseMoveEvent(self, event):
        # if the left mouse button is used
        if self.drag_started:
            data = QByteArray()
            mime_data = QMimeData()
            mime_data.setData(self.mimetext, data)
            drag = QDrag(self) 
            drag.setMimeData(mime_data)
            drag.setPixmap(self.icon.get_icon())
            drag.setHotSpot(self.rect().topLeft())  # where do we drag from
            if drag.exec_(Qt.MoveAction):
                self.parent().icons.remove(self)
                self.deleteLater()

    def _on_drag_started(self):
        self.drag_started = True

    def open_window(self):
        self.reset_selection()
        self.new_window.emit(os.path.join(self.path, self.name))
示例#21
0
    def __init__(self):
        super().__init__()
        self.current_status = _STATUSBAR_STATE_SEARCH
        vbox = QVBoxLayout(self)
        title = QLabel(translations.TR_SEARCH_TITLE)
        font = title.font()
        font.setPointSize(9)
        title.setFont(font)
        vbox.addWidget(title)
        spacing = 3
        if settings.IS_MAC_OS:
            spacing = 0
        vbox.setSpacing(spacing)
        # Search Layout
        self._search_widget = SearchWidget()
        vbox.addWidget(self._search_widget)
        # Replace Layout
        self._replace_widget = ReplaceWidget()
        self._replace_widget.hide()
        vbox.addWidget(self._replace_widget)
        # Not configurable shortcuts
        short_esc_status = QShortcut(QKeySequence(Qt.Key_Escape), self)
        short_esc_status.activated.connect(self.hide_status_bar)

        IDE.register_service("status_bar", self)
    def test_should_resize_to_match_height_for_width_when_user_enters_text(self):
        size_hint     = self.auto_resizing_text_edit.sizeHint()
        parent_height = size_hint.height() + 200

        layout = QVBoxLayout()
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.auto_resizing_text_edit)
        layout.addStretch()

        parent = QWidget()
        self.auto_resizing_text_edit.setParent(parent)

        parent.resize(size_hint.width(), parent_height)
        parent.setLayout(layout)

        # The window needs to get shown for the size changes to be propagated to layout.
        # Show it minimized to avoid stealing focus from the console running the tests.
        parent.showMinimized()

        assert self.auto_resizing_text_edit.height(), size_hint.height()
        assert self.auto_resizing_text_edit.width(),  parent.width()

        self.auto_resizing_text_edit.setPlainText('a\nb\nc\d')
        new_height_hint = self.auto_resizing_text_edit.heightForWidth(self.auto_resizing_text_edit.width())
        application.processEvents()

        self.assertNotEqual(new_height_hint, size_hint.height())
        self.assertEqual(self.auto_resizing_text_edit.height(), new_height_hint)
        self.assertEqual(self.auto_resizing_text_edit.width(),  parent.width())
示例#23
0
class LeftPanelContainer(MScrollArea):
    def __init__(self, app, parent=None):
        super().__init__(parent)
        self._app = app

        self.left_panel = LeftPanel(self._app)
        self._layout = QVBoxLayout(self)  # no layout, no children
        self.setWidget(self.left_panel)  # set Widget connect to self(self is ScrollArea)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidgetResizable(True)  # Widget can resize

        self.setObjectName('c_left_panel_container')
        self.set_theme_style()
        self.setMinimumWidth(180)
        self.setMaximumWidth(221)

        self.setup_ui()

    def set_theme_style(self):
        theme = self._app.theme_manager.current_theme
        style_str = '''
            #{0} {{
                background: transparent;
                border: 0px;
                border-right: 3px inset {1};
            }}
        '''.format(self.objectName(),
                   theme.color0_light.name())
        self.setStyleSheet(style_str)

    def setup_ui(self):
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)
示例#24
0
class SongsTable_Container(FFrame):
    def __init__(self, app, parent=None):
        super().__init__(parent)
        self._app = app

        self.songs_table = None
        self.table_control = TableControl(self._app)
        self._layout = QVBoxLayout(self)
        self.setup_ui()

    def setup_ui(self):
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)

        self._layout.addWidget(self.table_control)

    def set_table(self, songs_table):
        if self.songs_table:
            self._layout.replaceWidget(self.songs_table, songs_table)
            self.songs_table.close()
            del self.songs_table
        else:
            self._layout.addWidget(songs_table)
            self._layout.addSpacing(10)
        self.songs_table = songs_table
示例#25
0
文件: ui.py 项目: leohazy/FeelUOwn
class LeftPanel(FFrame):
    def __init__(self, app, parent=None):
        super().__init__(parent)
        self._app = app

        self.library_panel = LP_LibraryPanel(self._app)
        self.playlists_panel = LP_PlaylistsPanel(self._app)

        self._layout = QVBoxLayout(self)
        self.setLayout(self._layout)
        self.setObjectName('c_left_panel')
        self.set_theme_style()
        self.setup_ui()

    def set_theme_style(self):
        theme = self._app.theme_manager.current_theme
        style_str = '''
            #{0} {{
                background: transparent;
            }}
        '''.format(self.objectName(),
                   theme.color5.name())
        self.setStyleSheet(style_str)

    def setup_ui(self):
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)

        self._layout.addWidget(self.library_panel)
        self._layout.addWidget(self.playlists_panel)
        self._layout.addStretch(1)
示例#26
0
class MyCheckBox(MFrame):
    def __init__(self, app, parent=None):
        super().__init__(parent)
        self._app = app

        # self.header = MLabel("请选择歌曲并确认", self._app)
        self._layout = QVBoxLayout(self)
        self.setLayout(self._layout)

        self.set_theme_style()
        self.setObjectName("my_checkbox")
        self.setup_ui()

    def set_theme_style(self):
        theme = self._app.theme_manager.current_theme
        style_str = '''
            #{0} {{
                background: {1};
            }}
        '''.format(self.objectName(),
                   theme.color0_light.name())
        self.setStyleSheet(style_str)

    def setup_ui(self):
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)

        # self._layout.addWidget(self.header)
        self._layout.addStretch(1)

    def add_item(self, checkbox):
        self._layout.addWidget(checkbox)
示例#27
0
class PlaylistCenterPanelContainer(MScrollArea):
    def __init__(self, app, parent=None):
        super().__init__(parent)
        self._app = app
        self.check_group = MyCheckBox(self._app)

        self.setObjectName('pc_container')
        self._layout = QVBoxLayout(self)
        self.setWidget(self.check_group)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setWidgetResizable(True)

        self.set_theme_style()
        self.setup_ui()

    def set_theme_style(self):
        theme = self._app.theme_manager.current_theme
        style_str = '''
            #{0} {{
                background: {1};
            }}
        '''.format(self.objectName(),
                   theme.color0_light.name())
        self.setStyleSheet(style_str)

    def setup_ui(self):
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)
class CoverArtBox(QWidget):
    def __init__(self, parent=None):
        super(CoverArtBox, self).__init__(parent)
        self._renderUI()

    def _renderUI(self):
        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)

        defaultAlbumCover = QtGui.QPixmap(':/left_sidebar_icons/default_album_cover.png')

        self.coverArt = CoverArt()
        self.coverArt.setPixmap(defaultAlbumCover)
        self.coverArt.setFrameShape(QFrame.Box)
        self.coverArt.setAlignment(Qt.AlignHCenter)
        self.coverArt.setSizePolicy(QSizePolicy.MinimumExpanding,
                                    QSizePolicy.MinimumExpanding)

        self.infoLabel = InformationLabel()
        self.coverArt.setSizePolicy(QSizePolicy.MinimumExpanding,
                                    QSizePolicy.Fixed)

        self.layout.addWidget(self.coverArt)
        self.layout.addWidget(self.infoLabel, 0, Qt.AlignBottom)

        self.setLayout(self.layout)

    @QtCore.pyqtSlot(str, str, bytes)
    def setCoverArtBox(self, title, artist, coverArt):
        self.coverArt.setCoverArt(coverArt)
        self.infoLabel.setInformation(title, artist)
示例#29
0
class LoginDialog(MDialog):
    def __init__(self, app, parent=None):
        super().__init__(parent)
        self._app = app

        self.username_input = LineInput(self)
        self.password_input = LineInput(self)
        self.password_input.setEchoMode(MQLineEdit.Password)
        self.login_btn = MButton('登录', self)
        self.register_btn = MButton('注册', self)
        self._login_frame = MFrame()
        self._login_layout = QHBoxLayout(self._login_frame)
        self._layout = QVBoxLayout(self)

        self.username_input.setPlaceholderText('用户名或管理员backdoor登录')
        self.password_input.setPlaceholderText('密码')

        self.setObjectName('login_dialog')
        self.set_theme_style()
        self.setup_ui()

    def setup_ui(self):
        self.setFixedWidth(200)

        self._login_layout.setContentsMargins(0, 0, 0, 0)
        self._login_layout.setSpacing(1)
        self._login_layout.addWidget(self.login_btn)
        self._login_layout.addWidget(self.register_btn)

        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)
        self._layout.addWidget(self.username_input)
        self._layout.addWidget(self.password_input)
        self._layout.addWidget(self._login_frame)
示例#30
0
    def __init__(self, font, *args):
        QWidget.__init__(self, *args)
        self._browser = QTextEdit(self)
        self._browser.setReadOnly(True)
        document = self._browser.document()
        document.setDefaultStyleSheet(document.defaultStyleSheet() +
                                      "span {white-space:pre;}")

        self._browser.setFont(font)
        self._edit = _TextEdit(self, font)

        lowLevelWidget = self._edit.focusProxy()
        if lowLevelWidget is None:
            lowLevelWidget = self._edit
        lowLevelWidget.installEventFilter(self)

        self._edit.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
        self.setFocusProxy(self._edit)

        layout = QVBoxLayout(self)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self._browser)
        layout.addWidget(self._edit)

        self._history = ['']  # current empty line
        self._historyIndex = 0

        self._edit.setFocus()
示例#31
0
文件: siacle.py 项目: ykv001/PyQt5
    def initUI(self):

        fuenteSiacle = self.font()
        fuenteSiacle.setBold(True)
        fuenteSiacle.setPointSize(12)

        # ================= FRAME PANEL DE CONTROL ===================

        paletaBotones = self.palette()
        paletaBotones.setColor(QPalette.Background, QColor("#2EFEC8"))

        frameBotones = QFrame()
        frameBotones.setFrameStyle(QFrame.NoFrame)
        frameBotones.setAutoFillBackground(True)
        frameBotones.setPalette(paletaBotones)
        frameBotones.setFixedWidth(220)

        # ============================================================

        paletaPanel = self.palette()
        paletaPanel.setBrush(QPalette.Background,
                             QBrush(QColor(255, 90, 0), Qt.SolidPattern))
        paletaPanel.setColor(QPalette.Foreground, Qt.white)

        labelSiacle = QLabel("PANEL DE CONTROL", frameBotones)
        labelSiacle.setAlignment(Qt.AlignCenter)
        labelSiacle.setFont(fuenteSiacle)
        labelSiacle.setAutoFillBackground(True)
        labelSiacle.setPalette(paletaPanel)
        labelSiacle.setFixedSize(220, 46)
        labelSiacle.move(0, 0)

        # ============================================================

        botonNuevo = Boton(frameBotones)
        botonNuevo.setText(" Nuevo")
        botonNuevo.setToolTip("Nuevo cliente")
        botonNuevo.setCursor(Qt.PointingHandCursor)
        botonNuevo.move(-2, 45)

        botonActualizar = Boton(frameBotones)
        botonActualizar.setText(" Actualizar")
        botonActualizar.setToolTip("Actualizar cliente")
        botonActualizar.setCursor(Qt.PointingHandCursor)
        botonActualizar.move(-2, 82)

        botonEliminar = Boton(frameBotones)
        botonEliminar.setText(" Eliminar")
        botonEliminar.setToolTip("Eliminar cliente")
        botonEliminar.setCursor(Qt.PointingHandCursor)
        botonEliminar.move(-2, 119)

        botonLimpiar = Boton(frameBotones)
        botonLimpiar.setText(" Limpiar tabla")
        botonLimpiar.setToolTip("Limpiar tabla")
        botonLimpiar.setCursor(Qt.PointingHandCursor)
        botonLimpiar.move(-2, 156)

        # ============================================================

        paletaSuscribete = self.palette()
        paletaSuscribete.setBrush(
            QPalette.Background, QBrush(QColor(135, 206, 250),
                                        Qt.SolidPattern))

        fuenteSuscribete = self.font()
        fuenteSuscribete.setBold(True)
        fuenteSuscribete.setFamily("Arial")
        fuenteSuscribete.setPointSize(11)

        labelSuscribete = QLabel(
            "<a href='https://www.youtube.com/c/AndresNiñoPython?"
            "sub_confirmation=1'>SUSCRIBETE.</a>", frameBotones)
        labelSuscribete.setAlignment(Qt.AlignCenter)
        labelSuscribete.setOpenExternalLinks(True)
        labelSuscribete.setFont(fuenteSuscribete)
        labelSuscribete.setAutoFillBackground(True)
        labelSuscribete.setPalette(paletaSuscribete)
        labelSuscribete.setFixedSize(220, 46)
        labelSuscribete.move(0, 210)

        # ============ FRAME BIENVENIDO - CONFIGURACIÓN ==============

        paletaFrame = self.palette()
        paletaFrame.setColor(QPalette.Background, QColor("blue"))

        frameBienvenido = QFrame()
        frameBienvenido.setFrameStyle(QFrame.NoFrame)
        frameBienvenido.setAutoFillBackground(True)
        frameBienvenido.setPalette(paletaFrame)
        frameBienvenido.setFixedHeight(46)

        # ============================================================

        paletaTitulo = self.palette()
        paletaTitulo.setColor(QPalette.Foreground, Qt.yellow)

        labelBienvenido = QLabel("BIENVENIDO A SIACLE")
        labelBienvenido.setAlignment(Qt.AlignCenter)
        labelBienvenido.setFont(fuenteSiacle)
        labelBienvenido.setPalette(paletaTitulo)

        botonConfiguracion = QPushButton()
        botonConfiguracion.setIcon(QIcon("Imagenes/configuracion.png"))
        botonConfiguracion.setIconSize(QSize(24, 24))
        botonConfiguracion.setToolTip("Configurar Siacle")
        botonConfiguracion.setCursor(Qt.PointingHandCursor)
        botonConfiguracion.setFixedWidth(36)

        # Primero, creamos los widgets que queremos en el diseño. Luego, creamos el
        # objeto QHBoxLayout y agregamos los widgets en el diseño. Finalmente, llamamos
        # a QWidget.setLayout(diseño) para instalar el objeto QHBoxLayout en el widget.

        disenioFrame = QHBoxLayout()
        disenioFrame.addWidget(labelBienvenido, Qt.AlignCenter)
        disenioFrame.addStretch()
        disenioFrame.addWidget(botonConfiguracion)
        disenioFrame.setContentsMargins(0, 0, 5, 0)

        frameBienvenido.setLayout(disenioFrame)

        # ============================================================

        self.buscarLineEdit = QLineEdit()
        self.buscarLineEdit.setObjectName("Enter")
        self.buscarLineEdit.setPlaceholderText("Nombre del cliente")
        self.buscarLineEdit.setMinimumSize(200, 26)

        botonBuscar = QPushButton("Buscar")
        botonBuscar.setObjectName("Buscar")
        botonBuscar.setCursor(Qt.PointingHandCursor)
        botonBuscar.setMinimumSize(60, 26)

        separadorTodos = QFrame()
        separadorTodos.setFrameShape(QFrame.VLine)
        separadorTodos.setFrameShadow(QFrame.Raised)
        separadorTodos.setFixedSize(1, 26)

        botonTodos = QPushButton("Todos")
        botonTodos.setObjectName("Todos")
        botonTodos.setCursor(Qt.PointingHandCursor)
        botonTodos.setMinimumSize(60, 26)

        nombreColumnas = ("Id", "Nombre", "Apellido", "Sexo",
                          "Fecha de nacimiento", "País", "Teléfono o celular")

        menuMostrarOcultar = QMenu()
        for indice, columna in enumerate(nombreColumnas, start=0):
            accion = QAction(columna, menuMostrarOcultar)
            accion.setCheckable(True)
            accion.setChecked(True)
            accion.setData(indice)

            menuMostrarOcultar.addAction(accion)

        botonMostrarOcultar = QPushButton("Motrar/ocultar columnas")
        botonMostrarOcultar.setCursor(Qt.PointingHandCursor)
        botonMostrarOcultar.setMenu(menuMostrarOcultar)
        botonMostrarOcultar.setMinimumSize(180, 26)

        # Crear el objeto QHBoxLayout y agregar los widgets en el diseño.

        disenioBuscar = QHBoxLayout()
        disenioBuscar.setSpacing(10)
        disenioBuscar.addWidget(self.buscarLineEdit)
        disenioBuscar.addWidget(botonBuscar)
        disenioBuscar.addWidget(separadorTodos)
        disenioBuscar.addWidget(botonTodos)
        disenioBuscar.addWidget(botonMostrarOcultar)

        # =================== WIDGET  QTableWidget ===================

        self.tabla = QTableWidget()

        # Deshabilitar edición
        self.tabla.setEditTriggers(QAbstractItemView.NoEditTriggers)

        # Deshabilitar el comportamiento de arrastrar y soltar
        self.tabla.setDragDropOverwriteMode(False)

        # Seleccionar toda la fila
        self.tabla.setSelectionBehavior(QAbstractItemView.SelectRows)

        # Seleccionar una fila a la vez
        self.tabla.setSelectionMode(QAbstractItemView.SingleSelection)

        # Especifica dónde deben aparecer los puntos suspensivos "..." cuando se muestran
        # textos que no encajan
        self.tabla.setTextElideMode(Qt.ElideRight)  # Qt.ElideNone

        # Establecer el ajuste de palabras del texto
        self.tabla.setWordWrap(False)

        # Deshabilitar clasificación
        self.tabla.setSortingEnabled(False)

        # Establecer el número de columnas
        self.tabla.setColumnCount(7)

        # Establecer el número de filas
        self.tabla.setRowCount(0)

        # Alineación del texto del encabezado
        self.tabla.horizontalHeader().setDefaultAlignment(Qt.AlignHCenter
                                                          | Qt.AlignVCenter
                                                          | Qt.AlignCenter)

        # Deshabilitar resaltado del texto del encabezado al seleccionar una fila
        self.tabla.horizontalHeader().setHighlightSections(False)

        # Hacer que la última sección visible del encabezado ocupa todo el espacio disponible
        self.tabla.horizontalHeader().setStretchLastSection(True)

        # Ocultar encabezado vertical
        self.tabla.verticalHeader().setVisible(False)

        # Dibujar el fondo usando colores alternados
        self.tabla.setAlternatingRowColors(True)

        # Establecer altura de las filas
        self.tabla.verticalHeader().setDefaultSectionSize(20)

        # self.tabla.verticalHeader().setHighlightSections(True)

        # Establecer las etiquetas de encabezado horizontal usando etiquetas
        self.tabla.setHorizontalHeaderLabels(nombreColumnas)

        # Menú contextual
        self.tabla.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tabla.customContextMenuRequested.connect(self.menuContextual)

        # Establecer ancho de las columnas
        for indice, ancho in enumerate((80, 240, 240, 140, 150, 130), start=0):
            self.tabla.setColumnWidth(indice, ancho)

    # ============================================================

        disenioBuscarTabla = QVBoxLayout()
        disenioBuscarTabla.addLayout(disenioBuscar)
        disenioBuscarTabla.addWidget(self.tabla)
        disenioBuscarTabla.setSpacing(8)
        disenioBuscarTabla.setContentsMargins(10, 10, 10, 0)

        # ===================== LAYOUT DERECHO =======================

        disenioDerecho = QVBoxLayout()
        disenioDerecho.addWidget(frameBienvenido)
        disenioDerecho.addLayout(disenioBuscarTabla)
        disenioDerecho.setContentsMargins(0, 0, 0, 0)

        # ====================== LAYOUT FINAL ======================

        disenioFinal = QGridLayout()
        disenioFinal.addWidget(frameBotones, 0, 0)
        disenioFinal.addLayout(disenioDerecho, 0, 1)
        disenioFinal.setSpacing(0)
        disenioFinal.setContentsMargins(0, 0, 0, 0)

        self.setLayout(disenioFinal)

        # ========= GUARDAR INFORMACIÓN EN EL PORTAPAPELES =========

        self.copiarInformacion = QApplication.clipboard()
示例#32
0
class TemplateMultipleVariablesDialog(QDialog):
    """
    Class implementing a dialog for entering multiple template variables.
    """
    def __init__(self, variables, parent=None):
        """
        Constructor
        
        @param variables list of template variable names (list of strings)
        @param parent parent widget of this dialog (QWidget)
        """
        super(TemplateMultipleVariablesDialog, self).__init__(parent)

        self.TemplateMultipleVariablesDialogLayout = QVBoxLayout(self)
        self.TemplateMultipleVariablesDialogLayout.setContentsMargins(
            6, 6, 6, 6)
        self.TemplateMultipleVariablesDialogLayout.setSpacing(6)
        self.TemplateMultipleVariablesDialogLayout.setObjectName(
            "TemplateMultipleVariablesDialogLayout")
        self.setLayout(self.TemplateMultipleVariablesDialogLayout)

        # generate the scrollarea
        self.variablesView = QScrollArea(self)
        self.variablesView.setObjectName("variablesView")
        self.TemplateMultipleVariablesDialogLayout.addWidget(
            self.variablesView)

        self.variablesView.setWidgetResizable(True)
        self.variablesView.setFrameStyle(QFrame.NoFrame)

        self.top = QWidget(self)
        self.variablesView.setWidget(self.top)
        self.grid = QGridLayout(self.top)
        self.grid.setContentsMargins(0, 0, 0, 0)
        self.grid.setSpacing(6)
        self.top.setLayout(self.grid)

        # populate the scrollarea with labels and text edits
        self.variablesEntries = {}
        row = 0
        for var in variables:
            label = QLabel("{0}:".format(var), self.top)
            self.grid.addWidget(label, row, 0, Qt.Alignment(Qt.AlignTop))
            if var.find(":") >= 0:
                formatStr = var[1:-1].split(":")[1]
                if formatStr in ["ml", "rl"]:
                    t = QTextEdit(self.top)
                    t.setTabChangesFocus(True)
                else:
                    t = QLineEdit(self.top)
            else:
                t = QLineEdit(self.top)
            self.grid.addWidget(t, row, 1)
            self.variablesEntries[var] = t
            row += 1
        # add a spacer to make the entries aligned at the top
        spacer = QSpacerItem(20, 40, QSizePolicy.Minimum,
                             QSizePolicy.Expanding)
        self.grid.addItem(spacer, row, 1)
        self.variablesEntries[variables[0]].setFocus()
        self.top.adjustSize()

        # generate the buttons
        layout1 = QHBoxLayout()
        layout1.setContentsMargins(0, 0, 0, 0)
        layout1.setSpacing(6)
        layout1.setObjectName("layout1")

        spacer1 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                              QSizePolicy.Minimum)
        layout1.addItem(spacer1)

        self.okButton = QPushButton(self)
        self.okButton.setObjectName("okButton")
        self.okButton.setDefault(True)
        layout1.addWidget(self.okButton)

        self.cancelButton = QPushButton(self)
        self.cancelButton.setObjectName("cancelButton")
        layout1.addWidget(self.cancelButton)

        spacer2 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                              QSizePolicy.Minimum)
        layout1.addItem(spacer2)

        self.TemplateMultipleVariablesDialogLayout.addLayout(layout1)

        # set the texts of the standard widgets
        self.setWindowTitle(self.tr("Enter Template Variables"))
        self.okButton.setText(self.tr("&OK"))
        self.cancelButton.setText(self.tr("&Cancel"))

        # polish up the dialog
        self.resize(QSize(400, 480).expandedTo(self.minimumSizeHint()))

        self.okButton.clicked.connect(self.accept)
        self.cancelButton.clicked.connect(self.reject)

    def getVariables(self):
        """
        Public method to get the values for all variables.
        
        @return dictionary with the variable as a key and its value (string)
        """
        values = {}
        for var, textEdit in list(self.variablesEntries.items()):
            try:
                values[var] = textEdit.text()
            except AttributeError:
                values[var] = textEdit.toPlainText()
        return values
示例#33
0
class ArretWindowListRaison(MondonWidget):
    DELETE_RAISON_SIGNAL = pyqtSignal()
    # _____DEFINITION CONSTANTE CLASS_____
    WIDTH_TYPE = 120
    HEIGHT_LINE = 24
    SIZE = QSize(24, 24)
    VBOX_SPACING = 5
    VBOX_MARGIN = QMargins(10, 10, 10, 10)
    """
    Bloc de visualisation des raison de la window arret
    Affiche la liste des raisons ajouter a l'arret
    """
    def __init__(self, arret, parent=None):
        super(ArretWindowListRaison, self).__init__(parent=parent)
        self.set_background_color(color_bleu_gris)
        self.arret = arret
        self.list_layout_raison = {}
        self.radio_button_manager = None
        # _____INITIALISATION WIDGET_____
        self.vbox = QVBoxLayout(self)
        self.vbox.setContentsMargins(self.VBOX_MARGIN)
        self.vbox.setSpacing(self.VBOX_SPACING)
        self.initial_line = self.create_initial_line()
        self.update_widget()

    def update_widget(self):
        # On reinitialise le layout et la liste des layouts
        clear_layout(self.vbox)
        self.list_layout_raison = {}
        # Si la liste de raison est vide
        if len(self.arret.raisons) == 0:
            self.initial_line = self.create_initial_line()
            # On ajout la ligne pas de raison sélectionné
            self.vbox.addLayout(self.initial_line)
        else:
            index = 0
            first_type = None
            self.radio_button_manager = RadioButtonManager()
            self.radio_button_manager.ON_RADIO_BUTTON_CHANGED_SIGNAL.connect(
                self.on_radio_button_changed)
            for raison in self.arret.raisons:
                if index == 0:
                    raison.update_to_raison_primaire()
                if not first_type:
                    first_type = raison.type
                line_raison = self.create_line_raison(raison, first_type)
                self.list_layout_raison[index] = line_raison
                self.vbox.addLayout(line_raison)
                index += 1
        self.setLayout(self.vbox)

    def on_radio_button_changed(self, index_selected):
        list_raison = self.arret.raisons
        index = 0
        for raison in list_raison:
            if index_selected == index:
                raison.update_to_raison_primaire()
            else:
                raison.remove_to_raison_primaire()
            index += 1
        # Demande a l'object arret de trier la liste des raisons
        self.arret.raison_store()
        self.update_widget()

    def create_initial_line(self):
        """
        S'occupe de créer une ligne si l'arret contient aucune raison
        :return: Le layout de la ligne
        """
        # Création widget horizontal
        hbox = QHBoxLayout()
        # Création du label
        initial_label = QLabel("Aucune raison renseignée pour cette arrêt")
        initial_label.setFixedHeight(self.HEIGHT_LINE)
        initial_label.setAlignment(Qt.AlignCenter)
        # On met le label en rouge
        initial_label.setStyleSheet(red_title_label_stylesheet)
        # On ajoute le label au layout
        hbox.addWidget(initial_label)
        return hbox

    def create_line_raison(self, raison, first_type):
        """
        S'occupe de créer une ligne associé a une raison
        :return: Le layout de la ligne
        """
        hbox = QHBoxLayout()
        # On met le label et la croix en couleur en fonction du type
        if raison.type == "Prévu":
            label_stylesheet = blue_title_label_stylesheet
            bt_cross_stylesheet = button_blue_cross_stylesheet
        elif raison.type == "Imprévu":
            label_stylesheet = red_title_label_stylesheet
            bt_cross_stylesheet = button_red_cross_stylesheet
        else:
            label_stylesheet = gray_title_label_stylesheet
            bt_cross_stylesheet = button_gray_cross_stylesheet
        # On regarde si le type est égale au first type pour ajouter le radiobutton si besoin
        if raison.type == first_type and raison.type != "Nettoyage":
            radio_bt = RadioButton(parent=self)
            radio_bt.is_selected = raison.primaire == 1
            radio_bt.setStyleSheet(bt_cross_stylesheet)
            self.radio_button_manager.add(radio_bt)
            radio_bt.setFixedSize(self.HEIGHT_LINE, self.HEIGHT_LINE)
            hbox.addWidget(radio_bt, alignment=Qt.AlignVCenter)
        # Création du label type
        type_label = QLabel(raison.type)
        type_label.setStyleSheet(label_stylesheet)
        type_label.setAlignment(Qt.AlignCenter)
        type_label.setFixedWidth(self.WIDTH_TYPE)
        type_label.setFixedHeight(self.HEIGHT_LINE)
        # On ajoute le label au layout
        hbox.addWidget(type_label)
        # Création du label raison
        raison_label = QLabel(raison.raison)
        # On met le label en couleur en fonction du type et on définit la largeur
        raison_label.setStyleSheet(label_stylesheet)
        raison_label.setFixedHeight(self.HEIGHT_LINE)
        # On ajoute le label au layout
        hbox.addWidget(raison_label)
        # On crée un bouton pour supprimer la ligne
        bt_cross = PixmapButton(parent=self)
        bt_cross.setFixedSize(self.HEIGHT_LINE, self.HEIGHT_LINE)
        bt_cross.addImage("commun/assets/images/white_cross.png")
        bt_cross.setStyleSheet(bt_cross_stylesheet)
        bt_cross.clicked.connect(
            lambda: self.delete_line_raison(raison.raison))
        # On ajoute le bouton au layout
        hbox.addWidget(bt_cross)
        hbox.setSpacing(0)
        return hbox

    def delete_line_raison(self, raison):
        """
        S'occupe de supprimer une ligne raison
        :param raison: La raison a supprimer
        """
        # Supprime l'object Raison dans l'object Arret
        self.arret.remove_raison(raison)
        # Réinitialise la liste des layout raison
        self.update_widget()
        self.DELETE_RAISON_SIGNAL.emit()
class _MainContainer(QWidget):

    currentEditorChanged = pyqtSignal("QString")
    fileOpened = pyqtSignal("QString")
    fileSaved = pyqtSignal("QString")
    runFile = pyqtSignal("QString")
    showFileInExplorer = pyqtSignal("QString")
    addToProject = pyqtSignal("QString")
    allFilesClosed = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAcceptDrops(True)
        self._vbox = QVBoxLayout(self)
        self._vbox.setContentsMargins(0, 0, 0, 0)
        self._vbox.setSpacing(0)
        self.stack = QStackedLayout()
        self.stack.setStackingMode(QStackedLayout.StackAll)
        self._vbox.addLayout(self.stack)
        self.splitter = dynamic_splitter.DynamicSplitter()
        self._files_handler = files_handler.FilesHandler(self)

        # Code Navigation
        self.__code_back = []
        self.__code_forward = []
        self.__operations = {
            0: self._navigate_code_jumps,
            1: self._navigate_bookmarks
        }
        # QML UI
        self._add_file_folder = add_file_folder.AddFileFolderWidget(self)

        if settings.SHOW_START_PAGE:
            self.show_start_page()

        IDE.register_service("main_container", self)
        # Register signals connections
        connections = ({
            "target": "main_container",
            "signal_name": "updateLocator",
            "slot": self._explore_code
        }, {
            "target": "filesystem",
            "signal_name": "projectOpened",
            "slot": self._explore_code
        }, {
            "target": "projects_explore",
            "signal_name": "updateLocator",
            "slot": self._explore_code
        })

        IDE.register_signals("main_container", connections)

        esc_sort = QShortcut(QKeySequence(Qt.Key_Escape), self)
        esc_sort.activated.connect(self._set_focus_to_editor)

        fhandler_short = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_Tab), self)
        fhandler_short.activated.connect(self.show_files_handler)
        # Added for set language
        # self._setter_language = set_language.SetLanguageFile()

    def install(self):
        ninjaide = IDE.get_service("ide")
        ninjaide.place_me_on("main_container", self, "central", top=True)

        self.combo_area = combo_editor.ComboEditor(original=True)
        self.combo_area.allFilesClosed.connect(self._files_closed)
        self.combo_area.allFilesClosed.connect(
            lambda: self.allFilesClosed.emit())
        self.splitter.add_widget(self.combo_area)
        self.add_widget(self.splitter)
        # self.current_widget = self.combo_area
        # Code Locator
        self._code_locator = locator_widget.LocatorWidget(ninjaide)

        ui_tools.install_shortcuts(self, actions.ACTIONS, ninjaide)
        self.fileSaved.connect(self._show_message_about_saved)

    def run_file(self, filepath):
        self.runFile.emit(filepath)

    def _show_file_in_explorer(self, filepath):
        self.showFileInExplorer.emit(filepath)

    def _add_to_project(self, filepath):
        self.addToProject.emit(filepath)

    def _show_message_about_saved(self, message):
        if settings.NOTIFICATION_ON_SAVE:
            editor_widget = self.get_current_editor()
            indicator.Indicator.show_text(editor_widget, message)

    def show_files_handler(self):
        self._files_handler.next_item()

    def hide_files_handler(self):
        self._files_handler.hide()

    def import_from_everywhere(self):
        """Insert an import line from any place in the editor."""

        editorWidget = self.get_current_editor()
        if editorWidget:
            dialog = from_import_dialog.FromImportDialog(editorWidget, self)
            dialog.show()

    def navigate_code_history(self, operation, forward):
        self.__operations[operation](forward)

    def _navigate_code_jumps(self, forward=False):
        """Navigate between the jump points"""

        node = None
        if not forward and self.__code_back:
            if len(self.__code_back) == 1:
                return
            node = self.__code_back.pop()
            self.__code_forward.append(node)
            node = self.__code_back[-1]
        elif forward and self.__code_forward:
            node = self.__code_forward.pop()
            self.__code_back.append(node)
        if node is not None:
            filename = node[0]
            line, col = node[1]
            self.open_file(filename, line, col)

    def _navigate_bookmarks(self, forward=True):
        """Navigate between the bookmarks"""

        current_editor = self.get_current_editor()
        current_editor.navigate_bookmarks(forward=forward)

    def _set_focus_to_editor(self):
        status_bar = IDE.get_service("status_bar")
        tools_doock = IDE.get_service("tools_dock")
        editor_widget = self.get_current_editor()
        if status_bar.isVisible() and tools_doock.isVisible():
            status_bar.hide_status_bar()
        elif tools_doock.isVisible():
            tools_doock._hide()
        elif status_bar.isVisible():
            status_bar.hide_status_bar()
        if editor_widget is not None:
            editor_widget.reset_selections()

    def split_assistance(self):
        editor_widget = self.get_current_editor()
        if editor_widget is not None:
            split_widget = split_orientation.SplitOrientation(self)
            split_widget.show()

    def show_dialog(self, widget):
        self.add_widget(widget)
        self.stack.setCurrentWidget(widget)

    def show_split(self, orientation_vertical=False):
        orientation = Qt.Horizontal
        if orientation_vertical:
            orientation = Qt.Vertical
        self.combo_area.split_editor(orientation)

    def show_locator(self):
        """Show the Locator Widget"""

        if not self._code_locator.isVisible():
            self._code_locator.show()

    def _explore_code(self):
        """Update locator metadata for the current projects"""

        self._code_locator.explore_code()

    def current_editor_changed(self, filename):
        """Notify the new filename of the current editor"""

        if filename is None:
            filename = translations.TR_NEW_DOCUMENT
        self.currentEditorChanged.emit(filename)

    def get_current_editor(self):
        current_widget = self.combo_area.current_editor()
        if isinstance(current_widget, editor.NEditor):
            return current_widget
        return None

    def open_file(self, filename='', line=-1, col=0, ignore_checkers=False):
        logger.debug("Will try to open %s" % filename)
        if not filename:
            logger.debug("Has no filename")
            if settings.WORKSPACE:
                directory = settings.WORKSPACE
            else:
                directory = os.path.expanduser("~")
                editor_widget = self.get_current_editor()
                ninjaide = IDE.get_service("ide")
                current_project = ninjaide.get_current_project()
                # TODO: handle current project in NProject
                if current_project is not None:
                    directory = current_project.full_path
                elif editor_widget is not None and editor_widget.file_path:
                    directory = file_manager.get_folder(
                        editor_widget.file_path)
            filenames = QFileDialog.getOpenFileNames(
                self,
                "Open File",  # FIXME: translations
                directory,
                settings.get_supported_extensions_filter())[0]
        else:
            logger.debug("Has filename")
            filenames = [filename]
        if not filenames:
            return
        for filename in filenames:
            image_extensions = ("png", "jpg", "jpeg", "bmp", "gif")
            if file_manager.get_file_extension(filename) in image_extensions:
                logger.debug("Will open as image")
                self.open_image(filename)
            else:
                logger.debug("Will try to open: %s" % filename)
                self.__open_file(filename,
                                 line,
                                 col,
                                 ignore_checkers=ignore_checkers)

    def __open_file(self, filename, line, col, ignore_checkers=False):
        try:
            editor_widget = self.add_editor(filename)
            if line != -1:
                editor_widget.go_to_line(line, col)
            self.currentEditorChanged.emit(filename)
        except file_manager.NinjaIOException as reason:
            QMessageBox.information(
                self,
                "The file couldn't be open",  # FIXME: translations
                str(reason))
            logger.error("The file %s couldn't be open" % filename)

    def open_image(self, filename):
        for index in range(self.combo_area.stacked.count()):
            widget = self.combo_area.stacked.widget(index)
            if isinstance(widget, image_viewer.ImageViewer):
                if widget.image_filename == filename:
                    logger.debug("Image already open")
                    self.combo_area._set_current(neditable=None, index=index)
                    return
        viewer = image_viewer.ImageViewer(filename)
        self.combo_area.add_image_viewer(viewer)
        self.stack.setCurrentWidget(self.splitter)

    def autosave_file(self):
        for neditable in self.combo_area.bar.get_editables():
            neditable.autosave_file()

    def save_file(self, editor_widget=None):
        if editor_widget is None:
            # This may return None if there is not editor present
            editor_widget = self.get_current_editor()
        if editor_widget is None:
            return False
        # Ok, we have an editor instance
        # Save to file only if editor really was modified
        if editor_widget.is_modified:
            try:
                if editor_widget.nfile.is_new_file or \
                        not editor_widget.nfile.has_write_permission():
                    return self.save_file_as(editor_widget)
                # FIXME: beforeFileSaved.emit
                if settings.REMOVE_TRAILING_SPACES:
                    helpers.remove_trailing_spaces(editor_widget)
                # FIXME: new line at end
                if settings.ADD_NEW_LINE_AT_EOF:
                    helpers.insert_block_at_end(editor_widget)
                # Save content
                editor_widget.neditable.save_content()
                # FIXME: encoding
                # FIXME: translations
                self.fileSaved.emit("File Saved: %s" % editor_widget.file_path)
                return True
            except Exception as reason:
                logger.error("Save file error: %s" % reason)
                QMessageBox.information(self, "Save Error",
                                        "The file could't be saved!")
            return False

    def save_file_as(self, editor_widget=None):
        force = False
        if editor_widget is None:
            # We invoque from menu
            editor_widget = self.get_current_editor()
            if editor_widget is None:
                # We haven't editor in main container
                return False
            force = True
        try:
            filters = "(*.py);;(*.*)"
            if editor_widget.file_path is not None:  # Existing file
                extension = file_manager.get_file_extension(
                    editor_widget.file_path)
                if extension != 'py':
                    filters = "(*.%s);;(*.py);;(*.*)" % extension
                save_folder = self._get_save_folder(editor_widget.file_path)
            else:
                save_folder = settings.WORKSPACE

            filename = QFileDialog.getSaveFileName(self, "Save File",
                                                   save_folder, filters)[0]
            if not filename:
                return False
            # FIXME: remove trailing spaces
            extension = file_manager.get_file_extension(filename)
            if not extension:
                filename = "%s.%s" % (filename, "py")
            editor_widget.neditable.save_content(path=filename, force=force)
            # self._setter_language.set_language_from_extension(extension)
            self.fileSaved.emit("File Saved: {}".format(filename))
            self.currentEditorChanged.emit(filename)
            return True
        except file_manager.NinjaFileExistsException as reason:
            QMessageBox.information(
                self, "File Already Exists",
                "Invalid Path: the file '%s' already exists." %
                reason.filename)
        except Exception as reason:
            logger.error("save_file_as: %s", reason)
            QMessageBox.information(self, "Save Error",
                                    "The file couldn't be saved!")
        return False

    def save_project(self, project_path):
        """Save all files in the project path"""
        for neditable in self.combo_area.bar.get_editables():
            file_path = neditable.file_path
            if file_manager.belongs_to_folder(project_path, file_path):
                neditable.save_content()

    def _get_save_folder(self, filename):
        """Returns the root directory of the 'Main Project'
        or the home folder"""

        ninjaide = IDE.get_service("ide")
        current_project = ninjaide.get_current_project()
        if current_project is not None:
            return current_project.path
        return os.path.expanduser("~")

    def close_file(self):
        self.combo_area.close_current_file()

    def add_editor(self, filename=None):
        ninjaide = IDE.get_service("ide")
        editable = ninjaide.get_or_create_editable(filename)

        editable.canBeRecovered.connect(
            lambda: self.combo_area.info_bar.show_message(msg_type="recovery"))

        if editable.editor:
            # If already open
            logger.debug("%s is already open" % filename)
            self.combo_area.set_current(editable)
            return self.combo_area.current_editor()
        else:
            pass

        editor_widget = self.create_editor_from_editable(editable)
        # editor_widget.set_language()
        # Add the tab
        keep_index = (self.splitter.count() > 1
                      and self.combo_area.stacked.count() > 0)
        self.combo_area.add_editor(editable, keep_index)
        # Emit a signal about the file open
        self.fileOpened.emit(filename)

        if keep_index:
            self.combo_area.set_current(editable)

        self.stack.setCurrentWidget(self.splitter)
        editor_widget.setFocus()
        editor_widget.register_syntax_for(editable.language())
        return editor_widget

    def create_editor_from_editable(self, editable):
        neditor = editor.create_editor(editable)
        neditor.zoomChanged.connect(self._show_zoom_indicator)
        neditor.destroyed.connect(self.__on_editor_destroyed)
        neditor.addBackItemNavigation.connect(self.add_back_item_navigation)
        # editable.fileSaved.connect(self._editor_tab)
        return neditor

    def add_back_item_navigation(self):
        editor_widget = self.get_current_editor()
        if editor_widget is not None:
            item = (editor_widget.file_path, editor_widget.cursor_position)
            if item not in self.__code_back:
                self.__code_back.append(item)
                # self.__code_forward.clear()

    def _show_zoom_indicator(self, zoom):
        neditor = self.get_current_editor()
        indicator.Indicator.show_text(neditor, "Zoom: {} %".format(str(zoom)))

    @pyqtSlot()
    def __on_editor_destroyed(self):
        indicator.Indicator.instance = None

    def add_widget(self, widget):
        self.stack.addWidget(widget)

    def show_start_page(self):
        """Show Start Page widget in main container"""

        startp = self.stack.widget(0)
        if isinstance(startp, start_page.StartPage):
            self.stack.setCurrentIndex(0)
        else:
            startp = start_page.StartPage(parent=self)
            startp.newFile.connect(self.add_editor)
            self.stack.insertWidget(0, startp)
            self.stack.setCurrentIndex(0)

    def _files_closed(self):
        if settings.SHOW_START_PAGE:
            self.show_start_page()

    def add_status_bar(self, status_bar):
        self._vbox.addWidget(status_bar)

    def create_file(self, base_path, project_path):
        self._add_file_folder.create_file(base_path, project_path)

    def create_folder(self, base_path, project_path):
        self._add_file_folder.create_folder(base_path, project_path)

    def restyle_editor(self):
        neditables = self.combo_area.bar.get_editables()
        for neditable in neditables:
            neditable.editor.restyle()

    def zoom_in_editor(self):
        """Increase the font size in the current editor"""

        editor_widget = self.get_current_editor()
        if editor_widget is not None:
            editor_widget.zoom(1.)

    def zoom_out_editor(self):
        """Decrease the font size in the current editor"""

        editor_widget = self.get_current_editor()
        if editor_widget is not None:
            editor_widget.zoom(-1.)

    def reset_zoom_editor(self):
        """Reset the to original font size in the current editor"""

        editor_widget = self.get_current_editor()
        if editor_widget is not None:
            editor_widget.reset_zoom()

    def editor_move_up(self):
        editor_widget = self.get_current_editor()
        if editor_widget is not None:
            editor_widget.move_up_down(up=True)

    def editor_move_down(self):
        editor_widget = self.get_current_editor()
        if editor_widget is not None:
            editor_widget.move_up_down()

    def editor_duplicate_line(self):
        editor_widget = self.get_current_editor()
        if editor_widget is not None:
            editor_widget.duplicate_line()

    def editor_comment(self):
        """Mark the current line or selection as a comment."""
        editor_widget = self.get_current_editor()
        if editor_widget is not None:
            helpers.comment_or_uncomment(editor_widget)

    def editor_go_to_line(self, line):
        editor_widget = self.get_current_editor()
        if editor_widget is not None:
            editor_widget.go_to_line(line)
            editor_widget.setFocus()

    def _editor_settings_changed(self, key, value):
        key = key.split("/")[-1]
        editor_widget = self.get_current_editor()
        if editor_widget is not None:
            callback = getattr(editor.NEditor, key, False)
            if callback:
                callback = callback
                if not hasattr(callback, "__call__"):
                    # Property!
                    callback = callback.fset
                callback(editor_widget, value)

    def toggle_tabs_and_spaces(self):
        """Toggle Show/Hide Tabs and Spaces"""

        settings.SHOW_TABS_AND_SPACES = not settings.SHOW_TABS_AND_SPACES
        qsettings = IDE.ninja_settings()
        qsettings.setValue('preferences/editor/showTabsAndSpaces',
                           settings.SHOW_TABS_AND_SPACES)
        neditor = self.get_current_editor()
        if neditor is not None:
            neditor.show_whitespaces = settings.SHOW_TABS_AND_SPACES

    def __navigate_with_keyboard(self, forward):
        """Navigate between the positions in the jump history stack."""
        operation = self.combo_area.bar.code_navigator.operation
        self.navigate_code_history(operation, forward)

    def navigate_back(self):
        self.__navigate_with_keyboard(forward=False)

    def navigate_forward(self):
        self.__navigate_with_keyboard(forward=True)
示例#35
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent, Qt.Window)

        self.board = TetrixBoard()
        self.indictor = TetrixIndictor()

        nextPieceLabel = QLabel(self)
        nextPieceLabel.setFrameStyle(QFrame.Box | QFrame.Raised)
        nextPieceLabel.setAlignment(Qt.AlignCenter)
        self.board.setNextPieceLabel(nextPieceLabel)

        scoreLcd = QLCDNumber(6)
        scoreLcd.setSegmentStyle(QLCDNumber.Filled)
        levelLcd = QLCDNumber(2)
        levelLcd.setSegmentStyle(QLCDNumber.Filled)
        linesLcd = QLCDNumber(6)
        linesLcd.setSegmentStyle(QLCDNumber.Filled)

        startButton = QPushButton(self.tr("&Start"))
        startButton.setFocusPolicy(Qt.NoFocus)
        quitButton = QPushButton(self.tr("E&xit"))
        quitButton.setFocusPolicy(Qt.NoFocus)
        pauseButton = QPushButton(self.tr("&Pause"))
        pauseButton.setFocusPolicy(Qt.NoFocus)

        startButton.clicked.connect(self.board.start)
        pauseButton.clicked.connect(self.board.pause)
        quitButton.clicked.connect(self.close)
        self.board.scoreChanged.connect(scoreLcd.display)
        self.board.levelChanged.connect(levelLcd.display)
        self.board.linesRemovedChanged.connect(linesLcd.display)
        self.board.act.connect(self.indictor.showIndictor)

        layout1 = QHBoxLayout()
        layout3 = QVBoxLayout()
        layout3.addWidget(self.board)
        layout3.addWidget(self.indictor)
        layout3.setSpacing(0)
        layout1.addLayout(layout3)
        layout2 = QVBoxLayout()
        layout2.addWidget(self.createLabel(self.tr("Next Block")))
        layout2.addWidget(nextPieceLabel)
        layout2.addWidget(self.createLabel(self.tr("Level")))
        layout2.addWidget(levelLcd)
        layout2.addWidget(self.createLabel(self.tr("Score")), )
        layout2.addWidget(scoreLcd)
        layout2.addWidget(self.createLabel(self.tr("Total Lines")))
        layout2.addWidget(linesLcd)
        layout2.addWidget(startButton)
        layout2.addWidget(quitButton)
        layout2.addWidget(pauseButton)
        layout1.addLayout(layout2)
        layout1.setStretch(0, 75)
        layout1.setStretch(1, 25)
        self.setLayout(layout1)

        self.setWindowTitle(self.tr("Tetrix"))
        self.resize(self.logicalDpiX() / 96 * 275,
                    self.logicalDpiY() / 96 * 380)

        r = self.geometry()
        r.moveCenter(
            QApplication.instance().desktop().screenGeometry().center())
        self.setGeometry(r)
示例#36
0
    def __init_ui(self):
        layout = QVBoxLayout()
        layout.setContentsMargins(2, 2, 2, 2)
        layout.setSpacing(2)

        control_frame = QFrame(self)
        control_frame.setFrameStyle(QFrame.Panel)
        control_frame.setLineWidth(1)

        control_layout = QHBoxLayout()
        control_layout.setAlignment(Qt.AlignLeft)
        control_layout.setContentsMargins(2, 2, 2, 2)
        control_layout.setSpacing(3)

        low_label = QLabel("low limit:")
        low_label.setFixedWidth(60)
        control_layout.addWidget(low_label)

        self.__lower_edit: LimitValueLineEdit = LimitValueLineEdit(
            "lower limit")
        self.__lower_edit.setMaximumWidth(80)
        self.__lower_edit.deselect()
        self.__lower_edit.setAlignment(Qt.AlignLeft)
        self.__lower_edit.value_changed.connect(self.__handle_lower_limit_edit)
        control_layout.addWidget(self.__lower_edit)
        control_layout.addSpacing(10)

        high_label = QLabel("high limit:")
        high_label.setFixedWidth(60)
        control_layout.addWidget(high_label)

        self.__upper_edit: LimitValueLineEdit = LimitValueLineEdit(
            "upper limit")
        self.__upper_edit.setMaximumWidth(80)
        self.__upper_edit.deselect()
        self.__upper_edit.setAlignment(Qt.AlignLeft)
        self.__upper_edit.value_changed.connect(self.__handle_upper_limit_edit)
        control_layout.addWidget(self.__upper_edit)
        control_layout.addSpacing(10)

        self.__reset_button = QPushButton("Reset")
        self.__reset_button.setFixedWidth(60)
        self.__reset_button.clicked.connect(self.__handle_reset_clicked)
        control_layout.addWidget(self.__reset_button)

        control_frame.setLayout(control_layout)
        layout.addWidget(control_frame)

        # plot_frame = QGroupBox(self)
        plot_frame = QFrame(self)
        plot_frame.setFrameStyle(QFrame.Panel)
        plot_frame.setLineWidth(1)

        # plot_frame = QWidget(self)
        plot_layout = QHBoxLayout()
        plot_layout.setContentsMargins(2, 2, 2, 2)
        plot_layout.setSpacing(2)
        plot_layout.addWidget(self.__raw_data_canvas)
        plot_layout.addWidget(self.__adjusted_data_canvas)
        plot_frame.setLayout(plot_layout)
        layout.addWidget(plot_frame)

        self.setLayout(layout)
示例#37
0
class App(QFrame):
    def __init__(self):
        super().__init__()
        self.AppSettings()
        self.CreateApplication()

    def AppSettings(self):
        self.setWindowTitle('Web Browser')
        self.setMinimumSize(840, 620)

    def CreateApplication(self):
        # Main Layout
        self.layout = QVBoxLayout()
        self.layout.setSpacing(0)
        self.layout.setContentsMargins(0,0,0,0)

        # Variables
        self.tab_count = 0
        self.tabs = []

        self.tabbar = QTabBar(tabsClosable=True, movable=True)
        self.tabbar.tabCloseRequested.connect(self.CloseTab)
        self.tabbar.tabBarClicked.connect(self.SwitchTab)

        self.tabbar.setElideMode(Qt.ElideLeft)
        self.tabbar.setExpanding(False)

        # ToolBar
        self.ToolBar = QWidget()
        self.toolbar_layout = QHBoxLayout()
        
        # Tools
        self.btnAddTab = QPushButton('+')
        self.btnAddTab.clicked.connect(self.AddTab)

        self.address_bar =  AddressBar()
        self.address_bar.returnPressed.connect(self.BrowseTo)

        self.btn_back = QPushButton('<')
        self.btn_back.clicked.connect(self.Back)

        self.btn_forward = QPushButton('>')
        self.btn_forward.clicked.connect(self.Forward)

        self.btn_refresh = QPushButton('F5')
        self.btn_refresh.clicked.connect(self.Refresh)

        # Add Tools to ToolBar layout
        self.toolbar_layout.addWidget(self.btn_back)
        self.toolbar_layout.addWidget(self.btn_forward)
        self.toolbar_layout.addWidget(self.btn_refresh)
        self.toolbar_layout.addWidget(self.address_bar)
        self.toolbar_layout.addWidget(self.btnAddTab)


        # Container
        self.container = QWidget()
        self.container_layout = QStackedLayout()
        self.container.setLayout(self.container_layout)

        # addLayout to toolbar
        self.ToolBar.setLayout(self.toolbar_layout)

        
        # Adding Widgets to Main Layout
        self.layout.addWidget(self.tabbar)
        self.layout.addWidget(self.ToolBar)
        self.layout.addWidget(self.container)

        self.AddTab()

        self.setLayout(self.layout)
        self.show()


    def CloseTab(self, i):
        self.tabbar.removeTab(i)

    def AddTab(self):
        if len(self.tabs):
            self.tab_count += 1
        i = self.tab_count

        self.tabs.append(QWidget())
        self.tabs[i].layout  = QHBoxLayout()
        self.tabs[i].setObjectName('tab'+str(i))


        self.tabs[i].layout.setContentsMargins(0,0,0,0)

        self.tabs[i].content = QWebEngineView()
        self.tabs[i].content.titleChanged.connect(lambda: self.setTabTitle(i))
        self.tabs[i].content.iconChanged.connect(lambda: self.setTabIcon(i))
        self.tabs[i].content.urlChanged.connect(lambda: self.setAddressBar(i))


        self.tabs[i].content.load(QUrl.fromUserInput('http://www.google.com'))

        self.tabs[i].layout.addWidget(self.tabs[i].content)
        
        self.container_layout.addWidget(self.tabs[i])
        self.tabs[i].setLayout(self.tabs[i].layout)

        self.tabbar.addTab('New Tab')
        self.tabbar.setTabData(i, 'tab'+str(i))
        self.tabbar.setCurrentIndex(i)
        self.container_layout.setCurrentWidget(self.tabs[i])

        self.address_bar.selectAll()
        self.address_bar.setFocus()

    
    def SwitchTab(self, i):

        if self.tabs[i]:
            self.tabbar.currentIndex()
            tabName = self.tabbar.tabData(i)
            tabObj = self.findChild(QWidget, tabName)
            self.container_layout.setCurrentWidget(tabObj)

            url = tabObj.content.url().toString()
            self.address_bar.setText(url)

    def BrowseTo(self):
        text = self.address_bar.text()
        url = ""
        if 'http' not in text:
            if '.' not in text:
                if 'localhost' in text:
                    url = 'http://'+text
                else:
                    url = 'http://google.com/search?q='+text
            else:
                url = 'http://'+text
        else:
            url = text

        i = self.tabbar.currentIndex()
        self.object = self.findChild(QWidget, self.tabbar.tabData(i))
        self.object.content.load(QUrl.fromUserInput(url))
        

    def setTabTitle(self, i):
        tabName = self.tabbar.tabData(i)
        TabObj = self.findChild(QWidget, tabName)
        self.tabbar.setTabText(i, TabObj.content.title())

    def setAddressBar(self, i):
        tabName = self.tabbar.tabData(i)
        url = self.findChild(QWidget, tabName).content.url().toString()

        self.address_bar.setText(url)

    def setTabIcon(self, i):
        tabName = self.tabbar.tabData(i)
        icon = self.findChild(QWidget, tabName).content.icon()
        self.tabbar.setTabIcon(i, icon)

    def Back(self):
        i = self.tabbar.currentIndex()
        self.tabs[i].content.back()

    def Forward(self):
        i = self.tabbar.currentIndex()
        self.tabs[i].content.forward()

    def Refresh(self):
        i = self.tabbar.currentIndex()
        self.tabs[i].content.reload()
示例#38
0
layout_line2.addWidget(AnsGroupBox)
AnsGroupBox.hide(
)  # скроем панель с ответом, сначала должна быть видна панель вопросов

layout_line3.addStretch(1)
layout_line3.addWidget(btn_OK, stretch=2)  # кнопка должна быть большой
layout_line3.addStretch(1)

layout_card = QVBoxLayout()

layout_card.addLayout(layout_line1, stretch=2)
layout_card.addLayout(layout_line2, stretch=8)
layout_card.addStretch(1)
layout_card.addLayout(layout_line3, stretch=1)
layout_card.addStretch(1)
layout_card.setSpacing(5)  # пробелы между содержимым


def show_result():
    ''' показать панель ответов '''
    RadioGroupBox.hide()
    AnsGroupBox.show()
    btn_OK.setText('Следующий вопрос')


def show_question():
    ''' показать панель вопросов '''
    RadioGroupBox.show()
    AnsGroupBox.hide()
    btn_OK.setText('Ответить')
    RadioGroup.setExclusive(
示例#39
0
    def buildUi(self):

        main_layout = QVBoxLayout()
        main_layout.setSpacing(6)

        wiring_button = QPushButton(self.tr("Wiring configuration"))
        wiring_button.setToolTip(self.tr("Show/Hide wiring configuration"))
        wiring_button.setFocusPolicy(Qt.NoFocus)

        main_layout.addWidget(wiring_button)

        wiring_button.released.connect(self.wiringButtonReleased)
        wiring_button.released.connect(self.accept)

        if self._propVariables:
            button = self.tr("Rebuild panel from new wiring")
        else:
            button = self.tr("Build panel from wiring")

        build_button = QPushButton(" {} ".format(button))
        build_button.setFocusPolicy(Qt.NoFocus)

        main_layout.addWidget(build_button)

        credentials_box = QGroupBox(self.tr("Prop SSH credentials"))
        credentials_box.setToolTip(
            self.tr("Credentials for relaunch and reboot SSH commands"))
        credentials_box_layout = QGridLayout(credentials_box)
        main_layout.addWidget(credentials_box)

        self._addrInput = QLineEdit()
        credentials_box_layout.addWidget(QLabel(self.tr("IP address")),
                                         credentials_box_layout.rowCount(), 0)
        credentials_box_layout.addWidget(self._addrInput,
                                         credentials_box_layout.rowCount() - 1,
                                         1)
        credentials_box_layout.addItem(QSpacerItem(200, 5),
                                       credentials_box_layout.rowCount() - 1,
                                       2)

        self._userInput = QLineEdit()
        credentials_box_layout.addWidget(QLabel(self.tr("User")),
                                         credentials_box_layout.rowCount(), 0)
        credentials_box_layout.addWidget(self._userInput,
                                         credentials_box_layout.rowCount() - 1,
                                         1)
        credentials_box_layout.addItem(QSpacerItem(200, 5),
                                       credentials_box_layout.rowCount() - 1,
                                       2)

        self._paswInput = QLineEdit()
        credentials_box_layout.addWidget(QLabel(self.tr("Password")),
                                         credentials_box_layout.rowCount(), 0)
        credentials_box_layout.addWidget(self._paswInput,
                                         credentials_box_layout.rowCount() - 1,
                                         1)

        if 'addr' in self._sshCredentials:
            self._addrInput.setText(self._sshCredentials['addr'])
        if 'user' in self._sshCredentials:
            self._userInput.setText(self._sshCredentials['user'])

        if 'pasw' in self._sshCredentials:
            if len(self._sshCredentials['pasw']):
                r = list(
                    map(lambda x: chr(256 - int(x)),
                        bytearray.fromhex(self._sshCredentials['pasw'])))
                self._paswInput.setText(''.join(r))
            else:
                self._paswInput.setText(self._sshCredentials['pasw'])

        self._addrInput.editingFinished.connect(self.onCredentialsEdition)
        self._userInput.editingFinished.connect(self.onCredentialsEdition)
        self._paswInput.editingFinished.connect(self.onCredentialsEdition)

        if self._propSettings['prop']['board'] == 'nucleo':
            credentials_box.setVisible(False)

        close_button = QPushButton(self.tr("Close"))
        close_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        close_button.setFocusPolicy(Qt.NoFocus)

        edit_button = QPushButton(' {} '.format(
            self.tr("Edit captions and indicators")))
        edit_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        edit_button.setFocusPolicy(Qt.NoFocus)
        edit_button.setEnabled(len(self._propVariables))

        button_layout = QHBoxLayout()
        button_layout.addWidget(edit_button)
        button_layout.addStretch()
        button_layout.addWidget(close_button)
        main_layout.addLayout(button_layout)

        self.setLayout(main_layout)

        close_button.released.connect(self.accept)
        edit_button.released.connect(self.onEdit)
        build_button.released.connect(self.onBuild)
示例#40
0
    def __init__(self):
        super(UserInfoUi, self).__init__()
        self.factor = QApplication.desktop().screenGeometry().width() / 100
        self.resize(self.factor * 16, self.factor * 20)
        self.setWindowOpacity(1)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.setContentsMargins(0, 0, 0, 0)
        main_layout = QVBoxLayout()
        main_layout.setSpacing(0)
        v_layout = QVBoxLayout()
        h_layout = QHBoxLayout()
        self.user_name = QPushButton('admin')
        self.is_vip = QPushButton()
        self.is_vip.setCursor(QCursor(Qt.PointingHandCursor))
        self.is_vip.setIcon(QIcon(':/default/default_icons/is_crown.ico'))
        h_layout.addWidget(self.user_name)
        h_layout.addWidget(self.is_vip)
        h_layout.addStretch()
        self.capacity_bar = QProgressBar()
        self.capacity_bar.setValue(30)
        self.capacity_bar.setFixedHeight(self.factor)
        self.capacity_bar.setTextVisible(False)
        self.capacity_info = QLabel('6G/20G')
        v_layout.addLayout(h_layout)
        v_layout.addWidget(self.capacity_bar)
        v_layout.addWidget(self.capacity_info)
        self.v_widget = QWidget(self)
        self.v_widget.setWindowOpacity(1)
        self.v_widget.setLayout(v_layout)
        self.personal_center = QPushButton('个人中心')
        self.help_center = QPushButton('帮助中心')
        self.switch_account = QPushButton('切换账号')
        self.exit_account = QPushButton('退出')
        self.personal_center.setSizePolicy(QSizePolicy.Preferred,
                                           QSizePolicy.Expanding)
        self.help_center.setSizePolicy(QSizePolicy.Preferred,
                                       QSizePolicy.Expanding)
        self.switch_account.setSizePolicy(QSizePolicy.Preferred,
                                          QSizePolicy.Expanding)
        self.exit_account.setSizePolicy(QSizePolicy.Preferred,
                                        QSizePolicy.Expanding)
        button_widget = QWidget()
        button_layout = QVBoxLayout()
        button_layout.setSpacing(self.factor * 0.5)
        button_layout.addWidget(self.personal_center)
        button_layout.addWidget(self.help_center)
        button_layout.addWidget(self.switch_account)
        button_layout.addWidget(self.exit_account)
        button_widget.setLayout(button_layout)
        main_layout.addWidget(self.v_widget)
        main_layout.addWidget(button_widget)
        main_layout.setStretchFactor(self.v_widget, 2)
        main_layout.setStretchFactor(button_widget, 10)
        self.setLayout(main_layout)

        self.v_widget.setObjectName('user_info')
        self.user_name.setObjectName('transparent')
        self.is_vip.setObjectName('transparent')
        self.capacity_info.setObjectName('transparent')
        button_widget.setObjectName('color')
示例#41
0
class SongsTableContainer(QFrame):
    def __init__(self, app, parent=None):
        super().__init__(parent)
        self._app = app

        self.songs_table = SongsTableView(self)
        self.table_overview = TableOverview(self)

        self._layout = QVBoxLayout(self)

        self.setAutoFillBackground(False)
        if use_mac_theme():
            self._layout.setContentsMargins(0, 0, 0, 0)
            self._layout.setSpacing(0)
        self._layout.addWidget(self.table_overview)
        self._layout.addWidget(self.songs_table)

        self.songs_table.play_song_needed.connect(
            lambda song: asyncio.ensure_future(self.play_song(song)))
        self.songs_table.show_artist_needed.connect(
            lambda artist: asyncio.ensure_future(self.show_model(artist)))
        self.songs_table.show_album_needed.connect(
            lambda album: asyncio.ensure_future(self.show_model(album)))
        self._cover_pixmap = None
        self.hide()

    async def play_song(self, song):
        loop = asyncio.get_event_loop()
        with self._app.create_action('play {}'.format(song)):
            await loop.run_in_executor(None, lambda: song.url)
            self._app.player.play_song(song)

    def play_all(self):
        songs = self.songs_table.model().songs
        self._app.player.playlist.clear()
        for song in songs:
            self._app.player.playlist.add(song)
        self._app.player.play_next()

    async def show_model(self, model):
        model_type = ModelType(model._meta.model_type)
        if model_type == ModelType.album:
            func = self.show_album
        elif model_type == ModelType.artist:
            func = self.show_artist
        elif model_type == ModelType.playlist:
            func = self.show_playlist
        else:

            def func(model):
                pass  # seems silly

        self._app.histories.append(model)
        with self._app.create_action('show {}'.format(str(model))):
            await func(model)

    def show_player_playlist(self, songs):
        self.show_songs(songs)
        self.songs_table.song_deleted.connect(
            lambda song: self._app.playlist.remove(song))

    async def show_playlist(self, playlist):
        self.table_overview.show()
        loop = asyncio.get_event_loop()
        songs = await loop.run_in_executor(None, lambda: playlist.songs)
        self._show_songs(songs)
        desc = '<h2>{}</h2>\n{}'.format(playlist.name, playlist.desc or '')
        self.table_overview.set_desc(desc)
        if playlist.cover:
            loop.create_task(self.show_cover(playlist.cover))

        def remove_song(song):
            model = self.songs_table.model()
            row = model.songs.index(song)
            # 如果有 f-string 该有多好!
            msg = 'remove {} from {}'.format(song, playlist)
            with self._app.create_action(msg) as action:
                rv = playlist.remove(song.identifier)
                if rv:
                    model.removeRow(row)
                else:
                    action.failed()

        self.songs_table.song_deleted.connect(lambda song: remove_song(song))

    async def show_artist(self, artist):
        self.table_overview.show()
        loop = asyncio.get_event_loop()
        future_songs = loop.run_in_executor(None, lambda: artist.songs)
        future_desc = loop.run_in_executor(None, lambda: artist.desc)
        await asyncio.wait([future_songs, future_desc])
        desc = future_desc.result()
        self.table_overview.set_desc(desc or '<h2>{}</h2>'.format(artist.name))
        self._show_songs(future_songs.result())
        if artist.cover:
            loop.create_task(self.show_cover(artist.cover))

    async def show_album(self, album):
        loop = asyncio.get_event_loop()
        future_songs = loop.run_in_executor(None, lambda: album.songs)
        future_desc = loop.run_in_executor(None, lambda: album.desc)
        await asyncio.wait([future_songs, future_desc])
        self.table_overview.set_desc(future_desc.result()
                                     or '<h2>{}</h2>'.format(album.name))

    async def show_cover(self, cover):
        # FIXME: cover_hash may not work properly someday
        cover_uid = cover.split('/', -1)[-1]
        content = await self._app.img_ctl.get(cover, cover_uid)
        img = QImage()
        img.loadFromData(content)
        pixmap = QPixmap(img)
        if not pixmap.isNull():
            self.table_overview.set_cover(pixmap)
            self.update()

    def _show_songs(self, songs):
        try:
            self.songs_table.song_deleted.disconnect()
        except TypeError:  # no connections at all
            pass
        self.show()

        source_icon_map = {
            lib.identifier: lib.icon
            for lib in self._app.libraries
        }
        self.songs_table.setModel(SongsTableModel(songs or [],
                                                  source_icon_map))
        self.songs_table.scrollToTop()

    def show_songs(self, songs):
        self._show_songs(songs)
        self.table_overview.hide()

    def search(self, text):
        if self.isVisible() and self.songs_table is not None:
            self.songs_table.filter_row(text)
示例#42
0
    def __init__(self, parent=None, show_progress_dlg=False):
        super(SearchPanel, self).__init__(parent=parent)
        self._app_window = parent

        if self._app_window.dwarf is None:
            print('SearchPanel created before Dwarf exists')
            return

        self._app_window.dwarf.onMemoryScanResult.connect(
            self._on_search_result)

        self._app_window.dwarf.onSetRanges.connect(self._on_setranges)

        self._ranges_model = None
        self._result_model = None

        self._blocking_search = show_progress_dlg
        self.progress = None
        self._pattern_length = 0

        self._search_results = []

        self.setContentsMargins(0, 0, 0, 0)

        main_wrap = QVBoxLayout()
        main_wrap.setContentsMargins(1, 1, 1, 1)

        wrapping_wdgt = QWidget()
        wrapping_wdgt.setContentsMargins(10, 10, 10, 10)
        v_box = QVBoxLayout(wrapping_wdgt)
        v_box.setContentsMargins(0, 0, 0, 0)
        self.input = QLineEdit()
        self.input.setPlaceholderText(
            'search for a sequence of bytes in hex format: deadbeef123456aabbccddeeff...'
        )
        v_box.addWidget(self.input)

        self.check_all_btn = QPushButton('check all')
        self.check_all_btn.clicked.connect(self._on_click_check_all)
        self.uncheck_all_btn = QPushButton('uncheck all')
        self.uncheck_all_btn.clicked.connect(self._on_click_uncheck_all)
        self.search_btn = QPushButton('search')
        self.search_btn.clicked.connect(self._on_click_search)

        h_box = QHBoxLayout()
        h_box.addWidget(self.check_all_btn)
        h_box.addWidget(self.uncheck_all_btn)
        h_box.addWidget(self.search_btn)
        v_box.addLayout(h_box)

        main_wrap.addWidget(wrapping_wdgt)

        self.ranges = DwarfListView(self)
        self.ranges.clicked.connect(self._on_show_results)
        self.results = DwarfListView(self)
        self.results.setVisible(False)

        h_box = QHBoxLayout()
        h_box.setContentsMargins(0, 0, 0, 0)
        h_box.addWidget(self.ranges)
        h_box.addWidget(self.results)
        main_wrap.addLayout(h_box)

        main_wrap.setSpacing(0)

        self.setLayout(main_wrap)

        self._setup_models()
        self._app_window.dwarf.dwarf_api('updateRanges')
示例#43
0
class FoldersDialog(QDialog):
    """A dialog window responsible for providing access to adding/removing folders for the library class."""

    removeSignal = pyqtSignal(str)

    def __init__(self, window: QMainWindow, parent: QLabel, control) -> None:
        super().__init__(parent=parent, flags=Qt.FramelessWindowHint)
        self.setWindowModality(Qt.WindowModal)
        self.window = window
        self.parent = parent
        self.setFixedSize(500, 300)
        self.control = control
        self.activeDialog = None
        self.highlightedLabel = None
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.scrollArea = QScrollArea()
        self.scrollBar = QScrollBar(Qt.Vertical, self.scrollArea)
        self.scrollBar.setStyleSheet(scrollBarStyle)
        self.scrollArea.setVerticalScrollBar(self.scrollBar)
        self.scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setFrameShape(QFrame.NoFrame)
        self.layout.addWidget(self.scrollArea)
        self.folders = QWidget()
        self.scrollArea.setWidget(self.folders)
        self.foldersLayout = QVBoxLayout()
        self.foldersLayout.setAlignment(Qt.AlignTop)
        self.folders.setLayout(self.foldersLayout)

        self.buttons = QWidget()
        self.buttonsLayout = QHBoxLayout()
        self.buttons.setLayout(self.buttonsLayout)
        self.layout.addWidget(self.buttons)

        self.add = QPushButton()
        self.add.setText("Add")
        self.add.clicked.connect(self.addFolder)
        self.remove = QPushButton()
        self.remove.setText("Remove")
        self.remove.clicked.connect(self.removeFolder)
        self.cancel = QPushButton()
        self.cancel.setText("Done")
        self.cancel.clicked.connect(self.reject)
        for button in [self.add, self.remove, self.cancel]:
            self.buttonsLayout.addWidget(button)

        self.layout.setContentsMargins(10, 10, 10, 10)
        self.layout.setSpacing(5)
        self.layout.setAlignment(Qt.AlignTop)
        self.setStyleSheet("QDialog {"
                           "    background-color: #141414;"
                           "    border-style: solid;"
                           "    border-width: 8px;"
                           "    border-color: #202020;"
                           "}"
                           "QLabel {"
                           "    background-color: #141414;"
                           "    font-size: 12px"
                           "}")
        self.move(self.mapToGlobal(self.window.pos()) + QPoint(150, 150))

        self.fileDialog = QFileDialog()
        self.fileDialog.setAcceptMode(QFileDialog.AcceptOpen)
        self.fileDialog.setFileMode(QFileDialog.Directory)
        self.fileDialog.setWindowModality(Qt.WindowModal)
        self.fileDialog.Options(QFileDialog.ShowDirsOnly)
        self.fileDialog.fileSelected.connect(self.control.addWatchedFolder)
        self.fileDialog.fileSelected.connect(self.updateFolders)
        self.removeSignal.connect(self.control.removeWatchedFolder)
        for folder in self.control.library.folders:
            field = ClickLabel()
            field.setText(folder)
            field.setFixedHeight(15)
            field.click.connect(self.highlightLabel)
            self.foldersLayout.addWidget(field)

    def highlightLabel(self, label: QLabel) -> None:
        if self.highlightedLabel is not None:
            self.highlightedLabel.setStyleSheet(
                "QLabel {"
                "    background-color: #141414;"
                "}")
            if self.highlightedLabel == label:
                self.highlightedLabel = None
                return
        label.setStyleSheet("QLabel {" "    background-color: #353535;" "}")
        self.highlightedLabel = label

    def addFolder(self) -> None:
        self.fileDialog.show()

    def updateFolders(self, folder: str) -> None:
        field = ClickLabel()
        field.setText(folder.replace("/", "\\"))
        field.setFixedHeight(15)
        field.click.connect(self.highlightLabel)
        self.foldersLayout.addWidget(field)

    def removeFolder(self) -> None:
        if self.highlightedLabel is not None:
            self.foldersLayout.removeWidget(self.highlightedLabel)
            self.removeSignal.emit(self.highlightedLabel.text())
            self.highlightedLabel.deleteLater()
            self.highlightedLabel = None
示例#44
0
class MainWindow(QWidget):

    """The main window of qutebrowser.

    Adds all needed components to a vbox, initializes sub-widgets and connects
    signals.

    Attributes:
        status: The StatusBar widget.
        tabbed_browser: The TabbedBrowser widget.
        _downloadview: The DownloadView widget.
        _vbox: The main QVBoxLayout.
        _commandrunner: The main CommandRunner instance.
        _overlays: Widgets shown as overlay for the current webpage.
        _private: Whether the window is in private browsing mode.
    """

    def __init__(self, *, private, geometry=None, parent=None):
        """Create a new main window.

        Args:
            geometry: The geometry to load, as a bytes-object (or None).
            private: Whether the window is in private browsing mode.
            parent: The parent the window should get.
        """
        super().__init__(parent)
        # Late import to avoid a circular dependency
        # - browsertab -> hints -> webelem -> mainwindow -> bar -> browsertab
        from qutebrowser.mainwindow import tabbedbrowser
        from qutebrowser.mainwindow.statusbar import bar

        self.setAttribute(Qt.WA_DeleteOnClose)
        self._commandrunner = None
        self._overlays = []
        self.win_id = next(win_id_gen)
        self.registry = objreg.ObjectRegistry()
        objreg.window_registry[self.win_id] = self
        objreg.register('main-window', self, scope='window',
                        window=self.win_id)
        tab_registry = objreg.ObjectRegistry()
        objreg.register('tab-registry', tab_registry, scope='window',
                        window=self.win_id)

        message_bridge = message.MessageBridge(self)
        objreg.register('message-bridge', message_bridge, scope='window',
                        window=self.win_id)

        self.setWindowTitle('qutebrowser')
        self._vbox = QVBoxLayout(self)
        self._vbox.setContentsMargins(0, 0, 0, 0)
        self._vbox.setSpacing(0)

        self._init_downloadmanager()
        self._downloadview = downloadview.DownloadView(self.win_id)

        if config.val.content.private_browsing:
            # This setting always trumps what's passed in.
            private = True
        else:
            private = bool(private)
        self._private = private
        self.tabbed_browser = tabbedbrowser.TabbedBrowser(win_id=self.win_id,
                                                          private=private,
                                                          parent=self)
        objreg.register('tabbed-browser', self.tabbed_browser, scope='window',
                        window=self.win_id)
        self._init_command_dispatcher()

        # We need to set an explicit parent for StatusBar because it does some
        # show/hide magic immediately which would mean it'd show up as a
        # window.
        self.status = bar.StatusBar(win_id=self.win_id, private=private,
                                    parent=self)

        self._add_widgets()
        self._downloadview.show()

        self._init_completion()

        log.init.debug("Initializing modes...")
        modeman.init(self.win_id, self)

        self._commandrunner = runners.CommandRunner(self.win_id,
                                                    partial_match=True)

        self._keyhint = keyhintwidget.KeyHintView(self.win_id, self)
        self._add_overlay(self._keyhint, self._keyhint.update_geometry)

        self._prompt_container = prompt.PromptContainer(self.win_id, self)
        self._add_overlay(self._prompt_container,
                          self._prompt_container.update_geometry,
                          centered=True, padding=10)
        objreg.register('prompt-container', self._prompt_container,
                        scope='window', window=self.win_id)
        self._prompt_container.hide()

        self._messageview = messageview.MessageView(parent=self)
        self._add_overlay(self._messageview, self._messageview.update_geometry)

        self._init_geometry(geometry)
        self._connect_signals()

        # When we're here the statusbar might not even really exist yet, so
        # resizing will fail. Therefore, we use singleShot QTimers to make sure
        # we defer this until everything else is initialized.
        QTimer.singleShot(0, self._connect_overlay_signals)
        config.instance.changed.connect(self._on_config_changed)

        objreg.get("app").new_window.emit(self)
        self._set_decoration(config.val.window.hide_decoration)

    def _init_geometry(self, geometry):
        """Initialize the window geometry or load it from disk."""
        if geometry is not None:
            self._load_geometry(geometry)
        elif self.win_id == 0:
            self._load_state_geometry()
        else:
            self._set_default_geometry()
        log.init.debug("Initial main window geometry: {}".format(
            self.geometry()))

    def _add_overlay(self, widget, signal, *, centered=False, padding=0):
        self._overlays.append((widget, signal, centered, padding))

    def _update_overlay_geometries(self):
        """Update the size/position of all overlays."""
        for w, _signal, centered, padding in self._overlays:
            self._update_overlay_geometry(w, centered, padding)

    def _update_overlay_geometry(self, widget, centered, padding):
        """Reposition/resize the given overlay."""
        if not widget.isVisible():
            return

        size_hint = widget.sizeHint()
        if widget.sizePolicy().horizontalPolicy() == QSizePolicy.Expanding:
            width = self.width() - 2 * padding
            left = padding
        else:
            width = min(size_hint.width(), self.width() - 2 * padding)
            left = (self.width() - width) / 2 if centered else 0

        height_padding = 20
        status_position = config.val.statusbar.position
        if status_position == 'bottom':
            if self.status.isVisible():
                status_height = self.status.height()
                bottom = self.status.geometry().top()
            else:
                status_height = 0
                bottom = self.height()
            top = self.height() - status_height - size_hint.height()
            top = qtutils.check_overflow(top, 'int', fatal=False)
            topleft = QPoint(left, max(height_padding, top))
            bottomright = QPoint(left + width, bottom)
        elif status_position == 'top':
            if self.status.isVisible():
                status_height = self.status.height()
                top = self.status.geometry().bottom()
            else:
                status_height = 0
                top = 0
            topleft = QPoint(left, top)
            bottom = status_height + size_hint.height()
            bottom = qtutils.check_overflow(bottom, 'int', fatal=False)
            bottomright = QPoint(left + width,
                                 min(self.height() - height_padding, bottom))
        else:
            raise ValueError("Invalid position {}!".format(status_position))

        rect = QRect(topleft, bottomright)
        log.misc.debug('new geometry for {!r}: {}'.format(widget, rect))
        if rect.isValid():
            widget.setGeometry(rect)

    def _init_downloadmanager(self):
        log.init.debug("Initializing downloads...")
        qtnetwork_download_manager = objreg.get('qtnetwork-download-manager')

        try:
            webengine_download_manager = objreg.get(
                'webengine-download-manager')
        except KeyError:
            webengine_download_manager = None

        download_model = downloads.DownloadModel(qtnetwork_download_manager,
                                                 webengine_download_manager)
        objreg.register('download-model', download_model, scope='window',
                        window=self.win_id)

    def _init_completion(self):
        self._completion = completionwidget.CompletionView(self.win_id, self)
        cmd = objreg.get('status-command', scope='window', window=self.win_id)
        completer_obj = completer.Completer(cmd=cmd, win_id=self.win_id,
                                            parent=self._completion)
        self._completion.selection_changed.connect(
            completer_obj.on_selection_changed)
        objreg.register('completion', self._completion, scope='window',
                        window=self.win_id)
        self._add_overlay(self._completion, self._completion.update_geometry)

    def _init_command_dispatcher(self):
        dispatcher = commands.CommandDispatcher(self.win_id,
                                                self.tabbed_browser)
        objreg.register('command-dispatcher', dispatcher, scope='window',
                        window=self.win_id)
        self.tabbed_browser.widget.destroyed.connect(
            functools.partial(objreg.delete, 'command-dispatcher',
                              scope='window', window=self.win_id))

    def __repr__(self):
        return utils.get_repr(self)

    @pyqtSlot(str)
    def _on_config_changed(self, option):
        """Resize the completion if related config options changed."""
        if option == 'statusbar.padding':
            self._update_overlay_geometries()
        elif option == 'downloads.position':
            self._add_widgets()
        elif option == 'statusbar.position':
            self._add_widgets()
            self._update_overlay_geometries()
        elif option == 'window.hide_decoration':
            self._set_decoration(config.val.window.hide_decoration)

    def _add_widgets(self):
        """Add or readd all widgets to the VBox."""
        self._vbox.removeWidget(self.tabbed_browser.widget)
        self._vbox.removeWidget(self._downloadview)
        self._vbox.removeWidget(self.status)
        widgets = [self.tabbed_browser.widget]

        downloads_position = config.val.downloads.position
        if downloads_position == 'top':
            widgets.insert(0, self._downloadview)
        elif downloads_position == 'bottom':
            widgets.append(self._downloadview)
        else:
            raise ValueError("Invalid position {}!".format(downloads_position))

        status_position = config.val.statusbar.position
        if status_position == 'top':
            widgets.insert(0, self.status)
        elif status_position == 'bottom':
            widgets.append(self.status)
        else:
            raise ValueError("Invalid position {}!".format(status_position))

        for widget in widgets:
            self._vbox.addWidget(widget)

    def _load_state_geometry(self):
        """Load the geometry from the state file."""
        try:
            data = configfiles.state['geometry']['mainwindow']
            geom = base64.b64decode(data, validate=True)
        except KeyError:
            # First start
            self._set_default_geometry()
        except binascii.Error:
            log.init.exception("Error while reading geometry")
            self._set_default_geometry()
        else:
            self._load_geometry(geom)

    def _save_geometry(self):
        """Save the window geometry to the state config."""
        data = bytes(self.saveGeometry())
        geom = base64.b64encode(data).decode('ASCII')
        configfiles.state['geometry']['mainwindow'] = geom

    def _load_geometry(self, geom):
        """Load geometry from a bytes object.

        If loading fails, loads default geometry.
        """
        log.init.debug("Loading mainwindow from {!r}".format(geom))
        ok = self.restoreGeometry(geom)
        if not ok:
            log.init.warning("Error while loading geometry.")
            self._set_default_geometry()

    def _connect_overlay_signals(self):
        """Connect the resize signal and resize everything once."""
        for widget, signal, centered, padding in self._overlays:
            signal.connect(
                functools.partial(self._update_overlay_geometry, widget,
                                  centered, padding))
            self._update_overlay_geometry(widget, centered, padding)

    def _set_default_geometry(self):
        """Set some sensible default geometry."""
        self.setGeometry(QRect(50, 50, 800, 600))

    def _get_object(self, name):
        """Get an object for this window in the object registry."""
        return objreg.get(name, scope='window', window=self.win_id)

    def _connect_signals(self):
        """Connect all mainwindow signals."""
        status = self._get_object('statusbar')
        keyparsers = self._get_object('keyparsers')
        completion_obj = self._get_object('completion')
        cmd = self._get_object('status-command')
        message_bridge = self._get_object('message-bridge')
        mode_manager = self._get_object('mode-manager')

        # misc
        self.tabbed_browser.close_window.connect(self.close)
        mode_manager.entered.connect(hints.on_mode_entered)

        # status bar
        mode_manager.entered.connect(status.on_mode_entered)
        mode_manager.left.connect(status.on_mode_left)
        mode_manager.left.connect(cmd.on_mode_left)
        mode_manager.left.connect(message.global_bridge.mode_left)

        # commands
        keyparsers[usertypes.KeyMode.normal].keystring_updated.connect(
            status.keystring.setText)
        cmd.got_cmd[str].connect(self._commandrunner.run_safely)
        cmd.got_cmd[str, int].connect(self._commandrunner.run_safely)
        cmd.returnPressed.connect(self.tabbed_browser.on_cmd_return_pressed)

        # key hint popup
        for mode, parser in keyparsers.items():
            parser.keystring_updated.connect(functools.partial(
                self._keyhint.update_keyhint, mode.name))

        # messages
        message.global_bridge.show_message.connect(
            self._messageview.show_message)
        message.global_bridge.flush()
        message.global_bridge.clear_messages.connect(
            self._messageview.clear_messages)

        message_bridge.s_set_text.connect(status.set_text)
        message_bridge.s_maybe_reset_text.connect(status.txt.maybe_reset_text)

        # statusbar
        self.tabbed_browser.current_tab_changed.connect(status.on_tab_changed)

        self.tabbed_browser.cur_progress.connect(status.prog.setValue)
        self.tabbed_browser.cur_load_finished.connect(status.prog.hide)
        self.tabbed_browser.cur_load_started.connect(
            status.prog.on_load_started)

        self.tabbed_browser.cur_scroll_perc_changed.connect(
            status.percentage.set_perc)
        self.tabbed_browser.widget.tab_index_changed.connect(
            status.tabindex.on_tab_index_changed)

        self.tabbed_browser.cur_url_changed.connect(status.url.set_url)
        self.tabbed_browser.cur_url_changed.connect(functools.partial(
            status.backforward.on_tab_cur_url_changed,
            tabs=self.tabbed_browser))
        self.tabbed_browser.cur_link_hovered.connect(status.url.set_hover_url)
        self.tabbed_browser.cur_load_status_changed.connect(
            status.url.on_load_status_changed)

        self.tabbed_browser.cur_caret_selection_toggled.connect(
            status.on_caret_selection_toggled)

        self.tabbed_browser.cur_fullscreen_requested.connect(
            self._on_fullscreen_requested)
        self.tabbed_browser.cur_fullscreen_requested.connect(status.maybe_hide)

        # command input / completion
        mode_manager.entered.connect(self.tabbed_browser.on_mode_entered)
        mode_manager.left.connect(self.tabbed_browser.on_mode_left)
        cmd.clear_completion_selection.connect(
            completion_obj.on_clear_completion_selection)
        cmd.hide_completion.connect(completion_obj.hide)

    def _set_decoration(self, hidden):
        """Set the visibility of the window decoration via Qt."""
        window_flags = Qt.Window
        refresh_window = self.isVisible()
        if hidden:
            window_flags |= Qt.CustomizeWindowHint | Qt.NoDropShadowWindowHint
        self.setWindowFlags(window_flags)
        if refresh_window:
            self.show()

    @pyqtSlot(bool)
    def _on_fullscreen_requested(self, on):
        if not config.val.content.windowed_fullscreen:
            if on:
                self.setWindowState(self.windowState() | Qt.WindowFullScreen)
            elif self.isFullScreen():
                self.setWindowState(self.windowState() & ~Qt.WindowFullScreen)

    @cmdutils.register(instance='main-window', scope='window')
    @pyqtSlot()
    def close(self):
        """Close the current window.

        //

        Extend close() so we can register it as a command.
        """
        super().close()

    def resizeEvent(self, e):
        """Extend resizewindow's resizeEvent to adjust completion.

        Args:
            e: The QResizeEvent
        """
        super().resizeEvent(e)
        self._update_overlay_geometries()
        self._downloadview.updateGeometry()
        self.tabbed_browser.widget.tabBar().refresh()

    def showEvent(self, e):
        """Extend showEvent to register us as the last-visible-main-window.

        Args:
            e: The QShowEvent
        """
        super().showEvent(e)
        objreg.register('last-visible-main-window', self, update=True)

    def _do_close(self):
        """Helper function for closeEvent."""
        try:
            last_visible = objreg.get('last-visible-main-window')
            if self is last_visible:
                objreg.delete('last-visible-main-window')
        except KeyError:
            pass
        objreg.get('session-manager').save_last_window_session()
        self._save_geometry()
        log.destroy.debug("Closing window {}".format(self.win_id))
        self.tabbed_browser.shutdown()

    def closeEvent(self, e):
        """Override closeEvent to display a confirmation if needed."""
        if crashsignal.is_crashing:
            e.accept()
            return
        tab_count = self.tabbed_browser.widget.count()
        download_model = objreg.get('download-model', scope='window',
                                    window=self.win_id)
        download_count = download_model.running_downloads()
        quit_texts = []
        # Ask if multiple-tabs are open
        if 'multiple-tabs' in config.val.confirm_quit and tab_count > 1:
            quit_texts.append("{} {} open.".format(
                tab_count, "tab is" if tab_count == 1 else "tabs are"))
        # Ask if multiple downloads running
        if 'downloads' in config.val.confirm_quit and download_count > 0:
            quit_texts.append("{} {} running.".format(
                download_count,
                "download is" if download_count == 1 else "downloads are"))
        # Process all quit messages that user must confirm
        if quit_texts or 'always' in config.val.confirm_quit:
            msg = jinja.environment.from_string("""
                <ul>
                {% for text in quit_texts %}
                   <li>{{text}}</li>
                {% endfor %}
                </ul>
            """.strip()).render(quit_texts=quit_texts)
            confirmed = message.ask('Really quit?', msg,
                                    mode=usertypes.PromptMode.yesno,
                                    default=True)

            # Stop asking if the user cancels
            if not confirmed:
                log.destroy.debug("Cancelling closing of window {}".format(
                    self.win_id))
                e.ignore()
                return
        e.accept()
        self._do_close()
示例#45
0
文件: final.py 项目: nimRobotics/BTP
    def __init__(self):
        QWidget.__init__(self)
        self.setWindowTitle('OpenKDM')

        layout = QVBoxLayout()

        self.labelImage = QLabel(self)
        self.pixmap = QPixmap("logo_banner.png")
        self.pixmap = self.pixmap.scaledToWidth(512)  # image size
        self.labelImage.setPixmap(self.pixmap)
        self.labelImage.setAlignment(Qt.AlignCenter)

        self.button = QPushButton('Numerical Simulation')
        self.button.clicked.connect(self.login1)

        self.button2 = QPushButton('Analytical Solutions')
        self.button2.clicked.connect(self.login2)
        self.button.resize(100, 32)
        # self.button.setSizePolicy(QSizePolicy.Preferred,QSizePolicy.Expanding)
        # self.button2.setSizePolicy(QSizePolicy.Preferred,QSizePolicy.Expanding)

        self.button.setEnabled(False)
        self.button2.setEnabled(False)

        self.intro_text = """The study of the 'Kinematics and Dynamics of Machinery' (IITT course code: ME2206) lies at the very core of a mechanical engineering background. Although, little has changed in the way the subject is presented, our methodology brings the subject alive and current. We present the design and fabrication of a novel experimental setup for carrying out static, kinematic and dynamic analysis of three different mechanisms in a single setup. The mechanism is designed to be configurable to three different types of mechanisms namely - double crank, slider crank and a six bar mechanism depending on the use case. The mechanism has retrofitted parts (different link lengths and sliders) to facilitate multiple experiments in the same setup. The learner gets to 'play' with the mechanism parameters and immediately understand their effects. This will enhance one’s grasp of the concepts and the development of analytical skills. Hence greatly supplementing and reinforcing the theoretical understanding of the undergraduate students taking the course."""

        self.license_text = """MIT License

Copyright (c) 2020 Aakash Yadav

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """

        self.text = QLabel()
        self.text.setText(self.intro_text)
        self.text.setWordWrap(True)
        self.text.setAlignment(Qt.AlignCenter)

        self.license_layout = QVBoxLayout()
        self.license = QPlainTextEdit(self.license_text)
        self.license.setReadOnly(True)
        self.license_layout.addWidget(self.license)
        self.license_layout.setContentsMargins(200, 0, 200, 0)

        self.agree_box = QCheckBox("I have read the license agreement")
        # self.agree_box.setChecked(True)
        self.agree_box.stateChanged.connect(self.license_agree)
        self.license_layout.addWidget(self.agree_box)

        layout.addWidget(self.labelImage)
        layout.addWidget(self.text)
        layout.addLayout(self.license_layout)
        layout.addWidget(self.button)
        layout.addWidget(self.button2)
        layout.setSpacing(20)
        layout.setContentsMargins(200, 10, 200, 10)  #left, top, right, bottom

        self.setLayout(layout)
示例#46
0
    def __init__(self, parent=None):
        super(aliceGuiWidget, self).__init__(parent)

        hBoxLayoutSid = QHBoxLayout()
        hBoxLayoutSid.setSpacing(5)
        hBoxLayoutMac = QHBoxLayout()
        hBoxLayoutMac.setSpacing(5)

        vBoxLayout = QVBoxLayout()
        vBoxLayout.setSpacing(5)

        ssidLabel = QLabel("SID:", self)
        self.ssidLineEdit = QLineEdit(self)
        self.ssidLineEdit.setToolTip("SSID " + self.tr("Compatible") +
                                     " :\nAlice-*")
        self.ssidLineEdit.setMaxLength(8)
        self.ssidLineEdit.setInputMask("99999999;-")

        macLabel = QLabel("MAC:", self)
        self.macLineEdit = QLineEdit(self)
        self.macLineEdit.setToolTip(self.tr("Optional"))
        self.macLineEdit.setInputMask("HH:HH:HH:HH:HH:HH;_")

        self.outputTextEdit = QTextEdit(self)
        self.outputTextEdit.setReadOnly(True)

        self.calcPushButton = QPushButton(self.tr("Find"), self)
        self.calcPushButton.setIcon(getQIcon("key.png"))
        self.calcPushButton.setEnabled(0)

        hBoxLayoutSid.addWidget(ssidLabel)
        hBoxLayoutSid.addWidget(self.ssidLineEdit)
        hBoxLayoutMac.addWidget(macLabel)
        hBoxLayoutMac.addWidget(self.macLineEdit)

        hBoxLayoutSid.addWidget(self.calcPushButton)

        vBoxLayout.addLayout(hBoxLayoutSid)
        vBoxLayout.addLayout(hBoxLayoutMac)
        vBoxLayout.addWidget(self.outputTextEdit)

        self.setLayout(vBoxLayout)

        # @Grifisx: 	questa e' una classe di passaggio, poiche' il connect non puo' essere fatto con un metodo
        #			statico che riceve un self come argomento
        def slotFindKey():
            self.findKey(self)

        def enableBtn():
            if self.ssidLineEdit.text().length() == 8:
                if self.macLineEdit.text().length(
                ) == 17 or self.macLineEdit.text().length() == 5:
                    self.calcPushButton.setEnabled(1)
                else:
                    self.calcPushButton.setEnabled(0)
            else:
                self.calcPushButton.setEnabled(0)

        self.ssidLineEdit.textChanged.connect(enableBtn)
        self.macLineEdit.textChanged.connect(enableBtn)
        self.calcPushButton.clicked.connect(slotFindKey)
示例#47
0
class App(QFrame):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Web Browser")
        self.setMinimumSize(800, 600)
        self.create_app()
        self.setWindowIcon(QIcon('./logo.png'))

    def create_app(self):
        self.layout = QVBoxLayout()
        self.layout.setSpacing(0)
        self.layout.setContentsMargins(0, 0, 0, 0)

        # Create Tabs
        self.tabbar = QTabBar(movable=True, tabsClosable=True)
        self.tabbar.tabCloseRequested.connect(self.closeTab)
        self.tabbar.tabBarClicked.connect(self.switchTab)

        self.tabbar.setCurrentIndex(0)

        # Shortcut Key
        self.shortcutNewTab = QShortcut(QKeySequence("Ctrl+T"), self)
        self.shortcutNewTab.activated.connect(self.addTab)

        self.shortcutReload = QShortcut(QKeySequence("Ctrl+R"), self)
        self.shortcutReload.activated.connect(self.reloadPage)

        # Keep track of the tabs
        self.tabCount = 0
        self.tabs = []

        # Create Address Bar
        self.toolBar = QWidget()
        self.toolBarLayout = QHBoxLayout()

        self.addressbar = AddressBar()
        self.addressbar.returnPressed.connect(self.browseTo)

        # new tab button
        self.newTabButton = QPushButton("+")
        self.newTabButton.clicked.connect(self.addTab)

        # Set toolbar button
        self.BackButton = QPushButton("<<")
        self.ForwardButton = QPushButton(">>")
        self.BackButton.clicked.connect(self.goBackward)
        self.ForwardButton.clicked.connect(self.goForward)

        self.ReloadButton = QPushButton("Reload")
        self.ReloadButton.clicked.connect(self.reloadPage)

        # Build Toolbar
        self.toolBar.setObjectName("Toolbar")
        self.toolBar.setLayout(self.toolBarLayout)
        self.toolBarLayout.addWidget(self.BackButton)
        self.toolBarLayout.addWidget(self.ForwardButton)
        self.toolBarLayout.addWidget(self.ReloadButton)
        self.toolBarLayout.addWidget(self.addressbar)
        self.toolBarLayout.addWidget(self.newTabButton)

        # set main view
        self.container = QWidget()
        self.container.layout = QStackedLayout()
        self.container.setLayout(self.container.layout)

        # Add Widgets
        self.layout.addWidget(self.tabbar)
        self.layout.addWidget(self.toolBar)
        self.layout.addWidget(self.container)

        self.setLayout(self.layout)
        self.addTab()

        self.show()

    # The connection will sent the index of the tab that is clicked
    def closeTab(self, ind):
        self.tabbar.removeTab(ind)

    def addTab(self):
        ind = self.tabCount
        self.tabs.append(QWidget())
        self.tabs[ind].layout = QVBoxLayout()
        self.tabs[ind].layout.setContentsMargins(0, 0, 0, 0)

        # For tab switching
        self.tabs[ind].setObjectName("tab" + str(ind))

        self.tabs[ind].content = QWebEngineView()
        self.tabs[ind].content.load(QUrl.fromUserInput("http://google.com"))

        self.tabs[ind].content.titleChanged.connect(
            lambda: self.set_tab_content(ind, 'title'))
        self.tabs[ind].content.iconChanged.connect(
            lambda: self.set_tab_content(ind, 'icon'))
        self.tabs[ind].content.urlChanged.connect(
            lambda: self.set_tab_content(ind, "url"))

        # Add webview to tabs layout
        self.tabs[ind].layout.addWidget(self.tabs[ind].content)

        # set top level tab from list to layout
        self.tabs[ind].setLayout(self.tabs[ind].layout)

        # Add tab to top level
        self.container.layout.addWidget(self.tabs[ind])
        self.container.layout.setCurrentWidget(self.tabs[ind])

        # Set the tab at top of the screen
        self.tabbar.addTab("New Tab")
        self.tabbar.setTabData(ind, {
            "object": "tab" + str(ind),
            "initial": ind
        })
        self.tabbar.setCurrentIndex(ind)

        self.tabCount += 1

    def switchTab(self, i):
        tab_data = self.tabbar.tabData(i)['object']
        tab_content = self.findChild(QWidget, tab_data)
        self.container.layout.setCurrentWidget(tab_content)

        newUrl = tab_content.content.url().toString()
        self.addressbar.setText(newUrl)

    def browseTo(self):
        text = self.addressbar.text()

        # Get the index number of the current tab
        i = self.tabbar.currentIndex()
        # Get the name of the current tab
        tab = self.tabbar.tabData(i)['object']
        # Get the webview
        wv = self.findChild(QWidget, tab).content
        if "http" not in text:
            if "." not in text:
                url = "https://www.google.com/#q=" + text
            else:
                url = "https://" + text
        else:
            url = text
        wv.load(QUrl.fromUserInput(url))

    def set_tab_content(self, i, type):
        """
            self.tabs[i].objectName => tab1
            self.tabs[i].tabData(i)['object'] => tab1
        """

        tab_objectName = self.tabs[i].objectName()

        current_tab = self.tabbar.tabData(self.tabbar.currentIndex())['object']

        if current_tab == tab_objectName and type == "url":
            newUrl = self.findChild(QWidget,
                                    tab_objectName).content.url().toString()
            self.addressbar.setText(newUrl)
            return False

        count = 0
        running = True

        while running:
            tab_data_name = self.tabbar.tabData(count)

            if count >= 99:
                running = False

            if tab_objectName == tab_data_name['object']:
                if type == 'title':
                    new_title = self.findChild(QWidget,
                                               tab_objectName).content.title()
                    self.tabbar.setTabText(count, new_title)
                elif type == 'icon':
                    newIcon = self.findChild(QWidget,
                                             tab_objectName).content.icon()
                    self.tabbar.setTabIcon(count, newIcon)

                running = False
            else:
                count += 1

    def goBackward(self):
        activeTabIndex = self.tabbar.currentIndex()
        tab_name = self.tabbar.tabData(activeTabIndex)['object']
        tab_content = self.findChild(QWidget, tab_name).content

        tab_content.back()

    def goForward(self):
        activeTabIndex = self.tabbar.currentIndex()
        tab_name = self.tabbar.tabData(activeTabIndex)['object']
        tab_content = self.findChild(QWidget, tab_name).content

        tab_content.forward()

    def reloadPage(self):
        activeTabIndex = self.tabbar.currentIndex()
        tab_name = self.tabbar.tabData(activeTabIndex)['object']
        tab_content = self.findChild(QWidget, tab_name).content

        tab_content.reload()
示例#48
0
class MainWindow(QWidget):

    """The main window of qutebrowser.

    Adds all needed components to a vbox, initializes subwidgets and connects
    signals.

    Attributes:
        status: The StatusBar widget.
        _downloadview: The DownloadView widget.
        _tabbed_browser: The TabbedBrowser widget.
        _vbox: The main QVBoxLayout.
        _commandrunner: The main CommandRunner instance.
    """

    def __init__(self, win_id, parent=None):
        super().__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self._commandrunner = None
        self.win_id = win_id
        self.registry = objreg.ObjectRegistry()
        objreg.window_registry[win_id] = self
        objreg.register('main-window', self, scope='window', window=win_id)
        tab_registry = objreg.ObjectRegistry()
        objreg.register('tab-registry', tab_registry, scope='window',
                        window=win_id)

        message_bridge = message.MessageBridge(self)
        objreg.register('message-bridge', message_bridge, scope='window',
                        window=win_id)

        self.setWindowTitle('qutebrowser')
        if win_id == 0:
            self._load_geometry()
        else:
            self._set_default_geometry()
        log.init.debug("Initial mainwindow geometry: {}".format(
            self.geometry()))
        self._vbox = QVBoxLayout(self)
        self._vbox.setContentsMargins(0, 0, 0, 0)
        self._vbox.setSpacing(0)

        log.init.debug("Initializing downloads...")
        download_manager = downloads.DownloadManager(win_id, self)
        objreg.register('download-manager', download_manager, scope='window',
                        window=win_id)

        self._downloadview = downloadswidget.DownloadView(win_id)
        self._vbox.addWidget(self._downloadview)
        self._downloadview.show()

        self._tabbed_browser = tabbedbrowser.TabbedBrowser(win_id)
        objreg.register('tabbed-browser', self._tabbed_browser, scope='window',
                        window=win_id)
        self._vbox.addWidget(self._tabbed_browser)

        self.status = bar.StatusBar(win_id)
        self._vbox.addWidget(self.status)

        self._completion = completion.CompletionView(win_id, self)

        self._commandrunner = runners.CommandRunner(win_id)

        log.init.debug("Initializing search...")
        search_runner = runners.SearchRunner(self)
        objreg.register('search-runner', search_runner, scope='window',
                        window=win_id)

        log.init.debug("Initializing modes...")
        modeman.init(self.win_id, self)

        self._connect_signals()
        QTimer.singleShot(0, functools.partial(
            modeman.enter, win_id, usertypes.KeyMode.normal, 'init'))

        # When we're here the statusbar might not even really exist yet, so
        # resizing will fail. Therefore, we use singleShot QTimers to make sure
        # we defer this until everything else is initialized.
        QTimer.singleShot(0, self._connect_resize_completion)
        objreg.get('config').changed.connect(self.on_config_changed)
        #self.retranslateUi(MainWindow)
        #self.tabWidget.setCurrentIndex(0)
        #QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def __repr__(self):
        return utils.get_repr(self)

    @pyqtSlot(str, str)
    def on_config_changed(self, section, option):
        """Resize the completion if related config options changed."""
        if section == 'completion' and option in ('height', 'shrink'):
            self.resize_completion()

    @classmethod
    def spawn(cls, show=True):
        """Create a new main window.

        Args:
            show: Show the window after creating.

        Return:
            The new window id.
        """
        win_id = next(win_id_gen)
        win = MainWindow(win_id)
        if show:
            win.show()
        return win_id

    def _load_geometry(self):
        """Load the geometry from the state file."""
        state_config = objreg.get('state-config')
        try:
            data = state_config['geometry']['mainwindow']
            log.init.debug("Restoring mainwindow from {}".format(data))
            geom = base64.b64decode(data, validate=True)
        except KeyError:
            # First start
            self._set_default_geometry()
        except binascii.Error:
            log.init.exception("Error while reading geometry")
            self._set_default_geometry()
        else:
            try:
                ok = self.restoreGeometry(geom)
            except KeyError:
                log.init.exception("Error while restoring geometry.")
                self._set_default_geometry()
            if not ok:
                log.init.warning("Error while restoring geometry.")
                self._set_default_geometry()

    def _connect_resize_completion(self):
        """Connect the resize_completion signal and resize it once."""
        self._completion.resize_completion.connect(self.resize_completion)
        self.resize_completion()

    def _set_default_geometry(self):
        """Set some sensible default geometry."""
        self.setGeometry(QRect(50, 50, 800, 600))

    def _get_object(self, name):
        """Get an object for this window in the object registry."""
        return objreg.get(name, scope='window', window=self.win_id)

    def _connect_signals(self):
        """Connect all mainwindow signals."""
        # pylint: disable=too-many-locals,too-many-statements
        key_config = objreg.get('key-config')

        status = self._get_object('statusbar')
        keyparsers = self._get_object('keyparsers')
        completion_obj = self._get_object('completion')
        tabs = self._get_object('tabbed-browser')
        cmd = self._get_object('status-command')
        completer = self._get_object('completer')
        search_runner = self._get_object('search-runner')
        message_bridge = self._get_object('message-bridge')
        mode_manager = self._get_object('mode-manager')
        prompter = self._get_object('prompter')
        download_manager = self._get_object('download-manager')

        # misc
        self._tabbed_browser.close_window.connect(self.close)
        mode_manager.entered.connect(hints.on_mode_entered)

        # status bar
        mode_manager.entered.connect(status.on_mode_entered)
        mode_manager.left.connect(status.on_mode_left)
        mode_manager.left.connect(cmd.on_mode_left)
        mode_manager.left.connect(prompter.on_mode_left)

        # commands
        keyparsers[usertypes.KeyMode.normal].keystring_updated.connect(
            status.keystring.setText)
        cmd.got_cmd.connect(self._commandrunner.run_safely)
        cmd.got_search.connect(search_runner.search)
        cmd.got_search_rev.connect(search_runner.search_rev)
        cmd.returnPressed.connect(tabs.on_cmd_return_pressed)
        search_runner.do_search.connect(tabs.search)
        tabs.got_cmd.connect(self._commandrunner.run_safely)

        # config
        for obj in keyparsers.values():
            key_config.changed.connect(obj.on_keyconfig_changed)

        # messages
        message_bridge.s_error.connect(status.disp_error)
        message_bridge.s_info.connect(status.disp_temp_text)
        message_bridge.s_set_text.connect(status.set_text)
        message_bridge.s_maybe_reset_text.connect(status.txt.maybe_reset_text)
        message_bridge.s_set_cmd_text.connect(cmd.set_cmd_text)
        message_bridge.s_question.connect(prompter.ask_question,
                                          Qt.DirectConnection)

        # statusbar
        # FIXME some of these probably only should be triggered on mainframe
        # loadStarted.
        # https://github.com/The-Compiler/qutebrowser/issues/112
        tabs.current_tab_changed.connect(status.prog.on_tab_changed)
        tabs.cur_progress.connect(status.prog.setValue)
        tabs.cur_load_finished.connect(status.prog.hide)
        tabs.cur_load_started.connect(status.prog.on_load_started)

        tabs.current_tab_changed.connect(status.percentage.on_tab_changed)
        tabs.cur_scroll_perc_changed.connect(status.percentage.set_perc)

        tabs.current_tab_changed.connect(status.txt.on_tab_changed)
        tabs.cur_statusbar_message.connect(status.txt.on_statusbar_message)
        tabs.cur_load_started.connect(status.txt.on_load_started)

        tabs.current_tab_changed.connect(status.url.on_tab_changed)
        tabs.cur_url_text_changed.connect(status.url.set_url)
        tabs.cur_link_hovered.connect(status.url.set_hover_url)
        tabs.cur_load_status_changed.connect(status.url.on_load_status_changed)

        # command input / completion
        mode_manager.left.connect(tabs.on_mode_left)
        cmd.clear_completion_selection.connect(
            completion_obj.on_clear_completion_selection)
        cmd.hide_completion.connect(completion_obj.hide)

        # downloads
        tabs.start_download.connect(download_manager.fetch)

        # quickmark completion
        quickmark_manager = objreg.get('quickmark-manager')
        quickmark_manager.changed.connect(completer.init_quickmark_completions)

    @pyqtSlot()
    def resize_completion(self):
        """Adjust completion according to config."""
        # Get the configured height/percentage.
        confheight = str(config.get('completion', 'height'))
        if confheight.endswith('%'):
            perc = int(confheight.rstrip('%'))
            height = self.height() * perc / 100
        else:
            height = int(confheight)
        # Shrink to content size if needed and shrinking is enabled
        if config.get('completion', 'shrink'):
            contents_height = (
                self._completion.viewportSizeHint().height() +
                self._completion.horizontalScrollBar().sizeHint().height())
            if contents_height <= height:
                height = contents_height
        else:
            contents_height = -1
        # hpoint now would be the bottom-left edge of the widget if it was on
        # the top of the main window.
        topleft_y = self.height() - self.status.height() - height
        topleft_y = qtutils.check_overflow(topleft_y, 'int', fatal=False)
        topleft = QPoint(0, topleft_y)
        bottomright = self.status.geometry().topRight()
        rect = QRect(topleft, bottomright)
        if rect.isValid():
            self._completion.setGeometry(rect)

    @cmdutils.register(instance='main-window', scope='window')
    @pyqtSlot()
    def close(self):
        """Close the current window.

        //

        Extend close() so we can register it as a command.
        """
        super().close()

    def resizeEvent(self, e):
        """Extend resizewindow's resizeEvent to adjust completion.

        Args:
            e: The QResizeEvent
        """
        super().resizeEvent(e)
        self.resize_completion()
        self._downloadview.updateGeometry()
        self._tabbed_browser.tabBar().refresh()

    def closeEvent(self, e):
        """Override closeEvent to display a confirmation if needed."""
        confirm_quit = config.get('ui', 'confirm-quit')
        count = self._tabbed_browser.count()
        if confirm_quit == 'never':
            pass
        elif confirm_quit == 'multiple-tabs' and count <= 1:
            pass
        else:
            text = "Close {} {}?".format(
                count, "tab" if count == 1 else "tabs")
            confirmed = message.ask(self.win_id, text,
                                    usertypes.PromptMode.yesno, default=True)
            if not confirmed:
                log.destroy.debug("Cancelling losing of window {}".format(
                    self.win_id))
                e.ignore()
                return
        e.accept()
        objreg.get('app').geometry = bytes(self.saveGeometry())
        log.destroy.debug("Closing window {}".format(self.win_id))
        self._tabbed_browser.shutdown()
示例#49
0
class Performance(QWidget):

    def __init__(self) -> None :
        super(Performance, self).__init__()
        
        self.title = "Student Performance Prediction"
        self.sub_head = QLabel("Student's Detail")
        self.sub_head.setFont(QFont("Times",24, weight=QFont.Bold))
        self.label = QLabel(self)
        """"pixmap = QPixmap('std.jpg')
        self.label.setPixmap(pixmap)
        self.label.resize(pixmap.width(),pixmap.height())
        self.label.setGeometry(700,50,1600,1066)"""
        
        
        self.movie = QMovie("wow.gif")
        self.movie.frameChanged.connect(self.repaint)
        self.setGeometry(700,500,255,276)
        self.movie.start()
                
        self.l1 = QLineEdit()
        self.l2 = QLineEdit()
        self.l3 = QLineEdit()
        self.l4 = QLineEdit()
        self.l5 = QLineEdit()
        self.l6 = QLineEdit()
        self.l7 = QLineEdit()
        self.l8 = QLineEdit()
        self.l9 = QLineEdit()
        self.l10 = QLineEdit()
        self.l11 = QLineEdit()
        self.l12 = QLineEdit()
        self.l13 = QLineEdit()
        self.l14 = QLineEdit()
        self.l15 = QLineEdit()
        self.l16 = QLineEdit()
        self.l17 = QLineEdit()
        self.l18 = QLineEdit()
        
        self.t1 = QLabel("Enter Student Age:                     ")
        self.t2 = QLabel("Enter Mother's Education:              ")
        self.t3 = QLabel("Enter Father's Education:              ")
        self.t4 = QLabel("Enter Travel Time:                     ")
        self.t5 = QLabel("Enter Student no. of Failure:          ")
        self.t6 = QLabel("Enter School Support:                  ")
        self.t7 = QLabel("Enter Family Support:                  ")
        self.t8 = QLabel("Enter Paid:                            ")
        self.t9 = QLabel("Enter Activity Enrollment:             ")
        self.t10 = QLabel("Enter Internet Access:                ")
        self.t11 = QLabel("Enter Free Time:                      ")
        self.t12 = QLabel("Enter level of going out:             ")
        self.t13 = QLabel("Consumption of daily alcohol?:        ")
        self.t14 = QLabel("Consumption of weekly alcohol?:       ")
        self.t15 = QLabel("Current health status?:               ")
        self.t16 = QLabel("Absent level?:                        ")
        self.t17 = QLabel("Enter First Assesment Grade:          ")
        self.t18 = QLabel("Enter Second Assesment Grade:         ")
       
        
        self.r1 = QLabel("(15-25)")
        self.r2 = QLabel("(0-4)")
        self.r3 = QLabel("(0-4)")
        self.r4 = QLabel("(1-4)")
        self.r5 = QLabel("(1-4)")
        self.r6 = QLabel("(0[NO] or 1[YES])")
        self.r7 = QLabel("(0[NO] or 1[YES])")
        self.r8 = QLabel("(0[NO] or 1[YES])")
        self.r9 = QLabel("(0[NO] or 1[YES])")
        self.r10 = QLabel("(0[NO] or 1[YES])")
        self.r11 = QLabel("(0-5)")
        self.r12 = QLabel("(0-5)")
        self.r13= QLabel("(0-5)")
        self.r14 = QLabel("(0-5)")
        self.r15 = QLabel("(0-5)")
        self.r16 = QLabel("(0-93)")
        self.r17 = QLabel("(0-20)")
        self.r18 = QLabel("(0-20)")
        
        self.h1 = QHBoxLayout()
        self.h0 = QHBoxLayout()
        self.h2 = QHBoxLayout()
        self.h3 = QHBoxLayout()
        self.h4 = QHBoxLayout()
        self.h5 = QHBoxLayout()
        self.h6 = QHBoxLayout()
        self.h7 = QHBoxLayout()
        self.h8 = QHBoxLayout()
        self.h9 = QHBoxLayout()
        self.h10 = QHBoxLayout()
        self.h11 = QHBoxLayout()
        self.h12 = QHBoxLayout()
        self.h13 = QHBoxLayout()
        self.h14 = QHBoxLayout()
        self.h15 = QHBoxLayout()
        self.h16 = QHBoxLayout()
        self.h17 = QHBoxLayout()
        self.h18 = QHBoxLayout()
        
        self.clbtn = QPushButton("CLEAR")
        self.clbtn.setFixedWidth(100)
        self.submit = QPushButton("SUBMIT")
        self.submit.setFixedWidth(100)
        self.graph = QPushButton("SHOW GRAPH")
        self.graph.setFixedWidth(100)
        self.v1_box = QVBoxLayout()
        self.v2_box = QVBoxLayout()
        self.v3_box = QVBoxLayout()
        self.final_hbox = QHBoxLayout()
        self.initui()

        
        
    def paintEvent(self, event):
        currentFrame = self.movie.currentPixmap()
        frameRect = currentFrame.rect()
        frameRect.moveCenter(self.rect().center())
        if frameRect.intersects(event.rect()):
            painter = QPainter(self)
            painter.drawPixmap(frameRect.left(), frameRect.top(), currentFrame)
            
            
    def initui(self) -> None:
        """ The gui is created and widgets elements are set here """
        
        rangeVal = QIntValidator(self)
        rangeVal.setRange(0,1)
        rangeVal1 = QIntValidator(self)
        rangeVal1.setRange(15,25)
        rangeVal2 = QIntValidator(self)
        rangeVal2.setRange(1,5)
        rangeVal3 = QIntValidator(self)
        rangeVal3.setRange(0,4)
        rangeVal4 = QIntValidator(self)
        rangeVal4.setRange(1,4)
        rangeVal5 = QIntValidator(self)
        rangeVal5.setRange(0,93)
        rangeVal6 = QIntValidator(self)
        rangeVal6.setRange(1,20)
        
               
        
        
        self.v1_box.addWidget(self.sub_head)
        self.v1_box.addSpacing(10)
        self.v1_box.setSpacing(5)
        self.l1.setValidator(rangeVal1)
        self.l2.setValidator(rangeVal3)
        self.l3.setValidator(rangeVal3)
        self.l4.setValidator(rangeVal4)
        self.l5.setValidator(rangeVal4)
        self.l6.setValidator(rangeVal)
        self.l7.setValidator(rangeVal)
        self.l8.setValidator(rangeVal)
        self.l9.setValidator(rangeVal)
        self.l10.setValidator(rangeVal)
        self.l11.setValidator(rangeVal2)
        self.l12.setValidator(rangeVal2)
        self.l13.setValidator(rangeVal2)
        self.l14.setValidator(rangeVal2)
        self.l15.setValidator(rangeVal2)
        self.l16.setValidator(rangeVal5)
        self.l17.setValidator(rangeVal6)
        self.l18.setValidator(rangeVal6)
        
        
        
        
        self.l1.setFixedSize(40,30)
        self.l2.setFixedSize(40,30)
        self.l3.setFixedSize(40,30)
        self.l4.setFixedSize(40,30)
        self.l5.setFixedSize(40,30)
        self.l6.setFixedSize(40,30)
        self.l7.setFixedSize(40,30)
        self.l8.setFixedSize(40,30)
        self.l9.setFixedSize(40,30)
        self.l10.setFixedSize(40,30)
        self.l11.setFixedSize(40,30)
        self.l12.setFixedSize(40,30)
        self.l13.setFixedSize(40,30)
        self.l14.setFixedSize(40,30)
        self.l15.setFixedSize(40,30)
        self.l16.setFixedSize(40,30)
        self.l17.setFixedSize(40,30)
        self.l18.setFixedSize(40,30)
        
        
        
        self.h1.addWidget(self.t1)
        self.h1.addWidget(self.l1)
        self.h1.addWidget(self.r1)        
        self.v1_box.addLayout(self.h1)
        
        self.h2.addWidget(self.t2)
        self.h2.addWidget(self.l2)
        self.h2.addWidget(self.r2)       
        self.v1_box.addLayout(self.h2)
        
        self.h3.addWidget(self.t3)
        self.h3.addWidget(self.l3)
        self.h3.addWidget(self.r3)       
        self.v1_box.addLayout(self.h3)
        
        self.h4.addWidget(self.t4)
        self.h4.addWidget(self.l4)
        self.h4.addWidget(self.r4)      
        self.v1_box.addLayout(self.h4)
        
        self.h5.addWidget(self.t5)
        self.h5.addWidget(self.l5)
        self.h5.addWidget(self.r5)      
        self.v1_box.addLayout(self.h5)
        
        self.h6.addWidget(self.t6)
        self.h6.addWidget(self.l6)
        self.h6.addWidget(self.r6)      
        self.v1_box.addLayout(self.h6)
        
        self.h7.addWidget(self.t7)
        self.h7.addWidget(self.l7)
        self.h7.addWidget(self.r7)      
        self.v1_box.addLayout(self.h7)
        
        self.h8.addWidget(self.t8)
        self.h8.addWidget(self.l8)
        self.h8.addWidget(self.r8)      
        self.v1_box.addLayout(self.h8)
        
        self.h9.addWidget(self.t9)
        self.h9.addWidget(self.l9)
        self.h9.addWidget(self.r9)      
        self.v1_box.addLayout(self.h9)
        
        self.h10.addWidget(self.t10)
        self.h10.addWidget(self.l10)
        self.h10.addWidget(self.r10)      
        self.v1_box.addLayout(self.h10)
        
        self.h11.addWidget(self.t11)
        self.h11.addWidget(self.l11)
        self.h11.addWidget(self.r11)      
        self.v1_box.addLayout(self.h11)
        
        self.h12.addWidget(self.t12)
        self.h12.addWidget(self.l12)
        self.h12.addWidget(self.r12)      
        self.v1_box.addLayout(self.h12)
        
        self.h13.addWidget(self.t13)
        self.h13.addWidget(self.l13)
        self.h13.addWidget(self.r13)      
        self.v1_box.addLayout(self.h13)
        
        self.h14.addWidget(self.t14)
        self.h14.addWidget(self.l14)
        self.h14.addWidget(self.r14)      
        self.v1_box.addLayout(self.h14)
        
        self.h15.addWidget(self.t15)
        self.h15.addWidget(self.l15)
        self.h15.addWidget(self.r15)      
        self.v1_box.addLayout(self.h15)
        
        self.h16.addWidget(self.t16)
        self.h16.addWidget(self.l16)
        self.h16.addWidget(self.r16)      
        self.v1_box.addLayout(self.h16)
        
        self.h17.addWidget(self.t17)
        self.h17.addWidget(self.l17)
        self.h17.addWidget(self.r17)      
        self.v1_box.addLayout(self.h17)
        
        self.h18.addWidget(self.t18)
        self.h18.addWidget(self.l18)
        self.h18.addWidget(self.r18)      
        self.v1_box.addLayout(self.h18)
        
    
        self.h6 = QHBoxLayout()
        self.submit.clicked.connect(lambda: self.test_input())
        self.submit.setToolTip("Click to check the performance of Student")
        self.clbtn.clicked.connect(lambda: self.clfn())
        self.graph.clicked.connect(lambda: self.getgraph())
        self.h6.addWidget(self.submit)
        self.h6.addWidget(self.clbtn)
        self.h6.addWidget(self.graph)
        self.v1_box.addLayout(self.h6)
        self.report_ui()
        self.final_hbox.addLayout(self.v1_box)
        self.final_hbox.addSpacing(70)
        self.final_hbox.addLayout(self.v2_box)
        self.final_hbox.addSpacing(70)
        self.final_hbox.addLayout(self.v3_box)
        self.setLayout(self.final_hbox)

    def report_ui(self):
        self.v2_box.setSpacing(6)
        self.report_subhead = QLabel("About")
        self.report_subhead.setAlignment(Qt.AlignCenter)
        self.report_subhead.setFont(QFont("Times",24, weight=QFont.Bold))
        self.v2_box.addWidget(self.report_subhead)
        self.details = QLabel("This model uses Naive Bayes classifier.\nWe have used student dataset from UCI archive.")
        self.details.setFont(QFont("Arial",14, weight=QFont.Bold))
        self.details.setAlignment(Qt.AlignLeft)
        self.details.setWordWrap(True)
        self.model_details = QLabel("Fill details and press submit to see details. \n\n\n0 being the lowest and increasing")
        self.model_details.setWordWrap(True)
        self.v2_box.addWidget(self.details)
        self.results = QLabel(" ")
        self.results.setWordWrap(True)
        self.v2_box.addWidget(self.results)
        self.v2_box.addWidget(self.model_details)
        
        

    def clfn(self):
        """ clear all the text fields via clear button"""
        self.l1.clear()
        self.l2.clear()
        self.l3.clear()
        self.l3.clear()
        self.l4.clear()
        self.l5.clear()
        self.l6.clear()
        self.l7.clear()
        self.l8.clear()
        self.l9.clear()
        self.l10.clear()
        self.l11.clear()
        self.l12.clear()
        self.l13.clear()
        self.l14.clear()
        self.l15.clear()
        self.l16.clear()
        self.l17.clear()
        self.l18.clear()
        
        self.report_subhead.setText("About")
        self.model_details.setText("Fill details and press submit to see details.\n\n\n0 being the lowest and increasing")
        self.results.setText(" ")
        self.details.setText("This model uses Naive Bayes Algorithm.\nWe have used student dataset from UCI archive.")
    
    
    
    def test_input(self) -> None:
        global my_dic, output
        my_dic = {"age":int(self.l1.text()), "Medu":int(self.l2.text()),"Fedu":int(self.l3.text()), "traveltime":int(self.l4.text()), "failures": int(self.l5.text()),
                  "schoolsup": int(self.l6.text()),"famsup": int(self.l7.text()),"paid": int(self.l8.text()),"activities": int(self.l9.text()),"internet": int(self.l10.text()),
                  "freetime": int(self.l11.text()),"goout": int(self.l12.text()),"Dalc": int(self.l13.text()),"Walc": int(self.l14.text()),"health": int(self.l15.text()),"absences": int(self.l5.text()),
                  "G1": int(self.l17.text()),"G2": int(self.l18.text())}
        
        output = model.get_input(my_dic)
        self.report_subhead.setText("About")
        self.model_details.setText("This model uses Naive Bayes Algorithm. We have used student dataset from UCI archive.")
        if output == 0:
            self.results.setText("The model predicts that the academic performance based on the given data attributes will be POOR")
        elif output == 1:
            self.results.setText("The model predicts that the academic performance based on the given data attributes will be FAIR")
        else:
            self.results.setText("The model predicts that the academic performance based on the given data attributes will be GOOD")
        self.results.setFont(QFont("Arial",14, weight=QFont.Bold))        
  
    def getgraph(self) -> None:
        global my_dic, output
        import matplotlib.pyplot as plt
        %matplotlib qt
        print(output)
        output=output_reverse(output)
        langs = ['g1', 'g2', 'final']
        students = [my_dic['G1'],my_dic['G2'],output]
        fig = plt.figure()
        
        plt.bar(langs,students)
        plt.show()
        print(output,my_dic['G1'],my_dic['G2'])
    
    def mwindow(self) -> None:
        """ window features are set here and application is loaded into display"""
        self.setFixedSize(1200, 900)
        self.setWindowTitle("Student Performance Prediction")
        p = QPalette()
        gradient = QLinearGradient(0, 0, 0, 400)
        gradient.setColorAt(0.0, QColor(130, 160, 230))
        gradient.setColorAt(1.0, QColor(160, 220, 180))
        p.setBrush(QPalette.Window, QBrush(gradient))
        self.setPalette(p)
        self.show()       
示例#50
0
ANS.setLayout(layout_res)

ANS.hide()

line_1.addWidget(question, alignment=(Qt.AlignHCenter | Qt.AlignVCenter))
line_2.addWidget(ratn)
line_2.addWidget(ANS)
line_3.addWidget(ok, stretch=2)

line_3.addStretch(1)

layout_main.addLayout(line_1, stretch=2)
layout_main.addLayout(line_2, stretch=8)
layout_main.addStretch(1)
layout_main.addLayout(line_3, stretch=1)
layout_main.setSpacing(5)

answer = [rbtn1, rbtn2, rbtn3, rbtn4]


def ask(q: Question):
    shuffle(answer)
    answer[0].setText(q.right_ans)
    answer[1].setText(q.wrong_1)
    answer[2].setText(q.wrong_2)
    answer[3].setText(q.wrong_3)
    question.setText(q.question)
    correct.setText(q.right_ans)
    show_question()

示例#51
0
    def establishLayout(self):
        cWid = QWidget()
        self.setCentralWidget(cWid)

        self.currentPlaylist = QListWidget()
        self.currentPlaylist.setFocusPolicy(Qt.NoFocus)
        self.currentPlaylist.itemDoubleClicked.connect(self.currentSelection)
        self.currentPlaylist.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.currentPlaylist.addAction(self.playlistAdd)
        self.currentPlaylist.addAction(self.playlistDel)

        self.playlistView = QListWidget()
        self.playlistView.adjustSize()
        self.playlistView.setMaximumWidth(100)
        self.playlistView.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.playlistView.addAction(self.delPlaylist)
        self.playlistView.itemDoubleClicked.connect(self.parsePlaylist)

        self.seekSlider = QSlider(Qt.Horizontal)
        self.currentTimeLabel = QLabel('00:00')
        self.totalTimeLabel = QLabel('00:00')
        self.seekSlider.setRange(0, self.mediaPlayer.duration() / 1000)
        self.seekSlider.sliderMoved.connect(self.seek)
        self.seekSlider.valueChanged.connect(self.mediaPlayer.setPosition)

        # Set up splitter layout to hold the display widgets
        displaySplitter = QSplitter()
        displaySplitter.addWidget(self.playlistView)
        displaySplitter.addWidget(self.currentPlaylist)

        # Set up layout to hold the splitter layout
        displayLayout = QHBoxLayout()
        displayLayout.addWidget(displaySplitter)

        # Set up layout for Playlist Controls
        controls = PlaylistControls()
        controls.setState(self.mediaPlayer.state())
        controls.setVolume(self.mediaPlayer.volume())
        controls.setMuted(self.mediaPlayer.isMuted())
        controls.play.connect(self.mediaPlayer.play)
        controls.pause.connect(self.mediaPlayer.pause)
        controls.stop.connect(self.mediaPlayer.stop)
        controls.next.connect(self.playlist.next)
        controls.previous.connect(self.previousMedia)
        controls.changeVolume.connect(self.mediaPlayer.setVolume)
        controls.muteVolume.connect(self.mediaPlayer.setMuted)
        controls.shuffle.connect(self.playlist.shuffle)
        controls.repeatAll.connect(self.setRepeatAll)
        controls.repeatOne.connect(self.setRepeatOne)

        self.mediaPlayer.stateChanged.connect(controls.setState)
        self.mediaPlayer.volumeChanged.connect(controls.setVolume)
        self.mediaPlayer.mutedChanged.connect(controls.setMuted)

        controlLayout = QHBoxLayout()
        controlLayout.addWidget(controls)

        # Set up layout for Seek controls
        seekLayout = QHBoxLayout()
        seekLayout.addWidget(self.currentTimeLabel)
        seekLayout.addWidget(self.seekSlider)
        seekLayout.addWidget(self.totalTimeLabel)

        mainLayout = QVBoxLayout()
        layoutHelp(mainLayout, (displayLayout, seekLayout, controlLayout))
        mainLayout.setSpacing(0)

        self.setLayout(mainLayout)
        cWid.setLayout(mainLayout)

        if not self.mediaPlayer.isAvailable():
            QMessageBox.warning(self, "Service not available")

            controls.setEnabled(False)
            self.currentPlaylist.setEnabled(False)

        self.metaDataChanged()
        self.statusBar()
示例#52
0
class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent, flags=Qt.WindowFlags())
        self.parent = parent
        self.icon = parent.icon

        self.main_layout = QVBoxLayout()

        self.header_layout = QHBoxLayout()
        self.header_left_layout = QVBoxLayout()
        self.icon_layout = QVBoxLayout()
        self.icon_label = QLabel()
        self.header_right_layout = QVBoxLayout()
        self.app_name = QLabel(__name__.title())
        self.app_version = QLabel(__version__)
        self.author_name = QLabel(f'(c)2018 by {__author__}')

        self.choose_mode = LabeledComboBox(values=('Find and delete orphan files',
                                                   'Delete orphan files'),
                                           label='Choose mode:',
                                           vertical=True)
        self.load_defaults_button = QPushButton('Fill in default values')

        self.specific_layout = QVBoxLayout()
        self.specific_area_stack = QStackedWidget(self)
        self.find_orphans = FindOrphans()
        self.delete_orphans = DeleteOrphans()
        self.variable_area_widgets = (
            self.find_orphans,
            self.delete_orphans,
        )

        self.buttons_layout = QHBoxLayout()
        self.about_button = QPushButton('About...')
        self.cancel_button = QPushButton('Cancel')
        self.ok_button = QPushButton('OK')

        self.init_ui()

    def init_ui(self):
        self.choose_mode.input_widget.currentIndexChanged.connect(self.action_changed)
        self.load_defaults_button.clicked.connect(self.fill_in_default_values)
        self.about_button.clicked.connect(self.open_about)
        self.cancel_button.clicked.connect(self.quit_action)
        self.ok_button.clicked.connect(self.run_action)

        self.main_layout.setContentsMargins(15, 10, 15, 10)
        self.main_layout.addLayout(self.header_layout, 0)
        self.main_layout.addLayout(self.specific_layout, 0)
        self.main_layout.addLayout(self.buttons_layout, 0)
        self.main_layout.addStretch(2)

        self.header_layout.setSpacing(10)
        self.header_layout.addLayout(self.header_left_layout, 2)
        self.header_layout.addLayout(self.icon_layout, 0)
        self.header_layout.addLayout(self.header_right_layout, 0)

        self.header_left_layout.addWidget(self.choose_mode, 0, Qt.AlignBottom)
        self.header_left_layout.addWidget(self.load_defaults_button, 0, Qt.AlignBottom)

        self.icon_layout.setContentsMargins(0, 15, 0, 0)
        self.icon_layout.addWidget(self.icon_label, 0, Qt.AlignBottom)
        self.icon_label.setPixmap(self.icon)
        self.icon_label.setAlignment(Qt.AlignCenter)
        self.icon_label.setFixedWidth(100)
        self.icon_label.setFixedHeight(85)
        self.icon_label.setContentsMargins(75, 75, 75, 150)

        self.header_right_layout.addWidget(self.app_name, 0, Qt.AlignBottom)
        self.header_right_layout.addWidget(self.app_version, 0, Qt.AlignBottom)
        self.header_right_layout.addWidget(self.author_name, 0, Qt.AlignBottom)
        self.app_name.setAlignment(Qt.AlignCenter)
        font = QFont()
        font.setBold(True)
        font.setPointSize(20)
        self.app_name.setFont(font)
        self.app_version.setAlignment(Qt.AlignCenter)
        self.author_name.setAlignment(Qt.AlignCenter)

        self.load_defaults_button.setMinimumWidth(250)
        self.load_defaults_button.setMinimumHeight(40)
        self.load_defaults_button.setStyleSheet("background-color: darkseagreen")

        self.specific_layout.setContentsMargins(0, 0, 0, 0)
        self.specific_layout.setSpacing(0)
        self.specific_layout.addWidget(self.specific_area_stack, Qt.AlignBottom)

        for widget in self.variable_area_widgets:
            self.specific_area_stack.addWidget(widget)

        self.buttons_layout.setContentsMargins(0, 10, 0, 0)
        self.buttons_layout.addStretch(2)
        self.buttons_layout.addWidget(self.about_button, 0, Qt.AlignBottom)
        self.buttons_layout.addWidget(self.cancel_button, 0, Qt.AlignBottom)
        self.buttons_layout.addWidget(self.ok_button, 0, Qt.AlignBottom)

        self.setLayout(self.main_layout)

    def action_changed(self, index):
        self.specific_area_stack.setCurrentIndex(index)
        self.change_defaults_button_status(index)

    def change_defaults_button_status(self, index):
        if index == 1:
            self.load_defaults_button.setEnabled(False)
        else:
            self.load_defaults_button.setEnabled(True)

    def fill_in_default_values(self):
        path_to_prefs_file = zotler.get_prefs_file(silent=True)
        self.find_orphans.path_to_prefs_file.text = path_to_prefs_file

        zotero_home_dir = os.path.join(str(Path.home()), 'Zotero')
        self.find_orphans.path_to_database_file.text = os.path.join(zotero_home_dir,
                                                                    'zotero.sqlite')

    def open_about(self):
        self.parent.about_dialog.show()

    def run_action(self):
        if self.choose_mode.text == 'Find and delete orphan files':
            zotero_prefs = self.find_orphans.path_to_prefs_file.text
            zotero_dbase = self.find_orphans.path_to_database_file.text
            path_to_output_file = self.find_orphans.path_to_output_file.text.strip()

            error_messages = (
                i
                for i in (self.validate_path(zotero_prefs),
                          self.validate_path(zotero_dbase))
                if i is not None
            )

            joined_messages = '\n'.join(error_messages)
            if len(joined_messages) > 0:
                self.show_error_dialog(joined_messages)
            else:
                self.find_orphans_action(zotero_prefs, zotero_dbase, path_to_output_file)

        elif self.choose_mode.text == 'Delete orphan files':
            path_to_orphans_file = self.delete_orphans.path_to_list_of_orphans.text.strip()

            error_message = self.validate_path(path_to_orphans_file)
            if error_message is None:
                self.delete_orphans_action(path_to_orphans_file)
            else:
                self.show_error_dialog(error_message)
        else:
            raise InvalidModeError('Invalid mode\'s been chosen.')

    def find_orphans_action(self, zotero_prefs, zotero_dbase, path_to_output_file):
        orphan_files = zotler.create_set_of_orphans(zotero_dbase, zotero_prefs)

        if path_to_output_file == '':
            _, path_to_output_file = tempfile.mkstemp(prefix='zotler_gui-')

        with open(path_to_output_file, 'w') as output_file:
            print('\n'.join(orphan_files), file=output_file)

        self.delete_orphans_action(path_to_output_file)

    def delete_orphans_action(self, path_to_orphans_file):
        text_dialog = ShowStdinDialog(self, file_path=path_to_orphans_file)
        is_accepted = text_dialog.exec()
        if is_accepted:
            with open(path_to_orphans_file, 'r') as file:
                zotler.remove_files(file.readlines())

        self.quit_action()

    @staticmethod
    def show_error_dialog(joined_messages):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Critical)
        msg.setWindowTitle('Error')
        msg.setText(joined_messages)
        msg.exec_()

    @staticmethod
    def validate_path(path, is_directory=False, is_existing=True):
        message = None
        if is_existing:
            if not os.path.exists(path):
                message = f'{path} doesn\'t exist'
            elif is_directory and not os.path.isdir(path):
                message = f'{path} is not a directory'
            elif not is_directory and not os.path.isfile(path):
                message = f'{path} is not a file'

        return message

    @staticmethod
    def quit_action():
        QCoreApplication.instance().quit()
示例#53
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.graphicsView = QGraphicsView()
        scene = QGraphicsScene(self.graphicsView)
        scene.setSceneRect(0, 0, 384, 482)
        self.graphicsView.setScene(scene)
        self.display = Display()
        scene.addItem(self.display)
        self.graphicsView.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        self.timer = QTimer(self)
        self.timer.setInterval(16)
        self.timer.timeout.connect(self.update_yPhase)
        self.timer.start()

        self.fileName = os.getcwd() + '/scores/SP/'

        style = '''
            QPushButton{
                background-color: transparent;
                color:#7F7F7F;
                border:2px solid #7F7F7F;
            }
            QPushButton:checked{
                background-color:transparent;
                color:#3FAFFF;
                border:2px solid #3FAFFF;
            }
            QPushButton#style{
                font:bold 16px;
                border-radius: 4px;
            }
            QPushButton#file{
                font:bold 12px;
                border-radius: 4px;
            }
            QLineEdit{
                background-color: transparent;
                border:1px solid #CFCFCF;
                color:#CFCFCF;
            }
            '''

        #           name,           label,      objectName,     size,       check,          connect

        self.button('fileOpen', 'OPEN', 'file', 50, 20, True, False,
                    'fileOpen', style)
        self.button('fileNew', 'NEW', 'file', 50, 20, True, False, 'fileNew',
                    style)
        self.button('fileEdit', 'EDIT', 'file', 50, 20, True, False,
                    'fileEdit', style)
        self.button('fileSave', 'SAVE', 'file', 50, 20, True, False,
                    'fileSave', style)

        self.button('player1', '1P', 'style', 40, 24, True, True, 'player1',
                    style)
        self.button('player2', '2P', 'style', 40, 24, True, False, 'player2',
                    style)
        self.button('off', 'OFF', 'style', 180, 24, True, True, 'off', style)
        self.button('random', 'RANDOM', 'style', 180, 24, True, False,
                    'random', style)
        self.button('rRandom', 'R-RANDOM', 'style', 180, 24, True, False,
                    'rRandom', style)
        self.button('sRandom', 'S-RANDOM', 'style', 180, 24, True, False,
                    'sRandom', style)
        self.button('mirror', 'MIRROR', 'style', 180, 24, True, False,
                    'mirror', style)

        self.button('pencil', '/', 'style', 54, 24, True, False, 'pencil',
                    style)
        self.button('cnPencil', 'CN', 'style', 54, 24, True, False, 'cnPencil',
                    style)
        self.button('barPencil', '---', 'style', 54, 24, True, False,
                    'barPencil', style)
        self.button('bpmPencil', 'BPM', 'style', 54, 24, True, False,
                    'bpmPencil', style)

        self.button('grid16', '-16-', 'style', 60, 24, True, True, 'grid16',
                    style)
        self.button('grid32', '-32-', 'style', 60, 24, True, False, 'grid32',
                    style)
        self.button('grid64', '-64-', 'style', 60, 24, True, False, 'grid64',
                    style)
        self.button('grid12', '-12-', 'style', 60, 24, True, False, 'grid12',
                    style)
        self.button('grid24', '-24-', 'style', 60, 24, True, False, 'grid24',
                    style)
        self.button('grid48', '-48-', 'style', 60, 24, True, False, 'grid48',
                    style)

        #           name,           label_,                                                  width,  center
        self.label('url', '<p><font size="3" color="#CFCFCF">URL:</font></p>',
                   None, False)
        self.label('file',
                   '<p><font size="3" color="#CFCFCF">FILE:</font></p>', None,
                   False)
        self.label('genre', self.set_genre(), 280, True)
        self.label('title', self.set_title(), 280, True)
        self.label('artist', self.set_artist(), 280, True)
        self.label('level', self.set_level(), 280, True)

        #               name,   size,       pressed
        self.lineEdit('url', 230, 20, 'analyze_web', style)

        fileLayout = QGridLayout()
        fileLayout.setHorizontalSpacing(8)
        fileLayout.setVerticalSpacing(12)
        fileLayout.addWidget(self.urlLabel, 0, 0)
        fileLayout.addWidget(self.urlEdit, 0, 1, 1, 4)
        fileLayout.addWidget(self.fileLabel, 1, 0)
        fileLayout.addWidget(self.fileNewButton, 1, 1)
        fileLayout.addWidget(self.fileOpenButton, 1, 2)
        fileLayout.addWidget(self.fileEditButton, 1, 3)
        fileLayout.addWidget(self.fileSaveButton, 1, 4)
        fileLayout.setColumnStretch(5, 1)

        songInfoLayout = QVBoxLayout()
        songInfoLayout.setSpacing(24)
        songInfoLayout.addSpacing(20)
        songInfoLayout.addWidget(self.genreLabel)
        songInfoLayout.addWidget(self.titleLabel)
        songInfoLayout.addWidget(self.artistLabel)
        songInfoLayout.addWidget(self.levelLabel)
        songInfoLayout.addStretch()

        playerButtonLayout = QHBoxLayout()
        playerButtonLayout.setSpacing(12)
        playerButtonLayout.addWidget(self.player1Button)
        playerButtonLayout.addWidget(self.player2Button)
        playerButtonLayout.addStretch()

        styleLayout = QVBoxLayout()
        styleLayout.setSpacing(6)
        styleLayout.addWidget(self.offButton)
        styleLayout.addWidget(self.randomButton)
        styleLayout.addWidget(self.rRandomButton)
        styleLayout.addWidget(self.sRandomButton)
        styleLayout.addWidget(self.mirrorButton)

        toolsLayout = QGridLayout()
        toolsLayout.setHorizontalSpacing(12)
        toolsLayout.setVerticalSpacing(8)
        toolsLayout.addWidget(self.pencilButton, 0, 0)
        toolsLayout.addWidget(self.cnPencilButton, 0, 1)
        toolsLayout.addWidget(self.barPencilButton, 0, 2)
        toolsLayout.addWidget(self.bpmPencilButton, 0, 3)
        toolsLayout.setColumnStretch(4, 1)

        gridLayout = QGridLayout()
        gridLayout.setHorizontalSpacing(12)
        gridLayout.setVerticalSpacing(8)
        gridLayout.addWidget(self.grid16Button, 0, 0)
        gridLayout.addWidget(self.grid32Button, 0, 1)
        gridLayout.addWidget(self.grid64Button, 0, 2)
        gridLayout.addWidget(self.grid12Button, 1, 0)
        gridLayout.addWidget(self.grid24Button, 1, 1)
        gridLayout.addWidget(self.grid48Button, 1, 2)
        gridLayout.setColumnStretch(3, 1)

        propertyLayout = QVBoxLayout()
        propertyLayout.addLayout(fileLayout)
        propertyLayout.addSpacing(16)
        propertyLayout.addLayout(songInfoLayout)
        propertyLayout.addSpacing(32)
        propertyLayout.addLayout(playerButtonLayout)
        propertyLayout.addLayout(styleLayout)
        propertyLayout.addLayout(toolsLayout)
        propertyLayout.addLayout(gridLayout)
        propertyLayout.addStretch()

        mainLayout = QGridLayout()

        mainLayout.addWidget(self.graphicsView, 0, 0)
        mainLayout.addLayout(propertyLayout, 0, 1)
        mainLayout.setRowStretch(1, 1)

        self.update_layout()
        self.setLayout(mainLayout)
        self.setWindowTitle("IIDX simulator")
示例#54
0
class QUnFrameWindow(QWidget):
    """
    无边框窗口类
    """
    def __init__(self):
        super(QUnFrameWindow,
              self).__init__(None, Qt.FramelessWindowHint)  # 设置为顶级窗口,无边框
        self._padding = 5  # 设置边界宽度为5

        self.hour = 0
        self.minute = 1
        self.sldHour = QSlider(Qt.Horizontal)
        self.sldHour.setMinimum(0)
        self.sldHour.setMaximum(72)
        self.sldHour.setSingleStep(1)
        self.sldMinute = QSlider(Qt.Horizontal)
        self.sldMinute.setMinimum(1)
        self.sldMinute.setMaximum(60)
        self.sldMinute.setSingleStep(1)
        self.sldMinute.setValue(1)
        self.label = QLabel("00:01")
        self.label.setStyleSheet(
            "QLabel{color:rgb(0,0,0,255);font-size:50px;font-weight:normal;font-family:Arial;}"
        )
        self.cb = QRadioButton("执行")
        self.cb.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        self.cb.toggled.connect(self.openChange)
        self.sldHour.valueChanged.connect(self.updateHour)
        self.sldMinute.valueChanged.connect(self.updateMinute)

        self.initTitleLabel()  # 安放标题栏标签
        #self.setWindowTitle = self._setTitleText(self.setWindowTitle) # 用装饰器将设置WindowTitle名字函数共享到标题栏标签上
        # self.setWindowTitle()
        self.initLayout()  # 设置框架布局
        self.setFixedWidth(300)
        self.setFixedHeight(140)
        self.setMouseTracking(True)  # 设置widget鼠标跟踪
        self.initDrag()  # 设置鼠标跟踪判断默认值

    def updateTime(self):
        self.label.setText(str(self.hour) + ":" + str(self.minute))

    def updateHour(self):
        print("hour %s" % self.sldHour.value())
        self.hour = self.sldHour.value()
        self.updateTime()

    def updateMinute(self):
        print("minute %s" % self.sldMinute.value())
        self.minute = self.sldMinute.value()
        self.updateTime()

    def openChange(self, state):
        CREATE_NO_WINDOW = 0x08000000
        if state == True:
            print("open")
            subprocess.call("shutdown -s -t " +
                            str(self.hour * 3600 + self.minute * 60),
                            creationflags=CREATE_NO_WINDOW)
        else:
            print("close")
            subprocess.call('shutdown -a', creationflags=CREATE_NO_WINDOW)

    def initDrag(self):
        # 设置鼠标跟踪判断扳机默认值
        self._move_drag = False
        self._corner_drag = False
        self._bottom_drag = False
        self._right_drag = False

    def initTitleLabel(self):
        # 安放标题栏标签
        self._TitleLabel = QTitleLabel(self)
        self._TitleLabel.setMouseTracking(
            True)  # 设置标题栏标签鼠标跟踪(如不设,则标题栏内在widget上层,无法实现跟踪)
        self._TitleLabel.setIndent(10)  # 设置标题栏文本缩进
        self._TitleLabel.move(0, 0)  # 标题栏安放到左上角

    def initLayout(self):
        # 设置框架布局
        self._MainLayout = QVBoxLayout()
        self._MainLayout.setSpacing(0)
        self._MainLayout.addWidget(
            QLabel(), Qt.AlignLeft)  # 顶一个QLabel在竖放框架第一行,以免正常内容挤占到标题范围里
        self._MainLayout.addStretch()

        #
        hlayout = QHBoxLayout()

        hlayout.addWidget(self.label)
        hlayout.addWidget(self.cb)

        self._MainLayout.addLayout(hlayout)
        self._MainLayout.addWidget(self.sldHour)
        self._MainLayout.addWidget(self.sldMinute)
        #
        self.setLayout(self._MainLayout)

    def addLayout(self, QLayout):
        # 给widget定义一个addLayout函数,以实现往竖放框架的正确内容区内嵌套Layout框架
        self._MainLayout.addLayout(QLayout)

# def _setTitleText(self, func):
# 设置标题栏标签的装饰器函数
#  def wrapper(*args):
#  self._TitleLabel.setText(*args)
# return func(*args)
#return wrapper

    def setTitleAlignment(self, alignment):
        # 给widget定义一个setTitleAlignment函数,以实现标题栏标签的对齐方式设定
        self._TitleLabel.setAlignment(alignment | Qt.AlignVCenter)

    def setCloseButton(self, bool):
        # 给widget定义一个setCloseButton函数,为True时设置一个关闭按钮
        if bool == True:
            self._CloseButton = QTitleButton(b'\xef\x81\xb2'.decode("utf-8"),
                                             self)
            self._CloseButton.setObjectName(
                "CloseButton")  # 设置按钮的ObjectName以在qss样式表内定义不同的按钮样式
            self._CloseButton.setToolTip("关闭窗口")
            self._CloseButton.setMouseTracking(
                True)  # 设置按钮鼠标跟踪(如不设,则按钮在widget上层,无法实现跟踪)
            self._CloseButton.setFixedHeight(
                self._TitleLabel.height())  # 设置按钮高度为标题栏高度
            self._CloseButton.clicked.connect(self.close)  # 按钮信号连接到关闭窗口的槽函数

    def setMinMaxButtons(self, bool):
        # 给widget定义一个setMinMaxButtons函数,为True时设置一组最小化最大化按钮
        if bool == True:
            self._MinimumButton = QTitleButton(b'\xef\x80\xb0'.decode("utf-8"),
                                               self)
            self._MinimumButton.setObjectName(
                "MinMaxButton")  # 设置按钮的ObjectName以在qss样式表内定义不同的按钮样式
            self._MinimumButton.setToolTip("最小化")
            self._MinimumButton.setMouseTracking(
                True)  # 设置按钮鼠标跟踪(如不设,则按钮在widget上层,无法实现跟踪)
            self._MinimumButton.setFixedHeight(
                self._TitleLabel.height())  # 设置按钮高度为标题栏高度
            self._MinimumButton.clicked.connect(
                self.showMinimized)  # 按钮信号连接到最小化窗口的槽函数
            self._MaximumButton = QTitleButton(b'\xef\x80\xb1'.decode("utf-8"),
                                               self)
            self._MaximumButton.setObjectName(
                "MinMaxButton")  # 设置按钮的ObjectName以在qss样式表内定义不同的按钮样式
            self._MaximumButton.setToolTip("最大化")
            self._MaximumButton.setMouseTracking(
                True)  # 设置按钮鼠标跟踪(如不设,则按钮在widget上层,无法实现跟踪)
            self._MaximumButton.setFixedHeight(
                self._TitleLabel.height())  # 设置按钮高度为标题栏高度
            self._MaximumButton.clicked.connect(
                self._changeNormalButton)  # 按钮信号连接切换到恢复窗口大小按钮函数

    def _changeNormalButton(self):
        # 切换到恢复窗口大小按钮
        try:
            self.showMaximized()  # 先实现窗口最大化
            self._MaximumButton.setText(
                b'\xef\x80\xb2'.decode("utf-8"))  # 更改按钮文本
            self._MaximumButton.setToolTip("恢复")  # 更改按钮提示
            self._MaximumButton.disconnect()  # 断开原本的信号槽连接
            self._MaximumButton.clicked.connect(
                self._changeMaxButton)  # 重新连接信号和槽
        except:
            pass

    def _changeMaxButton(self):
        # 切换到最大化按钮
        try:
            self.showNormal()
            self._MaximumButton.setText(b'\xef\x80\xb1'.decode("utf-8"))
            self._MaximumButton.setToolTip("最大化")
            self._MaximumButton.disconnect()
            self._MaximumButton.clicked.connect(self._changeNormalButton)
        except:
            pass

    def resizeEvent(self, QResizeEvent):
        # 自定义窗口调整大小事件
        self._TitleLabel.setFixedWidth(self.width())  # 将标题标签始终设为窗口宽度
        # 分别移动三个按钮到正确的位置
        try:
            self._CloseButton.move(self.width() - self._CloseButton.width(), 0)
        except:
            pass
        try:
            self._MinimumButton.move(
                self.width() - (self._CloseButton.width() + 1) * 3 + 1, 0)
        except:
            pass
        try:
            self._MaximumButton.move(
                self.width() - (self._CloseButton.width() + 1) * 2 + 1, 0)
        except:
            pass
        # 重新调整边界范围以备实现鼠标拖放缩放窗口大小,采用三个列表生成式生成三个列表
        self._right_rect = [
            QPoint(x, y) for x in range(self.width() - self._padding,
                                        self.width() + 1)
            for y in range(1,
                           self.height() - self._padding)
        ]
        self._bottom_rect = [
            QPoint(x, y) for x in range(1,
                                        self.width() - self._padding)
            for y in range(self.height() - self._padding,
                           self.height() + 1)
        ]
        self._corner_rect = [
            QPoint(x, y) for x in range(self.width() - self._padding,
                                        self.width() + 1)
            for y in range(self.height() - self._padding,
                           self.height() + 1)
        ]

    def mousePressEvent(self, event):
        # 重写鼠标点击的事件
        if (event.button() == Qt.LeftButton) and (event.pos()
                                                  in self._corner_rect):
            # 鼠标左键点击右下角边界区域
            self._corner_drag = True
            event.accept()
        elif (event.button() == Qt.LeftButton) and (event.pos()
                                                    in self._right_rect):
            # 鼠标左键点击右侧边界区域
            self._right_drag = True
            event.accept()
        elif (event.button() == Qt.LeftButton) and (event.pos()
                                                    in self._bottom_rect):
            # 鼠标左键点击下侧边界区域
            self._bottom_drag = True
            event.accept()
        elif (event.button()
              == Qt.LeftButton) and (event.y() < self._TitleLabel.height()):
            # 鼠标左键点击标题栏区域
            self._move_drag = True
            self.move_DragPosition = event.globalPos() - self.pos()
            event.accept()

    def mouseMoveEvent(self, QMouseEvent):
        # 判断鼠标位置切换鼠标手势
        if QMouseEvent.pos() in self._corner_rect:
            self.setCursor(Qt.SizeFDiagCursor)
        elif QMouseEvent.pos() in self._bottom_rect:
            self.setCursor(Qt.SizeVerCursor)
        elif QMouseEvent.pos() in self._right_rect:
            self.setCursor(Qt.SizeHorCursor)
        else:
            self.setCursor(Qt.ArrowCursor)
        # 当鼠标左键点击不放及满足点击区域的要求后,分别实现不同的窗口调整
        # 没有定义左方和上方相关的5个方向,主要是因为实现起来不难,但是效果很差,拖放的时候窗口闪烁,再研究研究是否有更好的实现
        if Qt.LeftButton and self._right_drag:
            # 右侧调整窗口宽度
            self.resize(QMouseEvent.pos().x(), self.height())
            QMouseEvent.accept()
        elif Qt.LeftButton and self._bottom_drag:
            # 下侧调整窗口高度
            self.resize(self.width(), QMouseEvent.pos().y())
            QMouseEvent.accept()
        elif Qt.LeftButton and self._corner_drag:
            # 右下角同时调整高度和宽度
            self.resize(QMouseEvent.pos().x(), QMouseEvent.pos().y())
            QMouseEvent.accept()
        elif Qt.LeftButton and self._move_drag:
            # 标题栏拖放窗口位置
            self.move(QMouseEvent.globalPos() - self.move_DragPosition)
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        # 鼠标释放后,各扳机复位
        self._move_drag = False
        self._corner_drag = False
        self._bottom_drag = False
        self._right_drag = False
示例#55
0
class TRPreviewer(E5MainWindow):
    """
    Class implementing the UI Previewer main window.
    """
    def __init__(self, filenames=[], parent=None, name=None):
        """
        Constructor
        
        @param filenames filenames of form and/or translation files to load
        @param parent parent widget of this window (QWidget)
        @param name name of this window (string)
        """
        self.mainWidget = None
        self.currentFile = QDir.currentPath()

        super(TRPreviewer, self).__init__(parent)
        if not name:
            self.setObjectName("TRPreviewer")
        else:
            self.setObjectName(name)

        self.setStyle(Preferences.getUI("Style"),
                      Preferences.getUI("StyleSheet"))

        self.resize(QSize(800, 600).expandedTo(self.minimumSizeHint()))
        self.statusBar()

        self.setWindowIcon(UI.PixmapCache.getIcon("pymakr.png"))
        self.setWindowTitle(self.tr("Translations Previewer"))

        self.cw = QWidget(self)
        self.cw.setObjectName("qt_central_widget")

        self.TRPreviewerLayout = QVBoxLayout(self.cw)
        self.TRPreviewerLayout.setContentsMargins(6, 6, 6, 6)
        self.TRPreviewerLayout.setSpacing(6)
        self.TRPreviewerLayout.setObjectName("TRPreviewerLayout")

        self.languageLayout = QHBoxLayout()
        self.languageLayout.setContentsMargins(0, 0, 0, 0)
        self.languageLayout.setSpacing(6)
        self.languageLayout.setObjectName("languageLayout")

        self.languageLabel = QLabel(self.tr("Select language file"), self.cw)
        self.languageLabel.setObjectName("languageLabel")
        self.languageLayout.addWidget(self.languageLabel)

        self.languageCombo = QComboBox(self.cw)
        self.languageCombo.setObjectName("languageCombo")
        self.languageCombo.setEditable(False)
        self.languageCombo.setToolTip(self.tr("Select language file"))
        self.languageCombo.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Preferred)
        self.languageLayout.addWidget(self.languageCombo)

        languageSpacer = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                     QSizePolicy.Minimum)
        self.languageLayout.addItem(languageSpacer)
        self.TRPreviewerLayout.addLayout(self.languageLayout)

        self.preview = WidgetArea(self.cw)
        self.preview.setObjectName("preview")
        self.TRPreviewerLayout.addWidget(self.preview)
        self.preview.lastWidgetClosed.connect(self.__updateActions)

        self.setCentralWidget(self.cw)

        self.languageCombo.activated[str].connect(self.setTranslation)

        self.translations = TranslationsDict(self.languageCombo, self)
        self.translations.translationChanged.connect(
            self.preview.rebuildWidgets)

        self.__initActions()
        self.__initMenus()
        self.__initToolbars()

        self.__updateActions()

        # fire up the single application server
        from .TRSingleApplication import TRSingleApplicationServer
        self.SAServer = TRSingleApplicationServer(self)
        self.SAServer.loadForm.connect(self.preview.loadWidget)
        self.SAServer.loadTranslation.connect(self.translations.add)

        # defere loading of a UI file until we are shown
        self.filesToLoad = filenames[:]

    def show(self):
        """
        Public slot to show this dialog.
        
        This overloaded slot loads a UI file to be previewed after
        the main window has been shown. This way, previewing a dialog
        doesn't interfere with showing the main window.
        """
        super(TRPreviewer, self).show()
        if self.filesToLoad:
            filenames, self.filesToLoad = (self.filesToLoad[:], [])
            first = True
            for fn in filenames:
                fi = QFileInfo(fn)
                if fi.suffix().lower() == 'ui':
                    self.preview.loadWidget(fn)
                elif fi.suffix().lower() == 'qm':
                    self.translations.add(fn, first)
                    first = False

            self.__updateActions()

    def closeEvent(self, event):
        """
        Protected event handler for the close event.
        
        @param event close event (QCloseEvent)
        """
        if self.SAServer is not None:
            self.SAServer.shutdown()
            self.SAServer = None
        event.accept()

    def __initActions(self):
        """
        Private method to define the user interface actions.
        """
        self.openUIAct = QAction(UI.PixmapCache.getIcon("openUI.png"),
                                 self.tr('&Open UI Files...'), self)
        self.openUIAct.setStatusTip(self.tr('Open UI files for display'))
        self.openUIAct.setWhatsThis(
            self.tr("""<b>Open UI Files</b>"""
                    """<p>This opens some UI files for display.</p>"""))
        self.openUIAct.triggered.connect(self.__openWidget)

        self.openQMAct = QAction(UI.PixmapCache.getIcon("openQM.png"),
                                 self.tr('Open &Translation Files...'), self)
        self.openQMAct.setStatusTip(
            self.tr('Open Translation files for display'))
        self.openQMAct.setWhatsThis(
            self.tr(
                """<b>Open Translation Files</b>"""
                """<p>This opens some translation files for display.</p>"""))
        self.openQMAct.triggered.connect(self.__openTranslation)

        self.reloadAct = QAction(UI.PixmapCache.getIcon("reload.png"),
                                 self.tr('&Reload Translations'), self)
        self.reloadAct.setStatusTip(self.tr('Reload the loaded translations'))
        self.reloadAct.setWhatsThis(
            self.tr("""<b>Reload Translations</b>"""
                    """<p>This reloads the translations for the loaded"""
                    """ languages.</p>"""))
        self.reloadAct.triggered.connect(self.translations.reload)

        self.exitAct = QAction(UI.PixmapCache.getIcon("exit.png"),
                               self.tr('&Quit'), self)
        self.exitAct.setShortcut(QKeySequence(self.tr("Ctrl+Q", "File|Quit")))
        self.exitAct.setStatusTip(self.tr('Quit the application'))
        self.exitAct.setWhatsThis(
            self.tr("""<b>Quit</b>"""
                    """<p>Quit the application.</p>"""))
        self.exitAct.triggered.connect(qApp.closeAllWindows)

        self.whatsThisAct = QAction(UI.PixmapCache.getIcon("whatsThis.png"),
                                    self.tr('&What\'s This?'), self)
        self.whatsThisAct.setShortcut(QKeySequence(self.tr("Shift+F1")))
        self.whatsThisAct.setStatusTip(self.tr('Context sensitive help'))
        self.whatsThisAct.setWhatsThis(
            self.
            tr("""<b>Display context sensitive help</b>"""
               """<p>In What's This? mode, the mouse cursor shows an arrow"""
               """ with a question mark, and you can click on the interface"""
               """ elements to get a short description of what they do and"""
               """ how to use them. In dialogs, this feature can be accessed"""
               """ using the context help button in the titlebar.</p>"""))
        self.whatsThisAct.triggered.connect(self.__whatsThis)

        self.aboutAct = QAction(self.tr('&About'), self)
        self.aboutAct.setStatusTip(
            self.tr('Display information about this software'))
        self.aboutAct.setWhatsThis(
            self.tr(
                """<b>About</b>"""
                """<p>Display some information about this software.</p>"""))
        self.aboutAct.triggered.connect(self.__about)

        self.aboutQtAct = QAction(self.tr('About &Qt'), self)
        self.aboutQtAct.setStatusTip(
            self.tr('Display information about the Qt toolkit'))
        self.aboutQtAct.setWhatsThis(
            self.tr(
                """<b>About Qt</b>"""
                """<p>Display some information about the Qt toolkit.</p>"""))
        self.aboutQtAct.triggered.connect(self.__aboutQt)

        self.tileAct = QAction(self.tr('&Tile'), self)
        self.tileAct.setStatusTip(self.tr('Tile the windows'))
        self.tileAct.setWhatsThis(
            self.tr("""<b>Tile the windows</b>"""
                    """<p>Rearrange and resize the windows so that they are"""
                    """ tiled.</p>"""))
        self.tileAct.triggered.connect(self.preview.tileSubWindows)

        self.cascadeAct = QAction(self.tr('&Cascade'), self)
        self.cascadeAct.setStatusTip(self.tr('Cascade the windows'))
        self.cascadeAct.setWhatsThis(
            self.tr("""<b>Cascade the windows</b>"""
                    """<p>Rearrange and resize the windows so that they are"""
                    """ cascaded.</p>"""))
        self.cascadeAct.triggered.connect(self.preview.cascadeSubWindows)

        self.closeAct = QAction(UI.PixmapCache.getIcon("close.png"),
                                self.tr('&Close'), self)
        self.closeAct.setShortcut(QKeySequence(self.tr("Ctrl+W",
                                                       "File|Close")))
        self.closeAct.setStatusTip(self.tr('Close the current window'))
        self.closeAct.setWhatsThis(
            self.tr("""<b>Close Window</b>"""
                    """<p>Close the current window.</p>"""))
        self.closeAct.triggered.connect(self.preview.closeWidget)

        self.closeAllAct = QAction(self.tr('Clos&e All'), self)
        self.closeAllAct.setStatusTip(self.tr('Close all windows'))
        self.closeAllAct.setWhatsThis(
            self.tr("""<b>Close All Windows</b>"""
                    """<p>Close all windows.</p>"""))
        self.closeAllAct.triggered.connect(self.preview.closeAllWidgets)

    def __initMenus(self):
        """
        Private method to create the menus.
        """
        mb = self.menuBar()

        menu = mb.addMenu(self.tr('&File'))
        menu.setTearOffEnabled(True)
        menu.addAction(self.openUIAct)
        menu.addAction(self.openQMAct)
        menu.addAction(self.reloadAct)
        menu.addSeparator()
        menu.addAction(self.closeAct)
        menu.addAction(self.closeAllAct)
        menu.addSeparator()
        menu.addAction(self.exitAct)

        self.windowMenu = mb.addMenu(self.tr('&Window'))
        self.windowMenu.setTearOffEnabled(True)
        self.windowMenu.aboutToShow.connect(self.__showWindowMenu)
        self.windowMenu.triggered.connect(self.preview.toggleSelectedWidget)

        mb.addSeparator()

        menu = mb.addMenu(self.tr('&Help'))
        menu.setTearOffEnabled(True)
        menu.addAction(self.aboutAct)
        menu.addAction(self.aboutQtAct)
        menu.addSeparator()
        menu.addAction(self.whatsThisAct)

    def __initToolbars(self):
        """
        Private method to create the toolbars.
        """
        filetb = self.addToolBar(self.tr("File"))
        filetb.setIconSize(UI.Config.ToolBarIconSize)
        filetb.addAction(self.openUIAct)
        filetb.addAction(self.openQMAct)
        filetb.addAction(self.reloadAct)
        filetb.addSeparator()
        filetb.addAction(self.closeAct)
        filetb.addSeparator()
        filetb.addAction(self.exitAct)

        helptb = self.addToolBar(self.tr("Help"))
        helptb.setIconSize(UI.Config.ToolBarIconSize)
        helptb.addAction(self.whatsThisAct)

    def __whatsThis(self):
        """
        Private slot called in to enter Whats This mode.
        """
        QWhatsThis.enterWhatsThisMode()

    def __updateActions(self):
        """
        Private slot to update the actions state.
        """
        if self.preview.hasWidgets():
            self.closeAct.setEnabled(True)
            self.closeAllAct.setEnabled(True)
            self.tileAct.setEnabled(True)
            self.cascadeAct.setEnabled(True)
        else:
            self.closeAct.setEnabled(False)
            self.closeAllAct.setEnabled(False)
            self.tileAct.setEnabled(False)
            self.cascadeAct.setEnabled(False)

        if self.translations.hasTranslations():
            self.reloadAct.setEnabled(True)
        else:
            self.reloadAct.setEnabled(False)

    def __about(self):
        """
        Private slot to show the about information.
        """
        E5MessageBox.about(
            self, self.tr("TR Previewer"),
            self.tr(
                """<h3> About TR Previewer </h3>"""
                """<p>The TR Previewer loads and displays Qt User-Interface"""
                """ files and translation files and shows dialogs for a"""
                """ selected language.</p>"""))

    def __aboutQt(self):
        """
        Private slot to show info about Qt.
        """
        E5MessageBox.aboutQt(self, self.tr("TR Previewer"))

    def __openWidget(self):
        """
        Private slot to handle the Open Dialog action.
        """
        fileNameList = E5FileDialog.getOpenFileNames(
            None, self.tr("Select UI files"), "",
            self.tr("Qt User-Interface Files (*.ui)"))

        for fileName in fileNameList:
            self.preview.loadWidget(fileName)

        self.__updateActions()

    def __openTranslation(self):
        """
        Private slot to handle the Open Translation action.
        """
        fileNameList = E5FileDialog.getOpenFileNames(
            None, self.tr("Select translation files"), "",
            self.tr("Qt Translation Files (*.qm)"))

        first = True
        for fileName in fileNameList:
            self.translations.add(fileName, first)
            first = False

        self.__updateActions()

    def setTranslation(self, name):
        """
        Public slot to activate a translation.
        
        @param name name (language) of the translation (string)
        """
        self.translations.set(name)

    def __showWindowMenu(self):
        """
        Private slot to handle the aboutToShow signal of the window menu.
        """
        self.windowMenu.clear()
        self.windowMenu.addAction(self.tileAct)
        self.windowMenu.addAction(self.cascadeAct)
        self.windowMenu.addSeparator()

        self.preview.showWindowMenu(self.windowMenu)

    def reloadTranslations(self):
        """
        Public slot to reload all translations.
        """
        self.translations.reload()
示例#56
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('ConvertAll')
        modPath = os.path.abspath(sys.path[0])
        if modPath.endswith('.zip'):  # for py2exe
            modPath = os.path.dirname(modPath)
        iconPathList = [
            iconPath,
            os.path.join(modPath, 'icons/'),
            os.path.join(modPath, '../icons')
        ]
        self.icons = icondict.IconDict()
        self.icons.addIconPath([path for path in iconPathList if path])
        try:
            QApplication.setWindowIcon(self.icons['convertall_med'])
        except KeyError:
            pass
        self.helpView = None
        self.option = Option('convertall', 20)
        self.option.loadAll(optiondefaults.defaultList)
        self.recentUnits = recentunits.RecentUnits(self.option)
        try:
            num = ConvertDlg.unitData.readData()
        except unitdata.UnitDataError as text:
            QMessageBox.warning(self, 'ConvertAll',
                                _('Error in unit data - {0}').format(text))
            sys.exit(1)
        try:
            print(_('{0} units loaded').format(num))
        except UnicodeError:
            print('{0} units loaded'.format(num))
        self.fromGroup = UnitGroup(ConvertDlg.unitData, self.option)
        self.toGroup = UnitGroup(ConvertDlg.unitData, self.option)
        self.origPal = QApplication.palette()
        self.updateColors()
        self.unitButtons = []
        self.textButtons = []

        topLayout = QHBoxLayout(self)  # divide main, buttons
        mainLayout = QVBoxLayout()
        mainLayout.setSpacing(8)
        topLayout.addLayout(mainLayout)
        unitLayout = QGridLayout()  # unit selection
        unitLayout.setVerticalSpacing(3)
        unitLayout.setHorizontalSpacing(20)
        mainLayout.addLayout(unitLayout)

        fromLabel = QLabel(_('From Unit'))
        unitLayout.addWidget(fromLabel, 0, 0)
        self.fromUnitEdit = unitedit.UnitEdit(self.fromGroup)
        unitLayout.addWidget(self.fromUnitEdit, 1, 0)
        self.fromUnitEdit.setFocus()

        toLabel = QLabel(_('To Unit'))
        unitLayout.addWidget(toLabel, 0, 1)
        self.toUnitEdit = unitedit.UnitEdit(self.toGroup)
        unitLayout.addWidget(self.toUnitEdit, 1, 1)
        self.fromUnitEdit.gotFocus.connect(self.toUnitEdit.setInactive)
        self.toUnitEdit.gotFocus.connect(self.fromUnitEdit.setInactive)

        vertButtonLayout = QVBoxLayout()
        vertButtonLayout.setSpacing(2)
        mainLayout.addLayout(vertButtonLayout)

        self.unitListView = unitlistview.UnitListView(ConvertDlg.unitData)
        mainLayout.addWidget(self.unitListView)
        self.fromUnitEdit.currentChanged.connect(
            self.unitListView.updateFiltering)
        self.toUnitEdit.currentChanged.connect(
            self.unitListView.updateFiltering)
        self.fromUnitEdit.keyPressed.connect(self.unitListView.handleKeyPress)
        self.toUnitEdit.keyPressed.connect(self.unitListView.handleKeyPress)
        self.unitListView.unitChanged.connect(self.fromUnitEdit.unitUpdate)
        self.unitListView.unitChanged.connect(self.toUnitEdit.unitUpdate)
        self.unitListView.haveCurrentUnit.connect(self.enableButtons)
        self.unitListView.setFocusPolicy(Qt.NoFocus)

        textButtonLayout = QHBoxLayout()
        textButtonLayout.setSpacing(6)
        vertButtonLayout.addLayout(textButtonLayout)
        textButtonLayout.addStretch(1)
        self.textButtons.append(QPushButton('{0} (^2)'.format(_('Square'))))
        self.textButtons.append(QPushButton('{0} (^3)'.format(_('Cube'))))
        self.textButtons.append(QPushButton('{0} (*)'.format(_('Multiply'))))
        self.textButtons.append(QPushButton('{0} (/)'.format(_('Divide'))))
        for button in self.textButtons:
            button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            button.setFocusPolicy(Qt.NoFocus)
            textButtonLayout.addWidget(button)
            button.clicked.connect(self.unitListView.addUnitText)
        textButtonLayout.addStretch(1)

        unitButtonLayout = QHBoxLayout()
        unitButtonLayout.setSpacing(6)
        vertButtonLayout.addLayout(unitButtonLayout)
        unitButtonLayout.addStretch(1)
        self.clearButton = QPushButton(_('Clear Unit'))
        self.clearButton.clicked.connect(self.unitListView.clearUnitText)
        self.recentButton = QPushButton(_('Recent Unit'))
        self.recentButton.clicked.connect(self.recentMenu)
        self.filterButton = QPushButton(_('Filter List'))
        self.filterButton.clicked.connect(self.filterMenu)
        self.unitButtons = [
            self.clearButton, self.recentButton, self.filterButton
        ]
        for button in self.unitButtons:
            button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            button.setFocusPolicy(Qt.NoFocus)
            unitButtonLayout.addWidget(button)
        unitButtonLayout.addStretch(1)
        self.showHideButtons()

        numberLayout = QGridLayout()
        numberLayout.setVerticalSpacing(3)
        mainLayout.addLayout(numberLayout)
        statusLabel = QLabel(_('Set units'))
        statusLabel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        mainLayout.addWidget(statusLabel)

        fromNumLabel = QLabel(_('No Unit Set'))
        numberLayout.addWidget(fromNumLabel, 0, 0)
        self.fromNumEdit = numedit.NumEdit(self.fromGroup, self.toGroup,
                                           fromNumLabel, statusLabel,
                                           self.recentUnits, True)
        numberLayout.addWidget(self.fromNumEdit, 1, 0)
        self.fromUnitEdit.unitChanged.connect(self.fromNumEdit.unitUpdate)
        self.fromNumEdit.gotFocus.connect(self.fromUnitEdit.setInactive)
        self.fromNumEdit.gotFocus.connect(self.toUnitEdit.setInactive)
        self.fromNumEdit.gotFocus.connect(self.unitListView.resetFiltering)
        self.fromNumEdit.setEnabled(False)
        equalsLabel = QLabel(' = ')
        equalsLabel.setFont(QFont(self.font().family(), 20))
        numberLayout.addWidget(equalsLabel, 0, 1, 2, 1)

        toNumLabel = QLabel(_('No Unit Set'))
        numberLayout.addWidget(toNumLabel, 0, 3)
        self.toNumEdit = numedit.NumEdit(self.toGroup, self.fromGroup,
                                         toNumLabel, statusLabel,
                                         self.recentUnits, False)
        numberLayout.addWidget(self.toNumEdit, 1, 3)
        self.toUnitEdit.unitChanged.connect(self.toNumEdit.unitUpdate)
        self.toNumEdit.gotFocus.connect(self.fromUnitEdit.setInactive)
        self.toNumEdit.gotFocus.connect(self.toUnitEdit.setInactive)
        self.toNumEdit.gotFocus.connect(self.unitListView.resetFiltering)
        self.toNumEdit.setEnabled(False)
        self.fromNumEdit.convertNum.connect(self.toNumEdit.setNum)
        self.toNumEdit.convertNum.connect(self.fromNumEdit.setNum)
        self.fromNumEdit.convertRqd.connect(self.toNumEdit.convert)
        self.toNumEdit.convertRqd.connect(self.fromNumEdit.convert)

        buttonLayout = QVBoxLayout()  # major buttons
        topLayout.addLayout(buttonLayout)
        closeButton = QPushButton(_('&Close'))
        buttonLayout.addWidget(closeButton)
        closeButton.setFocusPolicy(Qt.NoFocus)
        closeButton.clicked.connect(self.close)
        optionsButton = QPushButton(_('&Options...'))
        buttonLayout.addWidget(optionsButton)
        optionsButton.setFocusPolicy(Qt.NoFocus)
        optionsButton.clicked.connect(self.changeOptions)
        helpButton = QPushButton(_('&Help...'))
        buttonLayout.addWidget(helpButton)
        helpButton.setFocusPolicy(Qt.NoFocus)
        helpButton.clicked.connect(self.help)
        aboutButton = QPushButton(_('&About...'))
        buttonLayout.addWidget(aboutButton)
        aboutButton.setFocusPolicy(Qt.NoFocus)
        aboutButton.clicked.connect(self.about)
        buttonLayout.addStretch()

        if self.option.boolData('RemenberDlgPos'):
            xSize = self.option.intData('MainDlgXSize', 0, 10000)
            ySize = self.option.intData('MainDlgYSize', 0, 10000)
            if xSize and ySize:
                self.resize(xSize, ySize)
            self.move(self.option.intData('MainDlgXPos', 0, 10000),
                      self.option.intData('MainDlgYPos', 0, 10000))
        if self.option.boolData('LoadLastUnit') and len(self.recentUnits) > 1:
            self.fromGroup.update(self.recentUnits[0])
            self.fromUnitEdit.unitUpdate()
            self.toGroup.update(self.recentUnits[1])
            self.toUnitEdit.unitUpdate()
            self.unitListView.updateFiltering()
            self.fromNumEdit.setFocus()
            self.fromNumEdit.selectAll()
        if self.option.boolData('ShowStartupTip'):
            self.show()
            tipDialog = TipDialog(self.option, self)
            tipDialog.exec_()
示例#57
0
    def __init__(self, classifiers, parent=None):
        super(QtClassifierWidget, self).__init__(parent)

        self.classifiers = classifiers

        self.setStyleSheet("background-color: rgba(60,60,65,100); color: white")

        self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
        self.setMinimumWidth(300)
        self.setMinimumHeight(100)

        layoutH0 = QHBoxLayout()

        self.lblClassifier = QLabel("Classifier: ")

        self.comboClassifier = QComboBox()
        self.comboClassifier.setMinimumWidth(300)
        for classifier in classifiers:
            self.comboClassifier.addItem(classifier['Classifier Name'])

        self.comboClassifier.currentIndexChanged.connect(self.classifierChanged)

        layoutH0.setAlignment(Qt.AlignLeft)
        layoutH0.addStretch()
        layoutH0.addWidget(self.lblClassifier)
        layoutH0.addWidget(self.comboClassifier)
        layoutH0.addStretch()

        self.lblFilename = QLabel("Filename: ")
        self.lblNClasses = QLabel("N. of classes: ")
        self.lblClasses = QLabel("Classes recognized: ")
        self.lblScale = QLabel("Training scale (px-to-mm): ")
        self.lblAvgColor = QLabel("Training avg. color: ")

        layoutH1a = QVBoxLayout()
        layoutH1a.setAlignment(Qt.AlignRight)
        layoutH1a.addWidget(self.lblFilename)
        layoutH1a.addWidget(self.lblNClasses)
        layoutH1a.addWidget(self.lblClasses)
        layoutH1a.addWidget(self.lblScale)
        layoutH1a.addWidget(self.lblAvgColor)

        LINEWIDTH = 300
        self.editFilename = QLineEdit(classifiers[0]["Weights"])
        self.editFilename.setStyleSheet("background-color: rgb(40,40,40); border: 1px solid rgb(90,90,90)")
        self.editFilename.setReadOnly(True)
        self.editFilename.setFixedWidth(LINEWIDTH)
        self.editNClasses = QLineEdit(str(classifiers[0]["Num. Classes"]))
        self.editNClasses.setStyleSheet("background-color: rgb(40,40,40); border: 1px solid rgb(90,90,90)")
        self.editNClasses.setReadOnly(True)
        self.editNClasses.setFixedWidth(LINEWIDTH)
        self.editClasses = QLineEdit(self.classes2str(classifiers[0]["Classes"]))
        self.editClasses.setStyleSheet("background-color: rgb(40,40,40); border: 1px solid rgb(90,90,90)")
        self.editClasses.setFixedWidth(LINEWIDTH)
        self.editClasses.setReadOnly(True)
        self.editScale = QLineEdit(str(classifiers[0]["Scale"]))
        self.editScale.setStyleSheet("background-color: rgb(40,40,40); border: 1px solid rgb(90,90,90)")
        self.editScale.setFixedWidth(LINEWIDTH)
        self.editScale.setReadOnly(True)
        self.editAvgColor = QLineEdit(self.avgcolor2str(classifiers[0]["Average Norm."]))
        self.editAvgColor.setStyleSheet("background-color: rgb(40,40,40); border: 1px solid rgb(90,90,90)")
        self.editAvgColor.setFixedWidth(LINEWIDTH)
        self.editAvgColor.setReadOnly(True)

        layoutH1b = QVBoxLayout()
        layoutH1b.setAlignment(Qt.AlignLeft)
        layoutH1b.addWidget(self.editFilename)
        layoutH1b.addWidget(self.editNClasses)
        layoutH1b.addWidget(self.editClasses)
        layoutH1b.addWidget(self.editScale)
        layoutH1b.addWidget(self.editAvgColor)

        layoutH1 = QHBoxLayout()
        layoutH1.addLayout(layoutH1a)
        layoutH1.addLayout(layoutH1b)

        self.btnCancel = QPushButton("Cancel")
        self.btnCancel.clicked.connect(self.close)
        self.btnApply = QPushButton("Apply")

        layoutH2 = QHBoxLayout()
        layoutH2.setAlignment(Qt.AlignRight)
        layoutH2.addStretch()
        layoutH2.addWidget(self.btnCancel)
        layoutH2.addWidget(self.btnApply)

        layoutV = QVBoxLayout()
        layoutV.addLayout(layoutH0)
        layoutV.addLayout(layoutH1)
        layoutV.addLayout(layoutH2)
        layoutV.setSpacing(3)
        self.setLayout(layoutV)

        self.setWindowTitle("SELECT CLASSIFIER")
        self.setWindowFlags(Qt.Window | Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint | Qt.WindowTitleHint)
示例#58
0
文件: main.py 项目: poiedk/Pythonic
class MainWindow(QWidget):

    log_level = logging.INFO
    formatter = logging.Formatter(
        fmt='%(asctime)s - %(levelname)s - %(message)s', datefmt='%H:%M:%S')

    number_of_grids = 5

    def __init__(self, app):
        super(MainWindow, self).__init__()
        self.app = app
        self.threadpool = QThreadPool()
        self.initUI()
        self.setAttribute(Qt.WA_DeleteOnClose)
        mp.set_start_method('spawn')

    def initUI(self):

        #start geometrie
        self.width = 1200
        self.height = 800
        self.desktop = QApplication.desktop()
        self.desktop_size = QRect()
        self.desktop_size = self.desktop.screenGeometry()

        self.logger = logging.getLogger()
        self.logger.setLevel(self.log_level)
        self.log_date = datetime.datetime.now()

        self.mod_path = os.path.dirname(Pythonic.__file__)

        log_date_str = self.log_date.strftime('%Y_%m_%d')
        month = self.log_date.strftime('%b')
        year = self.log_date.strftime('%Y')
        home_dict = str(Path.home())
        file_path = '{}/Pythonic_{}/{}/log_{}.txt'.format(
            home_dict, year, month, log_date_str)
        self.ensure_file_path(file_path)

        file_handler = logging.FileHandler(file_path)
        file_handler.setLevel(self.log_level)
        file_handler.setFormatter(self.formatter)

        self.logger.addHandler(file_handler)

        # init language !
        self.translator = QTranslator(self.app)
        #self.translator.load('translations/spanish_es')
        self.translator.load(join(self.mod_path, 'translations/english_en.qm'))
        self.app.installTranslator(self.translator)
        #QC.installTranslator(self.translator)

        logging.debug('Translation: {}'.format(QC.translate('', 'Save')))

        # setup the default language here
        #self.changeTranslator('german_de.qm')

        self.x_position = self.desktop_size.width() / 2 - self.width / 2
        self.y_position = self.desktop_size.height() / 2 - self.height / 2

        self.setAcceptDrops(True)

        self.layout_v = QVBoxLayout()

        # main_layout contains the workingarea and the toolbox
        self.main_layout = QVBoxLayout()
        self.main_layout.setSpacing(0)
        self.main_layout.setContentsMargins(0, 0, 0, 0)

        self.bottom_border_layout = QHBoxLayout()
        self.bottom_border_layout.setSpacing(0)
        self.setContentsMargins(0, 0, 0, 0)

        # create class objects
        #self.exceptwindow = ExceptWindow(self)

        self.wrk_area_arr = []
        self.wrk_tabs_arr = []
        self.grd_ops_arr = []
        self.working_tabs = QTabWidget()
        self.working_tabs.setMinimumSize(300, 300)
        for i in range(self.number_of_grids):

            self.wrk_area_arr.append(WorkingArea())
            self.wrk_tabs_arr.append(QScrollArea())
            self.wrk_tabs_arr[i].setWidget(self.wrk_area_arr[i])
            self.wrk_tabs_arr[i].setWidgetResizable(True)

            #self.working_tabs.addTab(self.wrk_area_arr[i], QC.translate('', 'Grid {}'.format(i)))
            self.working_tabs.addTab(self.wrk_tabs_arr[i],
                                     QC.translate('', 'Grid {}'.format(i + 1)))

            self.grd_ops_arr.append(GridOperator(self.wrk_area_arr[i].grid, i))

        # init reference for the current grid which is in focus
        self.focus_grid = self.wrk_area_arr[0]
        self.wrk_tab_index = 0

        #self.working_area = WorkingArea()
        self.storagebar = StorageBar(self)
        self.menubar = MenuBar()
        self.toolbox_tab = QTabWidget()
        self.toolbox_tab.setSizePolicy(QSizePolicy.Minimum,
                                       QSizePolicy.Preferred)
        self.topMenuBar = topMenuBar()
        self.settings = Settings()
        self.infoWindow = InfoWindow()

        #self.gridoperator = GridOperator(self)

        self.toolbox_basics = BasicTools(self)
        self.toolbox_binance = BinanceTools(self)
        self.toolbox_connectivity = ConnectivityTools(self)
        self.toolbox_ml = MLTools(self)

        # add Tabs to the toolbox
        self.toolbox_tab.addTab(self.toolbox_basics, QC.translate('', 'Basic'))
        self.toolbox_tab.addTab(self.toolbox_binance,
                                QC.translate('', 'Binance'))
        self.toolbox_tab.addTab(self.toolbox_connectivity,
                                QC.translate('', 'Connectivity'))
        self.toolbox_tab.addTab(self.toolbox_ml,
                                QC.translate('', 'Machine Learning'))

        # signals and slots
        self.menubar.set_info_text.connect(self.setInfoText)
        self.menubar.start_debug.connect(self.startDebug)
        self.menubar.start_exec.connect(self.startExec)
        #self.menubar.clear_grid.connect(self.working_area.setupDefault)
        #self.menubar.stop_exec.connect(self.gridoperator.stop_execution)
        #self.menubar.kill_proc.connect(self.gridoperator.kill_proc)
        #self.menubar.kill_proc.connect(self.working_area.allStop)
        #self.gridoperator.update_logger.connect(self.update_logfile)
        self.topMenuBar.switch_language.connect(self.changeTranslator)
        self.topMenuBar.close_signal.connect(self.closeEvent)
        self.topMenuBar.open_action.triggered.connect(
            self.menubar.openFileNameDialog)
        self.topMenuBar.save_action.triggered.connect(self.menubar.simpleSave)
        self.topMenuBar.save_as_action.triggered.connect(
            self.menubar.saveFileDialog)
        self.topMenuBar.new_action.triggered.connect(self.menubar.saveQuestion)
        self.topMenuBar.settings_action.triggered.connect(self.settings.show)
        self.topMenuBar.info_action.triggered.connect(self.showInfo)
        self.working_tabs.currentChanged.connect(self.wrkIndexChanged)
        #self.toolbox_binance.reg_tool.connect(self.working_area.regType)
        #self.toolbox_connectivity.reg_tool.connect(self.working_area.regType)
        #self.toolbox_basics.reg_tool.connect(self.working_area.regType)
        #self.storagebar.forward_config.connect(self.working_area.receiveConfig)
        #self.working_area.finish_dropbox.connect(self.storagebar.finishDropBox)
        self.menubar.stop_exec.connect(self.stopExecution)
        self.menubar.kill_proc.connect(self.killProcesses)
        self.menubar.load_file.connect(self.loadGrid)
        self.menubar.save_file.connect(self.saveGrid)
        self.menubar.clear_grid.connect(self.setupDefault)

        for i in range(self.number_of_grids):

            self.toolbox_binance.reg_tool.connect(self.wrk_area_arr[i].regType)
            self.toolbox_connectivity.reg_tool.connect(
                self.wrk_area_arr[i].regType)
            self.toolbox_ml.reg_tool.connect(self.wrk_area_arr[i].regType)
            self.toolbox_basics.reg_tool.connect(self.wrk_area_arr[i].regType)
            # hier auch noch anpassen
            self.storagebar.forward_config.connect(
                self.wrk_area_arr[i].receiveConfig)
            self.wrk_area_arr[i].finish_dropbox.connect(
                self.storagebar.finishDropBox)

            self.grd_ops_arr[i].update_logger.connect(self.update_logfile)
            self.grd_ops_arr[i].switch_grid.connect(self.receiveTarget)
            self.wrk_area_arr[i].query_grid_config_wrk.connect(
                self.queryGridConfiguration)

        # register tools
        self.toolbox_binance.register_tools()
        self.toolbox_basics.register_tools()
        self.toolbox_connectivity.register_tools()
        self.toolbox_ml.register_tools()

        self.scrollArea = QScrollArea()
        #self.scrollArea.setWidget(self.working_area)
        self.scrollArea.setWidget(self.working_tabs)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setMinimumSize(300, 300)

        self.scroll_dropBox = QScrollArea()
        self.scroll_dropBox.setWidget(self.storagebar)
        self.scroll_dropBox.setWidgetResizable(True)
        self.scroll_dropBox.setMaximumWidth(270)

        self.bottom_area = QWidget()
        self.bottom_area_layout = QHBoxLayout(self.bottom_area)
        self.bottom_area_layout.addWidget(self.scrollArea)
        self.bottom_area_layout.addWidget(self.scroll_dropBox)

        self.layout_v.addWidget(self.topMenuBar)
        self.layout_v.addWidget(self.menubar)
        self.layout_v.addWidget(self.toolbox_tab)
        self.layout_v.addWidget(self.bottom_area)

        self.main_widget = QWidget()
        self.main_widget.setLayout(self.layout_v)

        # add main widget to main layout
        self.main_layout.addWidget(self.main_widget, 0)
        self.main_layout.setSpacing(0)
        # resize button
        self.sizeGrip = QSizeGrip(self.main_widget)

        # bottom info text
        self.infoText = QLabel()
        self.infoText.setText('')

        # define the bottom border line
        self.bottom_border_layout.addWidget(self.infoText)
        self.bottom_border_layout.setSpacing(0)
        # left, top, right, bottom
        self.bottom_border_layout.setContentsMargins(5, 0, 5, 5)
        self.bottom_border_layout.addWidget(self.sizeGrip, 0, Qt.AlignRight)

        self.bottom_border = QWidget()
        self.bottom_border.setLayout(self.bottom_border_layout)
        self.main_layout.addWidget(self.bottom_border)

        self.setLayout(self.main_layout)
        self.setGeometry(self.x_position, self.y_position, self.width,
                         self.height)

    def receiveTarget(self, data):

        prg_return, fastpath = data
        grid, *pos = prg_return.target_0
        logging.debug(
            'MainWorker::receiveTarget() called from pos: {} goto grid: {}'.
            format(pos, grid))
        logging.debug(
            'MainWindow::receiveTarget() called fp {}'.format(fastpath))
        # go to goNext() in the target grid
        # set fastpath variable
        self.grd_ops_arr[grid].stop_flag = False
        self.grd_ops_arr[grid].fastpath = fastpath
        # remove grid from target_0
        prg_return.target_0 = pos
        if fastpath:
            self.grd_ops_arr[grid].delay = 0
        else:
            self.grd_ops_arr[grid].delay = self.settings.delay / 1000

        self.grd_ops_arr[grid].goNext(prg_return)

    def queryGridConfiguration(self):

        logging.debug('MainWindow::queryGridConfiguration() called')
        result = []
        for wrk_area in self.wrk_area_arr:
            result.append(wrk_area.returnCurrentElements())
        self.focus_grid.receiveGridConfiguration(result)

    def wrkIndexChanged(self, index):

        logging.debug(
            'MainWindow::wrkIndexChanged() called with index {}'.format(index))
        self.wrk_tab_index = index
        self.focus_grid = self.wrk_area_arr[index]

    def loadGrid(self, filename):

        logging.debug('MainWindow::loadGrid() called')
        grid_data_list = []
        try:
            with ZipFile(filename, 'r') as archive:
                for zipped_grid in archive.namelist():
                    pickled_grid = archive.read(zipped_grid)
                    element_list = pickle.loads(pickled_grid)
                    # first char repesents the grid number
                    self.wrk_area_arr[int(zipped_grid[0])].loadGrid(
                        pickle.loads(pickled_grid))
            archive.close()

        except Exception as e:
            err_msg = QMessageBox()
            err_msg.setIcon(QMessageBox.Critical)
            err_msg.setWindowTitle(QC.translate('', 'File Error'))
            #err_msg.setText(QC.translate('', 'File can\'t be read'))
            err_msg.setText('{}'.format(e))
            err_msg.setAttribute(Qt.WA_DeleteOnClose)
            err_msg.exec()
            raise

    def saveGrid(self, filename):

        logging.debug('MainWindow::saveGrid() called')

        with ZipFile(filename, 'w') as save_file:

            for i in range(self.number_of_grids):
                tmp_file = (self.wrk_area_arr[i].saveGrid())

                save_file.writestr('{}_grid'.format(str(i)), tmp_file)

        save_file.close()

    def setupDefault(self):

        logging.debug('MainWindow::setupDefault() called')
        self.wrk_area_arr[self.wrk_tab_index].setupDefault()

    def stopExecution(self):

        logging.debug('MainWindow::stopExecution() called')
        self.grd_ops_arr[self.wrk_tab_index].stop_execution()

    def killProcesses(self):

        logging.debug('MainWindow::killProcesses() called')
        self.grd_ops_arr[self.wrk_tab_index].kill_proc()
        self.wrk_area_arr[self.wrk_tab_index].allStop()

    def changeTranslator(self, fileName):

        #QC.removeTranslator(self.translator)
        self.app.removeTranslator(self.translator)
        logging.debug(
            'changeTranslator() called with file: {}'.format(fileName))
        self.translator.load(join(self.mod_path, 'translations/') + fileName)
        #QC.installTranslator(self.translator)
        self.app.installTranslator(self.translator)
        logging.debug('Translation: {}'.format(QC.translate('', 'Save')))
        """
        defaultLocale =QLocale.system().name()
        """
        #defaultLocale.truncate(defaultLocale.lastIndexOf(''''))
        #logging.debug('Locale: {}'.format())

    def setInfoText(self, text):

        #self.infoText.setText(QC.translate('', text))
        self.infoText.setText(text)

    def startDebug(self):
        logging.debug('MainWindow::startDebug() called')
        target = (0, 0)
        self.grd_ops_arr[self.wrk_tab_index].stop_flag = False
        self.grd_ops_arr[self.wrk_tab_index].fastpath = False
        self.grd_ops_arr[self.wrk_tab_index].delay = self.settings.delay / 1000
        self.grd_ops_arr[self.wrk_tab_index].startExec(target)

    def startExec(self):
        logging.debug('MainWindow::startExec() called')
        target = (0, 0)
        self.grd_ops_arr[self.wrk_tab_index].stop_flag = False
        self.grd_ops_arr[self.wrk_tab_index].delay = 0
        self.grd_ops_arr[self.wrk_tab_index].fastpath = True
        self.grd_ops_arr[self.wrk_tab_index].startExec(target)

    def changeEvent(self, event):
        if event.type() == QEvent.LanguageChange:
            logging.debug('changeEvent() called MainWindow')
            self.setWindowTitle(QC.translate('', 'Pythonic - 0.19'))

    def showInfo(self, event):

        logging.debug('showInfo called')
        self.infoWindow.show()

    def update_logfile(self):

        now = datetime.datetime.now().date()
        if (now != self.log_date.date()):
            self.logger.removeHandler(self.logger.handlers[0])
            log_date_str = now.strftime('%Y_%m_%d')
            month = now.strftime('%b')
            year = now.strftime('%Y')
            home_dict = str(Path.home())
            file_path = '{}/Pythonic_{}/{}/log_{}.txt'.format(
                home_dict, year, month, log_date_str)
            self.ensure_file_path(file_path)
            file_handler = logging.FileHandler(file_path)
            file_handler.setLevel(self.log_level)
            file_handler.setFormatter(self.formatter)
            self.logger.addHandler(file_handler)
            self.log_date = datetime.datetime.now()

    def ensure_file_path(self, file_path):

        directory = os.path.dirname(file_path)

        if not os.path.exists(directory):
            os.makedirs(directory)

    def closeEvent(self, event):
        logging.debug('closeEvent() called')
        messageBox = QMessageBox()
        messageBox.setAttribute(Qt.WA_DeleteOnClose)
        messageBox.setIcon(QMessageBox.Warning)
        messageBox.setWindowTitle(QC.translate('', 'Close?'))
        messageBox.setText(
            QC.translate('',
                         'Warning: Execution of all tasks will be stopped!'))
        messageBox.setStandardButtons(QMessageBox.No | QMessageBox.Yes)
        messageBox.setDefaultButton(QMessageBox.No)
        ret = messageBox.exec()

        if ret == QMessageBox.No:
            logging.debug('closeEvent() No clicked')
            event.ignore()
        else:
            logging.debug('closeEvent() Yes clicked')
            event.accept()
            sys.exit(0)
示例#59
0
class SongsTableContainer(QFrame):
    def __init__(self, app, parent=None):
        super().__init__(parent)
        self._app = app

        self.songs_table = SongsTableView(self)
        self._toolbar = TableToolbar(self)
        self._cover_label = QLabel(self)
        self._desc_container_folded = True
        self._desc_container = DescriptionContainer(self)
        self._top_container = QWidget(self)
        self._cover_container = QWidget(self._top_container)

        self.songs_table.play_song_needed.connect(
            lambda song: asyncio.ensure_future(self.play_song(song)))
        self.songs_table.show_artist_needed.connect(
            lambda artist: self._app.browser.goto(model=artist))
        self.songs_table.show_album_needed.connect(
            lambda album: self._app.browser.goto(model=album))

        self._desc_container.space_pressed.connect(
            self.toggle_desc_container_fold)
        self._toolbar.toggle_desc_needed.connect(
            self.toggle_desc_container_fold)
        self._toolbar.play_all_needed.connect(self.play_all)

        self.hide()
        self._setup_ui()

    def _setup_ui(self):
        self._left_sub_layout = QVBoxLayout(self._cover_container)
        self._top_layout = QHBoxLayout(self._top_container)
        self._layout = QVBoxLayout(self)

        self._cover_label.setMinimumWidth(200)
        self._right_sub_layout = QVBoxLayout()
        self._right_sub_layout.addWidget(self._desc_container)
        self._right_sub_layout.addWidget(self._toolbar)
        self._left_sub_layout.addWidget(self._cover_label)
        self._left_sub_layout.addStretch(0)
        # 根据 Qt 文档中所说,在大部分平台中,ContentMargin 为 11
        self._left_sub_layout.setContentsMargins(0, 0, 11, 0)
        self._left_sub_layout.setSpacing(0)

        self._top_layout.addWidget(self._cover_container)
        self._top_layout.addLayout(self._right_sub_layout)
        self._top_layout.setStretch(1, 1)

        self.setAutoFillBackground(False)
        if use_mac_theme():
            self._layout.setContentsMargins(0, 0, 0, 0)
            self._layout.setSpacing(0)
        self._layout.addWidget(self._top_container)
        self._layout.addWidget(self.songs_table)

        self._top_container.setSizePolicy(QSizePolicy.Expanding,
                                          QSizePolicy.Maximum)

        # FIXME: 更好的计算宽度和高度
        # 目前是假设知道自己初始化高度大约是 530px
        # 之后可以考虑按比例来计算
        self.overview_height = 180
        self._top_container.setMaximumHeight(self.overview_height)
        self._songs_table_height = 530 - self.overview_height
        self.songs_table.setMinimumHeight(self._songs_table_height)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    async def play_song(self, song):
        loop = asyncio.get_event_loop()
        await loop.run_in_executor(None, lambda: song.url)
        self._app.player.play_song(song)

    def play_all(self):
        songs = self.songs_table.model().songs
        self._app.player.playlist.clear()
        for song in songs:
            self._app.player.playlist.add(song)
        self._app.player.play_next()

    async def show_model(self, model):
        model_type = ModelType(model._meta.model_type)
        if model_type == ModelType.album:
            func = self.show_album
        elif model_type == ModelType.artist:
            func = self.show_artist
        elif model_type == ModelType.playlist:
            func = self.show_playlist
        else:

            def func(model):
                pass  # seems silly

        with self._app.create_action('show {}'.format(str(model))):
            await func(model)

    def show_player_playlist(self, songs):
        self.show_songs(songs)
        self.songs_table.song_deleted.connect(
            lambda song: self._app.playlist.remove(song))

    def set_desc(self, desc):
        self._desc_container.show()
        self._desc_container.set_html(desc)

    async def show_playlist(self, playlist):
        self._top_container.show()
        loop = asyncio.get_event_loop()
        if playlist.meta.allow_create_songs_g:
            songs_g = playlist.create_songs_g()
            self._show_songs(songs_g=songs_g)
        else:
            songs = await loop.run_in_executor(None, lambda: playlist.songs)
            self._show_songs(songs)
        desc = '<h2>{}</h2>\n{}'.format(playlist.name, playlist.desc or '')
        self.set_desc(desc)
        if playlist.cover:
            loop.create_task(self.show_cover(playlist.cover))

        def remove_song(song):
            model = self.songs_table.model()
            row = model.songs.index(song)
            msg = 'remove {} from {}'.format(song, playlist)
            with self._app.create_action(msg) as action:
                rv = playlist.remove(song.identifier)
                if rv:
                    model.removeRow(row)
                else:
                    action.failed()

        self.songs_table.song_deleted.connect(lambda song: remove_song(song))

    async def show_artist(self, artist):
        self._top_container.show()
        loop = asyncio.get_event_loop()

        songs_g = None
        future_songs = None
        futures = []
        future_desc = loop.run_in_executor(None, lambda: artist.desc)
        futures.append(future_desc)
        if artist.meta.allow_create_songs_g:
            songs_g = artist.create_songs_g()
        else:
            future_songs = loop.run_in_executor(None, lambda: artist.songs)
            futures.append(future_songs)
        await asyncio.wait(futures)
        desc = future_desc.result()
        self.set_desc(desc or '<h2>{}</h2>'.format(artist.name))
        if songs_g is not None:
            self._show_songs(songs_g=songs_g)
        else:
            self._show_songs(songs=future_songs.result())
        if artist.cover:
            loop.create_task(self.show_cover(artist.cover))

    async def show_album(self, album):
        self._top_container.show()
        loop = asyncio.get_event_loop()
        future_songs = loop.run_in_executor(None, lambda: album.songs)
        future_desc = loop.run_in_executor(None, lambda: album.desc)
        await asyncio.wait([future_songs, future_desc])
        self.set_desc(future_desc.result() or '<h2>{}</h2>'.format(album.name))
        songs = future_songs.result()
        self._show_songs(songs)
        if album.cover:
            loop.create_task(self.show_cover(album.cover))

    def show_collection(self, collection):
        self._top_container.hide()
        self.show_songs(collection.models)
        self.songs_table.song_deleted.connect(collection.remove)

    async def show_url(self, url):
        model = self._app.protocol.get_model(url)
        if model.meta.model_type == ModelType.song:
            self._app.player.play_song(model)
        else:
            # TODO: add artist/album/user support
            self._app.show_msg('暂时只支持歌曲,不支持其它歌曲资源')

    async def show_cover(self, cover):
        # FIXME: cover_hash may not work properly someday
        cover_uid = cover.split('/', -1)[-1]
        content = await self._app.img_mgr.get(cover, cover_uid)
        img = QImage()
        img.loadFromData(content)
        pixmap = QPixmap(img)
        if not pixmap.isNull():
            self.set_cover(pixmap)
            self.update()

    def _show_songs(self, songs=None, songs_g=None):
        try:
            self.songs_table.song_deleted.disconnect()
        except TypeError:  # no connections at all
            pass
        self.show()
        self.songs_table.show()
        songs = songs or []
        logger.debug('Show songs in table, total: %d', len(songs))
        source_name_map = {
            p.identifier: p.name
            for p in self._app.library.list()
        }
        if songs_g is not None:  # 优先使用生成器
            self.songs_table.setModel(
                SongsTableModel(source_name_map=source_name_map,
                                songs_g=songs_g,
                                parent=self.songs_table))
        else:
            self.songs_table.setModel(
                SongsTableModel(songs=songs,
                                source_name_map=source_name_map,
                                parent=self.songs_table))
        self.songs_table.scrollToTop()

    def show_songs(self, songs):
        self._show_songs(songs)
        self._top_container.show()
        self.hide_desc()
        self.hide_cover()

    def set_cover(self, pixmap):
        self._cover_container.show()
        self._cover_label.setPixmap(
            pixmap.scaledToWidth(self._cover_label.width(),
                                 mode=Qt.SmoothTransformation))

    def toggle_desc_container_fold(self):
        # TODO: add toggle animation?
        if self._desc_container_folded:
            self._top_container.setMaximumHeight(4000)
            self.songs_table.hide()
            self._desc_container_folded = False
        else:
            self._top_container.setMaximumHeight(self.overview_height)
            self.songs_table.show()
            self._desc_container_folded = True

    def search(self, text):
        if self.isVisible() and self.songs_table is not None:
            self.songs_table.filter_row(text)

    def hide_cover(self):
        self._cover_container.hide()

    def hide_desc(self):
        self._desc_container.hide()
示例#60
0
文件: Polo.py 项目: JamesWrigley/Polo
    def __init__(self):
        """
        Constructor for the main application class. Creates the GUI and sets up
        the initial state.
        """
        super().__init__()

        self.player_thread = threading.Thread()
        self.output_screen_size = 32

        # Center master window
        self.resize(400, 200)
        self.center_widget(self, 0)

        # Create widgets
        self.display_widget = DisplayWidget()
        self.media_preview_stack = QStackedWidget()
        open_button = QPushButton("Open")
        clear_button = QPushButton("Clear")
        next_button = QPushButton(QIcon("next.svg"), "")
        previous_button = QPushButton(QIcon("previous.svg"), "")
        preview_label = QLabel()

        self.nav_widget = QWidget()
        self.size_widget = QWidget()
        self.size_checkbox = QCheckBox("Autosize")
        size_lineedit = QLineEdit(str(self.output_screen_size))

        # Configure
        preview_label.setScaledContents(True)
        preview_label.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        open_button.setToolTip("Choose a media file to display")
        clear_button.setToolTip(
            "Clear the current media and turn off the display")
        size_lineedit.setInputMask("D0 \\i\\n")
        self.nav_widget.setEnabled(False)
        self.media_preview_stack.addWidget(QSvgWidget("blank.svg"))
        self.media_preview_stack.addWidget(preview_label)
        self.display_widget.setScaledContents(True)
        self.display_widget.setStyleSheet("background-color: rgb(20, 20, 20);")
        self.display_widget.closed.connect(self.close)
        self.size_checkbox.setChecked(True)
        self.size_checkbox.setEnabled(False)
        self.size_checkbox.setToolTip(
            "Use automatic screen dimensions for drawing")

        # Set up connections
        open_button.clicked.connect(self.choose_media)
        clear_button.clicked.connect(self.clear_media)
        next_button.clicked.connect(lambda: self.advance_media(1))
        previous_button.clicked.connect(lambda: self.advance_media(-1))
        size_lineedit.editingFinished.connect(self.size_changed)
        self.size_checkbox.stateChanged.connect(self.set_dimensions_visibility)

        # Set shortcuts
        makeShortcut = lambda hotkey: QShortcut(
            QKeySequence(hotkey), self, context=Qt.ApplicationShortcut)
        open_shortcut = makeShortcut("O")
        clear_shortcut = makeShortcut("C")
        close_shortcut = makeShortcut("Ctrl+Q")
        self.next_shortcut = makeShortcut("N")
        self.previous_shortcut = makeShortcut("P")
        self.dimensions_shortcut = makeShortcut("A")
        self.next_shortcut.setEnabled(False)
        self.previous_shortcut.setEnabled(False)
        self.dimensions_shortcut.setEnabled(False)

        open_shortcut.activated.connect(self.choose_media)
        clear_shortcut.activated.connect(self.clear_media)
        close_shortcut.activated.connect(self.close)
        self.next_shortcut.activated.connect(lambda: self.advance_media(1))
        self.previous_shortcut.activated.connect(
            lambda: self.advance_media(-1))
        self.dimensions_shortcut.activated.connect(self.size_checkbox.toggle)

        # Pack layouts
        vbox = QVBoxLayout()
        hbox = QHBoxLayout()
        nav_hbox = QHBoxLayout()
        size_hbox = QHBoxLayout()

        nav_hbox.addWidget(previous_button)
        nav_hbox.addWidget(next_button)

        size_hbox.addWidget(QLabel("Size:"))
        size_hbox.addWidget(size_lineedit)

        vbox.addWidget(open_button)
        vbox.addWidget(clear_button)
        vbox.addWidget(self.nav_widget)
        vbox.addWidget(self.size_checkbox)
        vbox.addWidget(self.size_widget)
        vbox.addStretch()

        hbox.addLayout(vbox)
        hbox.addWidget(self.media_preview_stack)

        hbox.setSpacing(20)
        hbox.setContentsMargins(20, 20, 20, 20)
        vbox.setSpacing(10)

        nav_hbox.setContentsMargins(0, 0, 0, 0)
        size_hbox.setContentsMargins(0, 0, 0, 0)
        self.nav_widget.setLayout(nav_hbox)
        self.size_widget.setLayout(size_hbox)

        # Create slave window
        desktop_widget = QDesktopWidget()
        if desktop_widget.screenCount() != 2:
            QMessageBox.warning(self, "Warning", "Cannot find a second screen, " \
                                                 "display will be on primary screen.")
            self.display_widget.showMaximized()
        else:
            self.center_widget(self.display_widget, 1)
            self.display_widget.showFullScreen()

        # Set default values in the screen dimension widgets
        display_geometry = desktop_widget.screenGeometry(self.display_widget)
        self.size_widget.hide()

        self.display_widget.setWindowTitle("Polo - Display")

        self.setLayout(hbox)
        self.setWindowTitle("Polo")
        self.show()