def test_quick_help_events(self): w = self.w help: QuickHelp = w.dock_help html = "<h3>HELLO</h3>" ev = QuickHelpTipEvent("", html, priority=QuickHelpTipEvent.Normal) QApplication.sendEvent(w, ev) self.assertEqual(help.currentText(), "<h3>HELLO</h3>")
def mouse_release(widget, pos, mouse_button=Qt.LeftButton): if isinstance(widget, QGraphicsView): widget = widget.viewport() event = QMouseEvent(QEvent.MouseButtonRelease, pos, mouse_button, Qt.NoButton, Qt.NoModifier) QApplication.sendEvent(widget, event)
def mouse_move(widget, pos, buttons=Qt.NoButton): if isinstance(widget, QGraphicsView): widget = widget.viewport() event = QMouseEvent(QEvent.MouseMove, pos, Qt.NoButton, buttons, Qt.NoModifier) QApplication.sendEvent(widget, event)
def mouseMove(widget, pos=QPoint(), delay=-1): # pragma: no-cover # Like QTest.mouseMove, but functional without QCursor.setPos if pos.isNull(): pos = widget.rect().center() me = QMouseEvent(QMouseEvent.MouseMove, pos, widget.mapToGlobal(pos), Qt.NoButton, Qt.MouseButtons(0), Qt.NoModifier) if delay > 0: QTest.qWait(delay) QApplication.sendEvent(widget, me)
def mouseMove(widget, pos=QPoint(), delay=-1): # pragma: no-cover # Like QTest.mouseMove, but functional without QCursor.setPos if pos.isNull(): pos = widget.rect().center() me = QMouseEvent(QMouseEvent.MouseMove, pos, widget.mapToGlobal(pos), Qt.NoButton, Qt.MouseButtons(0), Qt.NoModifier) if delay > 0: QTest.qWait(delay) QApplication.sendEvent(widget, me)
def qWheelScroll( widget: QWidget, buttons=Qt.NoButton, modifiers=Qt.NoModifier, pos=QPoint(), angleDelta=QPoint(0, 1), ): if pos.isNull(): pos = widget.rect().center() globalPos = widget.mapToGlobal(pos) event = QWheelEvent(QPointF(pos), QPointF(globalPos), QPoint(), angleDelta, buttons, modifiers, Qt.NoScrollPhase, False) QApplication.sendEvent(widget, event)
def test_button(self): # Run through various state change and drawing code for coverage b = buttons.SimpleButton() b.setIcon(b.style().standardIcon(QStyle.SP_ComputerIcon)) QApplication.sendEvent(b, QFocusEvent(QFocusEvent.FocusIn)) QApplication.sendEvent(b, QFocusEvent(QFocusEvent.FocusOut)) b.grab() b.setDown(True) b.grab() b.setCheckable(True) b.setChecked(True) b.grab()
def dragDrop(widget: QWidget, mime: QMimeData, pos: QPoint = QPoint(), action=Qt.CopyAction, buttons=Qt.LeftButton, modifiers=Qt.NoModifier) -> bool: """ Simulate a drag/drop interaction on the `widget`. A `QDragEnterEvent`, `QDragMoveEvent` and `QDropEvent` are created and dispatched to the `widget`. However if any of the `QDragEnterEvent` or `QDragMoveEvent` are not accepted, a `QDragLeaveEvent` is dispatched to 'reset' the widget state before this function returns `False` Parameters ---------- widget: QWidget The target widget. mime: QMimeData The mime data associated with the drag/drop. pos: QPoint Position of the drop action: Qt.DropActions Type of acceptable drop actions buttons: Qt.MouseButtons: Pressed mouse buttons. modifiers: Qt.KeyboardModifiers Pressed keyboard modifiers. Returns ------- state: bool Were the events accepted. See Also -------- QDragEnterEvent, QDropEvent """ if pos.isNull(): pos = widget.rect().center() ev = QDragEnterEvent(pos, action, mime, buttons, modifiers) ev.setAccepted(False) QApplication.sendEvent(widget, ev) ev = QDragMoveEvent(pos, action, mime, buttons, modifiers) ev.setAccepted(False) QApplication.sendEvent(widget, ev) if not ev.isAccepted(): QApplication.sendEvent(widget, QDragLeaveEvent()) return False ev = QDropEvent(QPointF(pos), action, mime, buttons, modifiers) ev.setAccepted(False) QApplication.sendEvent(widget, ev) return ev.isAccepted()
def contextMenu( widget: QWidget, pos=QPoint(), reason=QContextMenuEvent.Mouse, modifiers=Qt.NoModifier, delay=-1 ) -> None: """ Simulate a context menu event on `widget`. `pos` is the event origin specified in widget's local coordinates. If not specified. Then widget.rect().center() is used instead. """ if pos.isNull(): pos = widget.rect().center() globalPos = widget.mapToGlobal(pos) ev = QContextMenuEvent(reason, pos, globalPos, modifiers) if delay >= 0: QTest.qWait(delay) QApplication.sendEvent(widget, ev)
def test_tool_tips(self): scene = GraphicsScene() view = QGraphicsView(scene) w = TextListWidget() text = "A" * 10 w.setItems([text, text]) scene.addItem(w) view.grab() # ensure w is laid out wrect = view.mapFromScene(w.mapToScene( w.contentsRect())).boundingRect() p = QPoint(wrect.topLeft() + QPoint(5, 5)) ev = QHelpEvent(QHelpEvent.ToolTip, p, view.viewport().mapToGlobal(p)) try: QApplication.sendEvent(view.viewport(), ev) self.assertEqual(QToolTip.text(), text) finally: QToolTip.hideText()
def dragDrop(widget: 'QWidget', mime: QMimeData, pos: QPoint = QPoint(-1, -1), action=Qt.CopyAction, buttons=Qt.LeftButton, modifiers=Qt.NoModifier) -> bool: if pos == QPoint(-1, -1): pos = widget.rect().center() ev = QDragEnterEvent(pos, action, mime, buttons, modifiers) ev.setAccepted(False) QApplication.sendEvent(widget, ev) if not ev.isAccepted(): return False ev = QDropEvent(QPointF(pos), action, mime, buttons, modifiers) ev.setAccepted(False) QApplication.sendEvent(widget, ev) return ev.isAccepted()
def test_save_geometry(self): workflow = self.scheme nodes = workflow.nodes wm = TestingWidgetManager() wm.set_workflow(workflow) n = nodes[0] w = wm.widget_for_node(n) state = wm.save_widget_geometry(n, w) self.assertTrue(wm.restore_widget_geometry(n, w, state)) wm.activate_widget_for_node(n, w) state = wm.save_window_state() self.assertEqual(len(state), 1) self.assertIs(state[0][0], n) self.assertEqual(state[0][1], wm.save_widget_geometry(n, w)) QApplication.sendEvent( nodes[1], NodeEvent(NodeEvent.NodeActivateRequest, nodes[1])) wm.raise_widgets_to_front() wm.restore_window_state(state)
def qWheelScroll( widget: QWidget, buttons=Qt.NoButton, modifiers=Qt.NoModifier, pos=QPoint(), angleDelta=QPoint(0, 1), ): if pos.isNull(): pos = widget.rect().center() globalPos = widget.mapToGlobal(pos) if angleDelta.y() >= angleDelta.x(): qt4orient = Qt.Vertical qt4delta = angleDelta.y() else: qt4orient = Qt.Horizontal qt4delta = angleDelta.x() event = QWheelEvent(QPointF(pos), QPointF(globalPos), QPoint(), angleDelta, qt4delta, qt4orient, buttons, modifiers) QApplication.sendEvent(widget, event)
def test_drop(self): widget = self.widget with tempfile.TemporaryDirectory() as tmpdir: urlpath = QUrl.fromLocalFile(tmpdir) data = QMimeData() data.setUrls([urlpath]) pos = widget.recent_cb.rect().center() actions = Qt.LinkAction | Qt.CopyAction ev = QDragEnterEvent(pos, actions, data, Qt.LeftButton, Qt.NoModifier) assert QApplication.sendEvent(widget.recent_cb, ev) self.assertTrue(ev.isAccepted()) del ev ev = QDropEvent(pos, actions, data, Qt.LeftButton, Qt.NoModifier, QDropEvent.Drop) assert QApplication.sendEvent(widget.recent_cb, ev) self.assertTrue(ev.isAccepted()) del ev self.assertEqual(widget.currentPath, urlpath.toLocalFile()) self._startandwait(widget) self.widget.commit()
def dragEnterLeave(widget: QWidget, mime: QMimeData, pos=QPoint(), action=Qt.CopyAction, buttons=Qt.LeftButton, modifiers=Qt.NoModifier) -> None: """ Simulate a drag/move/leave interaction on the `widget`. A QDragEnterEvent, QDragMoveEvent and a QDragLeaveEvent are created and dispatched to the widget. """ if pos.isNull(): pos = widget.rect().center() ev = QDragEnterEvent(pos, action, mime, buttons, modifiers) ev.setAccepted(False) QApplication.sendEvent(widget, ev) ev = QDragMoveEvent(pos, action, mime, buttons, modifiers, QDragMoveEvent.DragMove) ev.setAccepted(False) QApplication.sendEvent(widget, ev) ev = QDragLeaveEvent() ev.setAccepted(False) QApplication.sendEvent(widget, ev) return
def test_drop(self): widget = self.widget with tempfile.TemporaryDirectory() as tmpdir: urlpath = QUrl.fromLocalFile(tmpdir) data = QMimeData() data.setUrls([urlpath]) pos = widget.recent_cb.rect().center() actions = Qt.LinkAction | Qt.CopyAction ev = QDragEnterEvent(pos, actions, data, Qt.LeftButton, Qt.NoModifier) assert QApplication.sendEvent(widget.recent_cb, ev) self.assertTrue(ev.isAccepted()) del ev ev = QDropEvent(pos, actions, data, Qt.LeftButton, Qt.NoModifier, QDropEvent.Drop) assert QApplication.sendEvent(widget.recent_cb, ev) self.assertTrue(ev.isAccepted()) del ev self.assertEqual(widget.recent_paths[0].abspath, urlpath.toLocalFile()) self._startandwait(widget) self.widget.commit()
def test_help_requests(self): w = self.w ev = QWhatsThisClickedEvent('help://search?id=one') QApplication.sendEvent(w, ev)
def showPopup(self): # type: () -> None """ Reimplemented from QComboBox.showPopup Popup up a customized view and filter edit line. Note ---- The .popup(), .lineEdit(), .completer() of the base class are not used. """ if self.__popup is not None: # We have user entered state that cannot be disturbed # (entered filter text, scroll offset, ...) return # pragma: no cover if self.count() == 0: return opt = QStyleOptionComboBox() self.initStyleOption(opt) popup = QListView( uniformItemSizes=True, horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff, verticalScrollBarPolicy=Qt.ScrollBarAsNeeded, iconSize=self.iconSize(), ) popup.setFocusProxy(self.__searchline) popup.setParent(self, Qt.Popup | Qt.FramelessWindowHint) popup.setItemDelegate(_ComboBoxListDelegate(popup)) proxy = QSortFilterProxyModel( popup, filterCaseSensitivity=Qt.CaseInsensitive ) proxy.setFilterKeyColumn(self.modelColumn()) proxy.setSourceModel(self.model()) popup.setModel(proxy) root = proxy.mapFromSource(self.rootModelIndex()) popup.setRootIndex(root) self.__popup = popup self.__proxy = proxy self.__searchline.setText("") self.__searchline.setPlaceholderText("Filter...") self.__searchline.setVisible(True) self.__searchline.textEdited.connect(proxy.setFilterFixedString) style = self.style() # type: QStyle popuprect_origin = style.subControlRect( QStyle.CC_ComboBox, opt, QStyle.SC_ComboBoxListBoxPopup, self ) # type: QRect popuprect_origin = QRect( self.mapToGlobal(popuprect_origin.topLeft()), popuprect_origin.size() ) editrect = style.subControlRect( QStyle.CC_ComboBox, opt, QStyle.SC_ComboBoxEditField, self ) # type: QRect self.__searchline.setGeometry(editrect) desktop = QApplication.desktop() screenrect = desktop.availableGeometry(self) # type: QRect # get the height for the view listrect = QRect() for i in range(min(proxy.rowCount(root), self.maxVisibleItems())): index = proxy.index(i, self.modelColumn(), root) if index.isValid(): listrect = listrect.united(popup.visualRect(index)) if listrect.height() >= screenrect.height(): break window = popup.window() # type: QWidget window.ensurePolished() if window.layout() is not None: window.layout().activate() else: QApplication.sendEvent(window, QEvent(QEvent.LayoutRequest)) margins = qwidget_margin_within(popup.viewport(), window) height = (listrect.height() + 2 * popup.spacing() + margins.top() + margins.bottom()) popup_size = (QSize(popuprect_origin.width(), height) .expandedTo(window.minimumSize()) .boundedTo(window.maximumSize()) .boundedTo(screenrect.size())) popuprect = QRect(popuprect_origin.bottomLeft(), popup_size) popuprect = dropdown_popup_geometry( popuprect, popuprect_origin, screenrect) popup.setGeometry(popuprect) current = proxy.mapFromSource( self.model().index(self.currentIndex(), self.modelColumn(), self.rootModelIndex())) popup.setCurrentIndex(current) popup.scrollTo(current, QAbstractItemView.EnsureVisible) popup.show() popup.setFocus(Qt.PopupFocusReason) popup.installEventFilter(self) popup.viewport().installEventFilter(self) popup.viewport().setMouseTracking(True) self.update() self.__popupTimer.restart()
def main(argv=None): app = QApplication(list(argv) if argv else []) argv = app.arguments() parser = argparse.ArgumentParser(description=( "Run an orange workflow without showing a GUI and exit " "when it completes.\n\n" "WARNING: This is experimental as Orange is not designed to run " "non-interactive.")) parser.add_argument("--log-level", "-l", metavar="LEVEL", type=int, default=logging.CRITICAL, dest="log_level") parser.add_argument("--config", default="Orange.canvas.config.Config", type=str) parser.add_argument("file") args = parser.parse_args(argv[1:]) log_level = args.log_level filename = args.file logging.basicConfig(level=log_level) cfg_class = utils.name_lookup(args.config) cfg: config.Config = cfg_class() config.set_default(cfg) config.init() reg = WidgetRegistry() widget_discovery = cfg.widget_discovery( reg, cached_descriptions=cache.registry_cache()) widget_discovery.run(cfg.widgets_entry_points()) model = cfg.workflow_constructor() model.set_runtime_env("basedir", os.path.abspath(os.path.dirname(filename))) sigprop = model.findChild(signalmanager.SignalManager) sigprop.pause() # Pause signal propagation during load with open(filename, "rb") as f: model.load_from(f, registry=reg) # Ensure all widgets are created (this is required for the workflow # to even start - relies to much on OWWidget behaviour). for _ in map(model.widget_for_node, model.nodes): pass sigprop.resume() # Resume inter-widget signal propagation def on_finished(): severity = 0 for node in model.nodes: for msg in node.state_messages(): if msg.contents and msg.severity == msg.Error: print(msg.contents, msg.message_id, file=sys.stderr) severity = msg.Error if severity == UserMessage.Error: app.exit(1) else: app.exit() sigprop.finished.connect(on_finished) rval = app.exec_() model.clear() # Notify the workflow model to 'close'. QApplication.sendEvent(model, QEvent(QEvent.Close)) app.processEvents() return rval
def showPopup(self): # type: () -> None """ Reimplemented from QComboBox.showPopup Popup up a customized view and filter edit line. Note ---- The .popup(), .lineEdit(), .completer() of the base class are not used. """ if self.__popup is not None: # We have user entered state that cannot be disturbed # (entered filter text, scroll offset, ...) return # pragma: no cover if self.count() == 0: return opt = QStyleOptionComboBox() self.initStyleOption(opt) popup = QListView( uniformItemSizes=True, horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff, verticalScrollBarPolicy=Qt.ScrollBarAsNeeded, iconSize=self.iconSize(), ) popup.setFocusProxy(self.__searchline) popup.setParent(self, Qt.Popup | Qt.FramelessWindowHint) popup.setItemDelegate(_ComboBoxListDelegate(popup)) proxy = QSortFilterProxyModel( popup, filterCaseSensitivity=Qt.CaseInsensitive ) proxy.setFilterKeyColumn(self.modelColumn()) proxy.setSourceModel(self.model()) popup.setModel(proxy) root = proxy.mapFromSource(self.rootModelIndex()) popup.setRootIndex(root) self.__popup = popup self.__proxy = proxy self.__searchline.setText("") self.__searchline.setPlaceholderText("Filter...") self.__searchline.setVisible(True) self.__searchline.textEdited.connect(proxy.setFilterFixedString) style = self.style() # type: QStyle popuprect_origin = style.subControlRect( QStyle.CC_ComboBox, opt, QStyle.SC_ComboBoxListBoxPopup, self ) # type: QRect popuprect_origin = QRect( self.mapToGlobal(popuprect_origin.topLeft()), popuprect_origin.size() ) editrect = style.subControlRect( QStyle.CC_ComboBox, opt, QStyle.SC_ComboBoxEditField, self ) # type: QRect self.__searchline.setGeometry(editrect) desktop = QApplication.desktop() screenrect = desktop.availableGeometry(self) # type: QRect # get the height for the view listrect = QRect() for i in range(min(proxy.rowCount(root), self.maxVisibleItems())): index = proxy.index(i, self.modelColumn(), root) if index.isValid(): listrect = listrect.united(popup.visualRect(index)) if listrect.height() >= screenrect.height(): break window = popup.window() # type: QWidget window.ensurePolished() if window.layout() is not None: window.layout().activate() else: QApplication.sendEvent(window, QEvent(QEvent.LayoutRequest)) margins = qwidget_margin_within(popup.viewport(), window) height = (listrect.height() + 2 * popup.spacing() + margins.top() + margins.bottom()) popup_size = (QSize(popuprect_origin.width(), height) .expandedTo(window.minimumSize()) .boundedTo(window.maximumSize()) .boundedTo(screenrect.size())) popuprect = QRect(popuprect_origin.bottomLeft(), popup_size) popuprect = dropdown_popup_geometry( popuprect, popuprect_origin, screenrect) popup.setGeometry(popuprect) current = proxy.mapFromSource( self.model().index(self.currentIndex(), self.modelColumn(), self.rootModelIndex())) popup.setCurrentIndex(current) popup.scrollTo(current, QAbstractItemView.EnsureVisible) popup.show() popup.setFocus(Qt.PopupFocusReason) popup.installEventFilter(self) popup.viewport().installEventFilter(self) popup.viewport().setMouseTracking(True) self.update() self.__popupTimer.restart()
def setPalette(self, palette): # type: (QPalette) -> None if self.__palette != palette: self.__palette = QPalette(palette) QApplication.sendEvent(self, QEvent(QEvent.PaletteChange))