Пример #1
0
    def __init__(self,
                 parent=None,
                 openExternalLinks=False,
                 elideText=False,
                 defaultStyleSheet="",
                 **kwargs):
        kwargs.setdefault(
            "sizePolicy", QSizePolicy(QSizePolicy.Minimum,
                                      QSizePolicy.Minimum))
        super().__init__(parent, **kwargs)
        self.__openExternalLinks = openExternalLinks  # type: bool
        self.__messages = OrderedDict()  # type: Dict[Hashable, Message]
        #: The full (joined all messages text - rendered as html), displayed
        #: in a tooltip.
        self.__fulltext = ""
        #: Leading icon
        self.__iconwidget = IconWidget(
            sizePolicy=QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
        #: Inline  message text
        self.__textlabel = ElidingLabel(
            wordWrap=False,
            textInteractionFlags=Qt.LinksAccessibleByMouse,
            openExternalLinks=self.__openExternalLinks,
            sizePolicy=QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum),
            elide=elideText)
        self.__textlabel.linkActivated.connect(self.linkActivated)
        self.__textlabel.linkHovered.connect(self.linkHovered)
        self.setLayout(QHBoxLayout())
        self.layout().setContentsMargins(2, 1, 2, 1)
        self.layout().setSpacing(0)
        self.layout().addWidget(self.__iconwidget, alignment=Qt.AlignLeft)
        self.layout().addSpacing(4)
        self.layout().addWidget(self.__textlabel)
        self.__textlabel.setAttribute(Qt.WA_MacSmallSize)
        self.__defaultStyleSheet = defaultStyleSheet

        self.anim = QPropertyAnimation(self.__iconwidget, b"opacity",
                                       self.__iconwidget)
        self.anim.setDuration(350)
        self.anim.setStartValue(1)
        self.anim.setKeyValueAt(0.5, 0)
        self.anim.setEndValue(1)
        self.anim.setEasingCurve(QEasingCurve.OutQuad)
        self.anim.setLoopCount(2)
Пример #2
0
    def __init__(self, master, model):
        QDialog.__init__(self)

        self.master = master

        self.setWindowFlags(Qt.Tool)
        self.setLayout(QVBoxLayout())
        self.setWindowTitle("Hidden Axes")

        btns_area = gui.widgetBox(
            self, spacing=9, orientation=Qt.Horizontal,
            sizePolicy=QSizePolicy(*SIZE_POLICY_FIXED)
        )
        self.btn_add = QPushButton(
            "Add", autoDefault=False, sizePolicy=QSizePolicy(*SIZE_POLICY_FIXED)
        )
        self.btn_add.clicked.connect(self._add)
        self.btn_cancel = QPushButton(
            "Cancel", autoDefault=False, sizePolicy=QSizePolicy(*SIZE_POLICY_FIXED)
        )
        self.btn_cancel.clicked.connect(self._cancel)

        btns_area.layout().addWidget(self.btn_add)
        btns_area.layout().addWidget(self.btn_cancel)

        filter_edit, view = variables_filter(model=model)
        self.view_other = view
        view.setMinimumSize(QSize(30, 60))
        view.setSizePolicy(*SIZE_POLICY_ADAPTING)
        view.viewport().setAcceptDrops(True)

        self.layout().addWidget(filter_edit)
        self.layout().addWidget(view)
        self.layout().addWidget(btns_area)

        master = self.master
        box = master.box
        master.master.setEnabled(False)
        self.move(box.mapToGlobal(QPoint(0, box.pos().y() + box.height())))
        self.setFixedWidth(master.master.controlArea.width())
        self.setMinimumHeight(300)
        self.show()
        self.raise_()
        self.activateWindow()
Пример #3
0
        def __init__(self, parent=None, bridge=None, *, debug=False, **kwargs):
            debug = debug or _ORANGE_DEBUG
            if debug:
                port = os.environ.setdefault('QTWEBENGINE_REMOTE_DEBUGGING',
                                             '12088')
                warnings.warn(
                    'To debug QWebEngineView, set environment variable '
                    'QTWEBENGINE_REMOTE_DEBUGGING={port} and then visit '
                    'http://127.0.0.1:{port}/ in a Chromium-based browser. '
                    'See https://doc.qt.io/qt-5/qtwebengine-debugging.html '
                    'This has also been done for you.'.format(port=port))
            super().__init__(parent,
                             sizeHint=QSize(500, 400),
                             sizePolicy=QSizePolicy(QSizePolicy.Expanding,
                                                    QSizePolicy.Expanding),
                             **kwargs)
            self.bridge = bridge
            self.debug = debug
            with open(_WEBVIEW_HELPERS, encoding="utf-8") as f:
                self._onloadJS(
                    f.read(),
                    name='webview_helpers',
                    injection_point=QWebEngineScript.DocumentCreation)

            qtwebchannel_js = QFile("://qtwebchannel/qwebchannel.js")
            if qtwebchannel_js.open(QFile.ReadOnly):
                source = bytes(qtwebchannel_js.readAll()).decode("utf-8")
                with open(_WEBENGINE_INIT_WEBCHANNEL, encoding="utf-8") as f:
                    init_webchannel_src = f.read()
                self._onloadJS(
                    source + init_webchannel_src %
                    dict(exposeObject_prefix=self._EXPOSED_OBJ_PREFIX),
                    name='webchannel_init',
                    injection_point=QWebEngineScript.DocumentCreation)
            else:
                warnings.warn(
                    "://qtwebchannel/qwebchannel.js is not readable.",
                    RuntimeWarning)

            self._onloadJS(';window.__load_finished = true;',
                           name='load_finished',
                           injection_point=QWebEngineScript.DocumentReady)

            channel = QWebChannel(self)
            if bridge is not None:
                if isinstance(bridge, QWidget):
                    warnings.warn(
                        "Don't expose QWidgets in WebView. Construct minimal "
                        "QObjects instead.",
                        OrangeDeprecationWarning,
                        stacklevel=2)
                channel.registerObject("pybridge", bridge)

            channel.registerObject('__bridge', _QWidgetJavaScriptWrapper(self))

            self.page().setWebChannel(channel)
Пример #4
0
 def __init__(self, parent: QWidget, items: List[str], callback: Callable):
     super().__init__(parent, callback)
     self._combo = QComboBox(
         parent,
         maximumWidth=180,
         sizePolicy=QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
     )
     self._combo.addItems(items)
     self._combo.currentIndexChanged.connect(self.valueChanged)
     self.layout().addWidget(self._combo)
Пример #5
0
 def _insert_main_area(self):
     self.mainArea = gui.vBox(
         self.__splitter, margin=4,
         sizePolicy=QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
     )
     self.__splitter.addWidget(self.mainArea)
     self.__splitter.setCollapsible(
         self.__splitter.indexOf(self.mainArea), False)
     self.mainArea.layout().setContentsMargins(
         0 if self.want_control_area else 4, 4, 4, 4)
Пример #6
0
 def __init__(self):
     super().__init__(
         editTriggers=QListView.DoubleClicked | QListView.EditKeyPressed,
         sizePolicy=QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Expanding),
         minimumWidth=200,
         selectionMode=QListView.ExtendedSelection,
         dragEnabled=True,
         acceptDrops=True,
         defaultDropAction=Qt.MoveAction,
     )
     self.setDropIndicatorShown(True)
Пример #7
0
 def add_textual(contents):
     le = gui.lineEdit(box,
                       self,
                       None,
                       sizePolicy=QSizePolicy(QSizePolicy.Expanding,
                                              QSizePolicy.Expanding))
     if contents:
         le.setText(contents)
     le.setAlignment(Qt.AlignRight)
     le.editingFinished.connect(self.conditions_changed)
     return le
Пример #8
0
    def __init__(self, rgbColors, parent=None, windowTitle="Palette Editor",
                 **kwargs):
        super().__init__(parent, **kwargs)
        self.setLayout(QVBoxLayout())
        self.layout().setContentsMargins(4, 4, 4, 4)

        hbox = gui.hBox(self, "Information")
        gui.widgetLabel(
            hbox,
            '<p align="center">You can reorder colors in the list using the'
            '<br/>buttons on the right or by dragging and dropping the items.'
            '<br/>To change a specific color double click the item in the '
            'list.</p>')

        hbox = gui.hBox(self, box=True)
        self.discListbox = gui.listBox(hbox, self, enableDragDrop=1)

        vbox = gui.vBox(hbox)
        buttonUPAttr = gui.button(vbox, self, "", callback=self.moveAttrUP,
                                  tooltip="Move selected colors up")
        buttonDOWNAttr = gui.button(vbox, self, "", callback=self.moveAttrDOWN,
                                    tooltip="Move selected colors down")
        buttonUPAttr.setIcon(QIcon(gui.resource_filename("icons/Dlg_up3.png")))
        buttonUPAttr.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding))
        buttonUPAttr.setMaximumWidth(30)
        buttonDOWNAttr.setIcon(QIcon(gui.resource_filename("icons/Dlg_down3.png")))
        buttonDOWNAttr.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding))
        buttonDOWNAttr.setMaximumWidth(30)
        self.discListbox.itemDoubleClicked.connect(self.changeDiscreteColor)

        box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
                               accepted=self.accept, rejected=self.reject)
        self.layout().addWidget(box)

        self.discListbox.setIconSize(QSize(25, 25))
        for ind, (r, g, b) in enumerate(rgbColors):
            item = QListWidgetItem(ColorPixmap(QColor(r, g, b), 25), "Color %d" % (ind + 1))
            item.rgbColor = (r, g, b)
            self.discListbox.addItem(item)

        self.resize(300, 300)
    def __call__(self, master, model_selected, model_other):
        self.master = master

        params_view = {
            "sizePolicy": QSizePolicy(*SIZE_POLICY_ADAPTING),
            "selectionMode": QListView.ExtendedSelection,
            "dragEnabled": True,
            "defaultDropAction": Qt.MoveAction,
            "dragDropOverwriteMode": False,
            "dragDropMode": QListView.DragDrop
        }

        self.view_selected = view = gui.listView(widget=master.controlArea,
                                                 master=master,
                                                 box="Displayed Axes",
                                                 **params_view)
        view.box.setMinimumHeight(120)
        view.viewport().setAcceptDrops(True)

        delete = QAction("Delete",
                         view,
                         shortcut=QKeySequence(Qt.Key_Delete),
                         triggered=self.__deactivate_selection)
        view.addAction(delete)

        self.model_selected = model = model_selected

        model.rowsInserted.connect(master.invalidate_plot)
        model.rowsRemoved.connect(master.invalidate_plot)
        model.rowsMoved.connect(master.invalidate_plot)

        view.setModel(model)

        addClassLabel = QAction("+",
                                master,
                                toolTip="Add new class label",
                                triggered=self._action_add)
        removeClassLabel = QAction(unicodedata.lookup("MINUS SIGN"),
                                   master,
                                   toolTip="Remove selected class label",
                                   triggered=self.__deactivate_selection)

        add_remove = itemmodels.ModelActionsWidget(
            [addClassLabel, removeClassLabel], master)
        add_remove.layout().addStretch(10)
        add_remove.layout().setSpacing(1)
        add_remove.setSizePolicy(*SIZE_POLICY_FIXED)
        view.box.layout().addWidget(add_remove)

        self.add_remove = add_remove
        self.box = add_remove.buttons[1]

        self.model_other = model_other
Пример #10
0
 def __init__(self, parent=None, openExternalLinks=False, **kwargs):
     kwargs.setdefault(
         "sizePolicy", QSizePolicy(QSizePolicy.Minimum,
                                   QSizePolicy.Minimum))
     super().__init__(parent, **kwargs)
     self.__openExternalLinks = openExternalLinks  # type: bool
     self.__messages = OrderedDict()  # type: Dict[Hashable, Message]
     #: The full (joined all messages text - rendered as html), displayed
     #: in a tooltip.
     self.__fulltext = ""
     #: The full text displayed in a popup. Is empty if the message is
     #: short
     self.__popuptext = ""
     #: Leading icon
     self.__iconwidget = IconWidget(
         sizePolicy=QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))
     #: Inline  message text
     self.__textlabel = QLabel(
         wordWrap=False,
         textInteractionFlags=Qt.LinksAccessibleByMouse,
         openExternalLinks=self.__openExternalLinks,
         sizePolicy=QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum),
     )
     #: Indicator that extended contents are accessible with a click on the
     #: widget.
     self.__popupicon = QLabel(
         sizePolicy=QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum),
         text="\N{VERTICAL ELLIPSIS}",
         visible=False,
     )
     self.__textlabel.linkActivated.connect(self.linkActivated)
     self.__textlabel.linkHovered.connect(self.linkHovered)
     self.setLayout(QHBoxLayout())
     self.layout().setContentsMargins(2, 1, 2, 1)
     self.layout().setSpacing(0)
     self.layout().addWidget(self.__iconwidget)
     self.layout().addSpacing(4)
     self.layout().addWidget(self.__textlabel)
     self.layout().addWidget(self.__popupicon)
     self.__textlabel.setAttribute(Qt.WA_MacSmallSize)
Пример #11
0
 def __init__(self, scene, parent, **kwargs):
     for k, v in dict(verticalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
                      horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
                      viewportUpdateMode=QGraphicsView.BoundingRectViewportUpdate,
                      renderHints=(QPainter.Antialiasing |
                                   QPainter.TextAntialiasing |
                                   QPainter.SmoothPixmapTransform),
                      alignment=(Qt.AlignTop |
                                 Qt.AlignLeft),
                      sizePolicy=QSizePolicy(QSizePolicy.MinimumExpanding,
                                             QSizePolicy.MinimumExpanding)).items():
         kwargs.setdefault(k, v)
     super().__init__(scene, parent, **kwargs)
Пример #12
0
    def __init__(self):
        super().__init__()

        self.corpus = None      # Corpus
        self.n_documents = ''   # Info on docs
        self.n_matching = ''    # Info on docs matching the word
        self.n_tokens = ''      # Info on tokens
        self.n_types = ''       # Info on types (unique tokens)

        # Info attributes
        info_box = gui.widgetBox(self.controlArea, 'Info')
        gui.label(info_box, self, 'Documents: %(n_documents)s')
        gui.label(info_box, self, 'Tokens: %(n_tokens)s')
        gui.label(info_box, self, 'Types: %(n_types)s')
        gui.label(info_box, self, 'Matching: %(n_matching)s')

        # Width parameter
        gui.spin(self.controlArea, self, 'context_width', 3, 10, box=True,
                 label="Number of words:", callback=self.set_width)

        gui.rubber(self.controlArea)

        # Search
        c_box = gui.widgetBox(self.mainArea, orientation="vertical")
        self.input = gui.lineEdit(
            c_box, self, 'word', orientation=Qt.Horizontal,
            sizePolicy=QSizePolicy(QSizePolicy.MinimumExpanding,
                                   QSizePolicy.Fixed),
            label='Query:', callback=self.set_word, callbackOnType=True)
        self.input.setFocus()

        # Concordances view
        self.conc_view = QTableView()
        self.model = ConcordanceModel()
        self.conc_view.setModel(self.model)
        self.conc_view.setWordWrap(False)
        self.conc_view.setSelectionBehavior(QTableView.SelectRows)
        self.conc_view.setSelectionModel(DocumentSelectionModel(self.model))
        self.conc_view.setItemDelegate(HorizontalGridDelegate())
        # connect selectionChanged to self.commit(), which will be
        # updated by gui.auto_commit()
        self.conc_view.selectionModel().selectionChanged.connect(lambda:
                                                                 self.commit())
        self.conc_view.horizontalHeader().hide()
        self.conc_view.setShowGrid(False)
        self.mainArea.layout().addWidget(self.conc_view)
        self.set_width()

        # Auto-commit box
        gui.auto_commit(self.controlArea, self, 'autocommit', 'Commit',
                        'Auto commit is on')
Пример #13
0
    def _setup_library_box(self):
        self.library_view = QListView(
            editTriggers=QListView.DoubleClicked | QListView.EditKeyPressed,
            minimumWidth=200,
            sizePolicy=QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Expanding),
        )
        self.library_view.setItemDelegate(WordListItemDelegate(self))
        self.library_view.setModel(self.library_model)
        self.library_view.selectionModel().selectionChanged.connect(
            self.__on_library_selection_changed)

        self.__library_box.layout().setSpacing(1)
        self.__library_box.layout().addWidget(self.library_view)

        actions_widget = ModelActionsWidget()
        actions_widget.layout().setSpacing(1)

        action = QAction("+", self)
        action.setToolTip("Add a new word list to the library")
        action.triggered.connect(self.__on_add_word_list)
        actions_widget.addAction(action)

        action = QAction("\N{MINUS SIGN}", self)
        action.setToolTip("Remove word list from library")
        action.triggered.connect(self.__on_remove_word_list)
        actions_widget.addAction(action)

        action = QAction("Update", self)
        action.setToolTip("Save changes in the editor to library")
        action.setShortcut(QKeySequence(QKeySequence.Save))
        action.triggered.connect(self.__on_update_word_list)
        actions_widget.addAction(action)

        gui.rubber(actions_widget.layout())

        action = QAction("More", self, toolTip="More actions")

        new_from_file = QAction("Import Words from File", self)
        new_from_file.triggered.connect(self.__on_import_word_list)

        save_to_file = QAction("Save Words to File", self)
        save_to_file.setShortcut(QKeySequence(QKeySequence.SaveAs))
        save_to_file.triggered.connect(self.__on_save_word_list)

        menu = QMenu(actions_widget)
        menu.addAction(new_from_file)
        menu.addAction(save_to_file)
        action.setMenu(menu)
        button = actions_widget.addAction(action)
        button.setPopupMode(QToolButton.InstantPopup)
        self.__library_box.layout().addWidget(actions_widget)
Пример #14
0
    def __init__(self, parent=None, items=None, **kwargs):
        super().__init__(parent, **kwargs)
        self.setFlag(QGraphicsWidget.ItemClipsChildrenToShape, True)
        self.__items = []
        self.__textitems = []
        self.__group = None
        self.__spacing = 0

        sp = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sp.setWidthForHeight(True)
        self.setSizePolicy(sp)

        if items is not None:
            self.setItems(items)
Пример #15
0
    def __init__(self, parent=None, orientation=Qt.Horizontal, **kwargs):
        sizePolicy = kwargs.pop("sizePolicy", None)
        super().__init__(None, **kwargs)
        self.__orientation = Qt.Horizontal
        if sizePolicy is None:
            sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
            sizePolicy.setControlType(QSizePolicy.Frame)
            self.setSizePolicy(sizePolicy)
        else:
            self.setSizePolicy(sizePolicy)

        self.setOrientation(orientation)

        if parent is not None:
            self.setParentItem(parent)
Пример #16
0
        def __init__(self, parent=None, bridge=None, *, debug=False, **kwargs):
            super().__init__(parent,
                             sizeHint=QSize(500, 400),
                             sizePolicy=QSizePolicy(QSizePolicy.Expanding,
                                                    QSizePolicy.Expanding),
                             **kwargs)

            if isinstance(parent, QWidget) and parent.layout() is not None:
                parent.layout().addWidget(self)  # TODO REMOVE

            self.bridge = bridge
            self.frame = None
            debug = debug or _ORANGE_DEBUG
            self.debug = debug

            if isinstance(bridge, QWidget):
                warnings.warn(
                    "Don't expose QWidgets in WebView. Construct minimal "
                    "QObjects instead.",
                    OrangeDeprecationWarning,
                    stacklevel=2,
                )

            def _onload(_ok):
                if _ok:
                    self.frame = self.page().mainFrame()
                    self.frame.javaScriptWindowObjectCleared.connect(
                        lambda: self.frame.addToJavaScriptWindowObject(
                            "pybridge", bridge))
                    with open(_WEBVIEW_HELPERS, encoding="utf-8") as f:
                        self.frame.evaluateJavaScript(f.read())

            self.loadFinished.connect(_onload)
            _onload(True)

            history = self.history()
            history.setMaximumItemCount(0)
            settings = self.settings()
            settings.setMaximumPagesInCache(0)
            settings.setAttribute(settings.LocalContentCanAccessFileUrls, True)
            settings.setAttribute(settings.LocalContentCanAccessRemoteUrls,
                                  False)

            if debug:
                settings.setAttribute(settings.LocalStorageEnabled, True)
                settings.setAttribute(settings.DeveloperExtrasEnabled, True)
                settings.setObjectCacheCapacities(4e6, 4e6, 4e6)
                settings.enablePersistentStorage()
Пример #17
0
    def __init__(self, parent=None, **kwargs):
        # type: (Optional[QWidget], Any)-> None
        super().__init__(parent, **kwargs)
        self.__pages = []  # type: List[_ToolBoxPage]
        self.__tabButtonHeight = -1
        self.__tabIconSize = QSize()
        self.__exclusive = False
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)

        # Scroll area for the contents.
        self.__scrollArea = QScrollArea(
            self,
            objectName="toolbox-scroll-area",
            sizePolicy=QSizePolicy(QSizePolicy.MinimumExpanding,
                                   QSizePolicy.MinimumExpanding),
            horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff,
            widgetResizable=True,
        )
        sb = ScrollBar()
        sb.styleChange.connect(self.updateGeometry)
        self.__scrollArea.setVerticalScrollBar(sb)
        self.__scrollArea.setFrameStyle(QScrollArea.NoFrame)

        # A widget with all of the contents.
        # The tabs/contents are placed in the layout inside this widget
        self.__contents = QWidget(self.__scrollArea,
                                  objectName="toolbox-contents")
        self.__contentsLayout = _ToolBoxLayout(
            sizeConstraint=_ToolBoxLayout.SetMinAndMaxSize, spacing=0)
        self.__contentsLayout.setContentsMargins(0, 0, 0, 0)
        self.__contents.setLayout(self.__contentsLayout)

        self.__scrollArea.setWidget(self.__contents)

        layout.addWidget(self.__scrollArea)

        self.setLayout(layout)
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.MinimumExpanding)

        self.__tabActionGroup = QActionGroup(
            self,
            objectName="toolbox-tab-action-group",
        )
        self.__tabActionGroup.setExclusive(self.__exclusive)
        self.__actionMapper = QSignalMapper(self)
        self.__actionMapper.mapped[QObject].connect(self.__onTabActionToggled)
Пример #18
0
    def _create_layout(self):
        box = gui.widgetBox(self.controlArea, orientation='horizontal')
        self.varmodel = VariableListModel(parent=self)
        self.attr_combo = gui.comboBox(box,
                                       self,
                                       'selected_attr',
                                       orientation=Qt.Horizontal,
                                       label='Region attribute:',
                                       callback=self.on_attr_change,
                                       sendSelectedValue=True)
        self.attr_combo.setModel(self.varmodel)
        self.map_combo = gui.comboBox(box,
                                      self,
                                      'selected_map',
                                      orientation=Qt.Horizontal,
                                      label='Map type:',
                                      callback=self.on_map_change,
                                      items=Map.all)
        hexpand = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.attr_combo.setSizePolicy(hexpand)
        self.map_combo.setSizePolicy(hexpand)

        url = urljoin(
            'file:',
            pathname2url(
                os.path.join(os.path.dirname(__file__), 'resources',
                             'owdocmap.html')))

        class Bridge(QObject):
            @pyqtSlot(str)
            def region_selected(_, regions):
                return self.region_selected(regions)

        self.webview = gui.WebviewWidget(self.controlArea,
                                         Bridge(),
                                         url=QUrl(url),
                                         debug=False)
        self.controlArea.layout().addWidget(self.webview)

        QTimer.singleShot(
            0,
            lambda: self.webview.evalJS('REGIONS = {};'.format({
                Map.WORLD: CC_WORLD,
                Map.EUROPE: CC_EUROPE,
                Map.USA: CC_USA
            })))
Пример #19
0
        def __init__(self, parent=None, bridge=None, *, debug=False, **kwargs):
            if debug:
                import os
                port = os.environ.setdefault('QTWEBENGINE_REMOTE_DEBUGGING',
                                             '12088')
                warnings.warn(
                    'To debug QWebEngineView, set environment variable '
                    'QTWEBENGINE_REMOTE_DEBUGGING={port} and then visit '
                    'http://localhost:{port}/ in a Chromium-based browser. '
                    'See https://doc.qt.io/qt-5/qtwebengine-debugging.html '
                    'This has also been done for you.'.format(port=port))
            super().__init__(parent,
                             sizeHint=QSize(500, 400),
                             sizePolicy=QSizePolicy(QSizePolicy.Expanding,
                                                    QSizePolicy.Expanding),
                             **kwargs)
            self.bridge = bridge
            self.debug = debug

            self._onloadJS(open(_WEBVIEW_HELPERS).read(),
                           name='webview_helpers',
                           injection_point=QWebEngineScript.DocumentCreation)

            qtwebchannel_js = QFile("://qtwebchannel/qwebchannel.js")
            if qtwebchannel_js.open(QFile.ReadOnly):
                source = bytes(qtwebchannel_js.readAll()).decode("utf-8")
                self._onloadJS(
                    source + open(_WEBENGINE_INIT_WEBCHANNEL).read() %
                    dict(exposeObject_prefix=self._EXPOSED_OBJ_PREFIX),
                    name='webchannel_init',
                    injection_point=QWebEngineScript.DocumentCreation)
            else:
                warnings.warn(
                    "://qtwebchannel/qwebchannel.js is not readable.",
                    RuntimeWarning)

            self._onloadJS(';window.__load_finished = true;',
                           name='load_finished',
                           injection_point=QWebEngineScript.DocumentReady)

            channel = QWebChannel(self)
            if bridge is not None:
                channel.registerObject("pybridge", bridge)
            channel.registerObject('__self', self)  # Subclasses rely in this
            self.page().setWebChannel(channel)
Пример #20
0
    def __init__(self):
        super().__init__()

        box = gui.widgetBox(self.controlArea, "Movie Selection (from %d)" % \
            len(movielens.get_all_movie_names()))
        methodbox = gui.radioButtons(box,
                                     self,
                                     "method",
                                     callback=self._on_method_changed)

        gui.appendRadioButton(methodbox, "Fraction of movies")
        percent = gui.hSlider(gui.indentedBox(methodbox),
                              self,
                              "percent",
                              minValue=1,
                              maxValue=100,
                              step=1,
                              ticks=10,
                              labelFormat="%d %%")

        gui.appendRadioButton(methodbox, "Time period:")
        ibox = gui.indentedBox(methodbox)
        start = gui.spin(ibox,
                         self,
                         "start",
                         1907,
                         2015,
                         1,
                         label="Starting year: ")
        end = gui.spin(ibox, self, "end", 1907, 2015, 1, label="Ending year: ")

        self.method_params = [percent, start, end]

        gui.button(self.controlArea,
                   self,
                   "&Apply",
                   callback=self.send_output,
                   default=True)

        self.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))

        self.setMinimumWidth(250)
        self.setMaximumWidth(250)
        self._on_method_changed()
        self.send_output()
Пример #21
0
    def __init__(self):
        super().__init__()
        self.movies = None
        self.infobox = gui.widgetBox(self.controlArea, "Select Actors")

        percent = gui.hSlider(
            gui.indentedBox(self.infobox), self, "percent",
            minValue=1, maxValue=100, step=1, ticks=10, labelFormat="%d %%")

        gui.button(self.controlArea, self, "&Apply",
                   callback=self.send_output, default=True)

        self.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))

        self.setMinimumWidth(250)
        self.setMaximumWidth(250)

        self.movies = None
Пример #22
0
    def __init__(self, *args, acceptedType=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.setSizePolicy(
            QSizePolicy(QSizePolicy.Minimum, QSizePolicy.MinimumExpanding))
        self.setMinimumHeight(10)
        self.setMouseTracking(True)
        self.setAttribute(Qt.WA_Hover)

        self.setSelectionMode(self.SingleSelection)
        self.setAutoScroll(False)  # Prevent scrolling to removed item
        self.setDragEnabled(True)
        self.setDropIndicatorShown(True)
        self.setDragDropMode(self.InternalMove)
        self.setDefaultDropAction(Qt.MoveAction)
        self.setDragDropOverwriteMode(False)
        self.setUniformItemSizes(True)

        self.setItemDelegate(VariablesDelegate())
Пример #23
0
    def __init__(self):
        self.data = None
        # List of all features (model for ComboBox)
        self.features = itemmodels.VariableListModel(
            ["Select Feature"], parent=self)

        box = gui.vBox(self.controlArea, "Select ")
        self.features_widget = QComboBox(
            self.controlArea,
            minimumContentsLength=16,
            sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLengthWithIcon,
            sizePolicy=QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        )
        self.features_widget.setModel(self.features)
        self.features_widget.currentIndexChanged.connect(self.feature_changed)
        self.button = QPushButton("Split")
        self.button.clicked.connect(self.split)
        self.button.setEnabled(False)

        box.layout().addWidget(self.features_widget)
        box.layout().addWidget(self.button)
Пример #24
0
    def init_form(self):
        self._form = QWidget()
        layout = QVBoxLayout()

        if _api.USED_API == _api.QT_API_PYQT5:
            layout.setContentsMargins(0, 0, 0, 0)
        else:
            layout.setMargin(0)

        self._form.setLayout(layout)
        self._app = vv.use('pyqt5')
        self._app.Create()

        Figure = self._app.GetFigureClass()
        self._fig = Figure(self._form)

        policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        widget = self._fig._widget
        widget.setSizePolicy(policy)

        layout.addWidget(widget)
Пример #25
0
        def __init__(self, parent=None, bridge=None, *, debug=False, **kwargs):
            super().__init__(parent,
                             sizeHint=QSize(500, 400),
                             sizePolicy=QSizePolicy(QSizePolicy.Expanding,
                                                    QSizePolicy.Expanding),
                             **kwargs)

            if isinstance(parent, QWidget) and parent.layout() is not None:
                parent.layout().addWidget(self)  # TODO REMOVE

            self.bridge = bridge
            self.frame = None
            self.debug = debug

            def _onload(_ok):
                if _ok:
                    self.frame = self.page().mainFrame()
                    self.frame.javaScriptWindowObjectCleared.connect(
                        lambda: self.frame.addToJavaScriptWindowObject(
                            'pybridge', bridge))
                    self.frame.evaluateJavaScript(
                        open(_WEBVIEW_HELPERS).read())

            self.loadFinished.connect(_onload)
            _onload(True)

            history = self.history()
            history.setMaximumItemCount(0)
            settings = self.settings()
            settings.setMaximumPagesInCache(0)
            settings.setAttribute(settings.LocalContentCanAccessFileUrls, True)
            settings.setAttribute(settings.LocalContentCanAccessRemoteUrls,
                                  False)

            if debug:
                settings.setAttribute(settings.LocalStorageEnabled, True)
                settings.setAttribute(settings.DeveloperExtrasEnabled, True)
                settings.setObjectCacheCapacities(4e6, 4e6, 4e6)
                settings.enablePersistentStorage()
Пример #26
0
    def make_tree_view(self, type, callback, append_to):
        if (type == 'comm'):
            data = unc.commodities_HS_all()
        elif (type == 'ser'):
            data = unc.services_all()

        global current_tree_widget
        if (current_tree_widget is not None):
            append_to.layout().removeWidget(current_tree_widget)

        class TreeView(QTreeView):
            def sizeHint(self):
                return QSize(700, 600)

        tree = TreeView(
            sizePolicy=QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum))
        model = QStandardItemModel(0, 1)

        model = self.recursive({'children': data}, None, model)

        self.comm_ser_top_item = model.index(0, 0)

        model.itemChanged.connect(callback)
        tree.setModel(model)
        tree.setHeaderHidden(True)
        tree.expandAll()
        tree.setEditTriggers(QAbstractItemView.NoEditTriggers)

        proxy_model = FindFilterProxyModel()
        proxy_model.setSourceModel(model)
        proxy_model.setFilterKeyColumn(-1)
        tree.setModel(proxy_model)
        tree.expandAll()

        current_tree_widget = tree

        append_to.layout().addWidget(tree)

        return [tree, proxy_model, model]
Пример #27
0
    def __init__(
            self,
            parent: Optional[QGraphicsItem] = None,
            items: Iterable[str] = (),
            alignment: Union[Qt.AlignmentFlag, Qt.Alignment] = Qt.AlignLeading,
            orientation: Qt.Orientation = Qt.Vertical,
            autoScale=False,
            elideMode=Qt.ElideNone,
            **kwargs: Any
    ) -> None:
        self.__items: List[str] = []
        self.__textitems: List[QGraphicsSimpleTextItem] = []
        self.__group: Optional[QGraphicsItemGroup] = None
        self.__spacing = 0
        self.__alignment = Qt.AlignmentFlag(alignment)
        self.__orientation = orientation
        self.__autoScale = autoScale
        # The effective font when autoScale is in effect
        self.__effectiveFont = QFont()
        self.__widthCache = {}
        self.__elideMode = elideMode
        sizePolicy = kwargs.pop(
            "sizePolicy", None)  # type: Optional[QSizePolicy]
        super().__init__(None, **kwargs)
        self.setFlag(QGraphicsWidget.ItemClipsChildrenToShape, True)
        sp = QSizePolicy(QSizePolicy.Preferred,
                         QSizePolicy.Preferred)
        sp.setWidthForHeight(True)
        self.setSizePolicy(sp)

        if sizePolicy is not None:
            self.setSizePolicy(sizePolicy)

        if parent is not None:
            self.setParentItem(parent)

        if items is not None:
            self.setItems(items)
Пример #28
0
    def __init__(self):
        super().__init__()
        self.libraryListSource = []

        for name in self.signal_names:
            setattr(self, name, {})

        self._cachedDocuments = {}

        self.infoBox = gui.vBox(self.controlArea, 'Info')
        gui.label(
            self.infoBox, self,
            "<p>Execute python script.</p><p>Input variables:<ul><li> " +
            "<li>".join(map("in_{0}, in_{0}s".format, self.signal_names)) +
            "</ul></p><p>Output variables:<ul><li>" +
            "<li>".join(map("out_{0}".format, self.signal_names)) +
            "</ul></p>")

        self.libraryList = itemmodels.PyListModel(
            [],
            self,
            flags=Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable)

        self.libraryList.wrap(self.libraryListSource)

        self.controlBox = gui.vBox(self.controlArea, 'Library')
        self.controlBox.layout().setSpacing(1)

        self.libraryView = QListView(
            editTriggers=QListView.DoubleClicked | QListView.EditKeyPressed,
            sizePolicy=QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred))
        self.libraryView.setItemDelegate(ScriptItemDelegate(self))
        self.libraryView.setModel(self.libraryList)

        self.libraryView.selectionModel().selectionChanged.connect(
            self.onSelectedScriptChanged)
        self.controlBox.layout().addWidget(self.libraryView)

        w = itemmodels.ModelActionsWidget()

        self.addNewScriptAction = action = QAction("+", self)
        action.setToolTip("Add a new script to the library")
        action.triggered.connect(self.onAddScript)
        w.addAction(action)

        action = QAction(unicodedata.lookup("MINUS SIGN"), self)
        action.setToolTip("Remove script from library")
        action.triggered.connect(self.onRemoveScript)
        w.addAction(action)

        action = QAction("Update", self)
        action.setToolTip("Save changes in the editor to library")
        action.setShortcut(QKeySequence(QKeySequence.Save))
        action.triggered.connect(self.commitChangesToLibrary)
        w.addAction(action)

        action = QAction("More", self, toolTip="More actions")

        new_from_file = QAction("Import Script from File", self)
        save_to_file = QAction("Save Selected Script to File", self)
        restore_saved = QAction("Undo Changes to Selected Script", self)
        save_to_file.setShortcut(QKeySequence(QKeySequence.SaveAs))

        new_from_file.triggered.connect(self.onAddScriptFromFile)
        save_to_file.triggered.connect(self.saveScript)
        restore_saved.triggered.connect(self.restoreSaved)

        menu = QMenu(w)
        menu.addAction(new_from_file)
        menu.addAction(save_to_file)
        menu.addAction(restore_saved)
        action.setMenu(menu)
        button = w.addAction(action)
        button.setPopupMode(QToolButton.InstantPopup)

        w.layout().setSpacing(1)

        self.controlBox.layout().addWidget(w)

        self.execute_button = gui.button(self.controlArea,
                                         self,
                                         'Run',
                                         callback=self.commit)

        run = QAction("Run script",
                      self,
                      triggered=self.commit,
                      shortcut=QKeySequence(Qt.ControlModifier | Qt.Key_R))
        self.addAction(run)

        self.splitCanvas = QSplitter(Qt.Vertical, self.mainArea)
        self.mainArea.layout().addWidget(self.splitCanvas)

        self.defaultFont = defaultFont = \
            "Monaco" if sys.platform == "darwin" else "Courier"

        self.textBox = gui.vBox(self, 'Python Script')
        self.splitCanvas.addWidget(self.textBox)
        self.text = PythonScriptEditor(self)
        self.textBox.layout().addWidget(self.text)

        self.textBox.setAlignment(Qt.AlignVCenter)
        self.text.setTabStopWidth(4)

        self.text.modificationChanged[bool].connect(self.onModificationChanged)

        self.saveAction = action = QAction("&Save", self.text)
        action.setToolTip("Save script to file")
        action.setShortcut(QKeySequence(QKeySequence.Save))
        action.setShortcutContext(Qt.WidgetWithChildrenShortcut)
        action.triggered.connect(self.saveScript)

        self.consoleBox = gui.vBox(self, 'Console')
        self.splitCanvas.addWidget(self.consoleBox)
        self.console = PythonConsole({}, self)
        self.consoleBox.layout().addWidget(self.console)
        self.console.document().setDefaultFont(QFont(defaultFont))
        self.consoleBox.setAlignment(Qt.AlignBottom)
        self.console.setTabStopWidth(4)
        self.splitCanvas.setSizes([2, 1])
        self.setAcceptDrops(True)
        self.controlArea.layout().addStretch(10)

        self._restoreState()
        self.settingsAboutToBePacked.connect(self._saveState)
Пример #29
0
    def __init__(self):
        super().__init__()
        self.data = None
        self.editors = {}

        box = gui.vBox(self.controlArea, "Variable Definitions")

        toplayout = QHBoxLayout()
        toplayout.setContentsMargins(0, 0, 0, 0)
        box.layout().addLayout(toplayout)

        self.editorstack = QStackedWidget(
            sizePolicy=QSizePolicy(QSizePolicy.MinimumExpanding,
                                   QSizePolicy.MinimumExpanding)
        )

        for descclass, editorclass in self.EDITORS:
            editor = editorclass()
            editor.featureChanged.connect(self._on_modified)
            self.editors[descclass] = editor
            self.editorstack.addWidget(editor)

        self.editorstack.setEnabled(False)

        buttonlayout = QVBoxLayout(spacing=10)
        buttonlayout.setContentsMargins(0, 0, 0, 0)

        self.addbutton = QPushButton(
            "New", toolTip="Create a new variable",
            minimumWidth=120,
            shortcut=QKeySequence.New
        )

        def unique_name(fmt, reserved):
            candidates = (fmt.format(i) for i in count(1))
            return next(c for c in candidates if c not in reserved)

        def reserved_names():
            varnames = []
            if self.data is not None:
                varnames = [var.name for var in
                            self.data.domain.variables + self.data.domain.metas]
            varnames += [desc.name for desc in self.featuremodel]
            return set(varnames)

        def generate_newname(fmt):
            return unique_name(fmt, reserved_names())

        menu = QMenu(self.addbutton)
        cont = menu.addAction("Continuous")
        cont.triggered.connect(
            lambda: self.addFeature(
                ContinuousDescriptor(generate_newname("X{}"), "", 3))
        )
        disc = menu.addAction("Discrete")
        disc.triggered.connect(
            lambda: self.addFeature(
                DiscreteDescriptor(generate_newname("D{}"), "",
                                   ("A", "B"), -1, False))
        )
        string = menu.addAction("String")
        string.triggered.connect(
            lambda: self.addFeature(
                StringDescriptor(generate_newname("S{}"), ""))
        )
        menu.addSeparator()
        self.duplicateaction = menu.addAction("Duplicate Selected Variable")
        self.duplicateaction.triggered.connect(self.duplicateFeature)
        self.duplicateaction.setEnabled(False)
        self.addbutton.setMenu(menu)

        self.removebutton = QPushButton(
            "Remove", toolTip="Remove selected variable",
            minimumWidth=120,
            shortcut=QKeySequence.Delete
        )
        self.removebutton.clicked.connect(self.removeSelectedFeature)

        buttonlayout.addWidget(self.addbutton)
        buttonlayout.addWidget(self.removebutton)
        buttonlayout.addStretch(10)

        toplayout.addLayout(buttonlayout, 0)
        toplayout.addWidget(self.editorstack, 10)

        # Layout for the list view
        layout = QVBoxLayout(spacing=1, margin=0)
        self.featuremodel = DescriptorModel(parent=self)

        self.featureview = QListView(
            minimumWidth=200,
            sizePolicy=QSizePolicy(QSizePolicy.Minimum,
                                   QSizePolicy.MinimumExpanding)
        )

        self.featureview.setItemDelegate(FeatureItemDelegate(self))
        self.featureview.setModel(self.featuremodel)
        self.featureview.selectionModel().selectionChanged.connect(
            self._on_selectedVariableChanged
        )

        layout.addWidget(self.featureview)

        box.layout().addLayout(layout, 1)

        box = gui.hBox(self.controlArea)
        box.layout().addWidget(self.report_button)
        self.report_button.setMinimumWidth(180)
        gui.rubber(box)
        commit = gui.button(box, self, "Send", callback=self.apply,
                            default=True)
        commit.setMinimumWidth(180)
Пример #30
0
    def __init__(self):
        super().__init__()

        self.corpus = None  # Corpus
        self.corpus_docs = None  # Documents generated from Corpus
        self.output_mask = []  # Output corpus indices
        self.doc_webview = None  # WebView for showing content
        self.search_features = [
        ]  # two copies are needed since Display allows drag & drop
        self.display_list_indices = [0]

        # Info attributes
        self.update_info()
        info_box = gui.widgetBox(self.controlArea, 'Info')
        gui.label(info_box, self, 'Documents: %(n_documents)s')
        gui.label(info_box, self, 'Preprocessed: %(is_preprocessed)s')
        gui.label(info_box, self, '  ◦ Tokens: %(n_tokens)s')
        gui.label(info_box, self, '  ◦ Types: %(n_types)s')
        gui.label(info_box, self, 'POS tagged: %(is_pos_tagged)s')
        gui.label(info_box, self, 'N-grams range: %(ngram_range)s')
        gui.label(info_box, self, 'Matching: %(n_matching)s')

        # Search features
        self.search_listbox = gui.listBox(
            self.controlArea,
            self,
            'search_indices',
            'search_features',
            selectionMode=QListView.ExtendedSelection,
            box='Search features',
            callback=self.search_features_changed)

        # Display features
        display_box = gui.widgetBox(self.controlArea, 'Display features')
        self.display_listbox = gui.listBox(
            display_box,
            self,
            'display_list_indices',
            'display_features',
            selectionMode=QListView.ExtendedSelection,
            callback=self.show_docs,
            enableDragDrop=True)
        self.show_tokens_checkbox = gui.checkBox(display_box,
                                                 self,
                                                 'show_tokens',
                                                 'Show Tokens && Tags',
                                                 callback=self.show_docs)

        # Auto-commit box
        gui.auto_commit(self.controlArea, self, 'autocommit', 'Send data',
                        'Auto send is on')

        # Search
        self.filter_input = gui.lineEdit(self.mainArea,
                                         self,
                                         'regexp_filter',
                                         orientation=Qt.Horizontal,
                                         sizePolicy=QSizePolicy(
                                             QSizePolicy.MinimumExpanding,
                                             QSizePolicy.Fixed),
                                         label='RegExp Filter:')
        self.filter_input.textChanged.connect(self.refresh_search)

        # Main area
        self.splitter = QSplitter(
            orientation=Qt.Horizontal,
            childrenCollapsible=False,
        )

        # Document list
        self.doc_list = QTableView()
        self.doc_list.setSelectionBehavior(QTableView.SelectRows)
        self.doc_list.setSelectionMode(QTableView.ExtendedSelection)
        self.doc_list.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.doc_list.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)
        self.doc_list.horizontalHeader().setVisible(False)
        self.splitter.addWidget(self.doc_list)

        self.doc_list_model = QStandardItemModel(self)
        self.doc_list.setModel(self.doc_list_model)
        self.doc_list.selectionModel().selectionChanged.connect(self.show_docs)

        # Document contents
        self.doc_webview = gui.WebviewWidget(self.splitter, debug=False)
        self.doc_webview.loadFinished.connect(self.highlight_docs)

        self.mainArea.layout().addWidget(self.splitter)