示例#1
1
 def keyPressEvent(self, event):  #QKeyEvent
     key = event.key()
     char = event.text() if event.text(
     ) in self.availChars else ''  #else chr(key)if (key in range(0xffff) and chr(key) in self.availChars)
     #print(event.text(),event.text() in self.availChars,char)
     backspaceKey, deleteKey = QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete
     if key in [backspaceKey, deleteKey] or char:
         pos, width = self.cursorPosition(), len(self.selectedText())
         self._realString = self._realString[:pos - (
             1 if key == backspaceKey else 0)] + char + self._realString[
                 pos - (1 if key == deleteKey else 0) + width:]
         if char:
             randChar = self.getRandChar()
             event = QtGui.QKeyEvent(
                 QtCore.QEvent(QtCore.QEvent.KeyPress).type(),
                 ord(randChar), event.modifiers(), randChar)
         if self._verifier:
             QtWidgets.QToolTip.showText(
                 self.mapToGlobal(QtCore.QPoint()),
                 '일치합니다.' if self._verifier.equals(hash(
                     self._realString)) else '일치하지 않습니다.')
         else:
             QtWidgets.QToolTip.showText(
                 self.mapToGlobal(QtCore.QPoint()),
                 ('너무 위험합니다.', '더 복잡해야 합니다.', '조금 더 복잡해야 합니다.', '안전합니다.',
                  '매우 안전합니다.')[MPManager.Instance().evalConfidence(
                      self._realString)]
             )  #str(MPManager.Instance().evalConfidence(self._realString)))
     elif key in [QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter]:
         self.login()
     super().keyPressEvent(event)
示例#2
1
 def closeEvent(self, *args, **kwargs):
     self.save_settings()
     #Enable paste of clipboard after termination
     clipboard = QtWidgets.QApplication.clipboard()
     event = QtCore.QEvent(QtCore.QEvent.Clipboard)
     QtWidgets.QApplication.sendEvent(clipboard, event)
     return QtWidgets.QMainWindow.closeEvent(self, *args, **kwargs)
示例#3
1
def _message_app(app, src_path, components_list):
    # Alert the main QThread about the change
    app._class_rerender_queue.put_nowait((src_path, components_list))
    logger.info("Detected change in %s.", src_path)
    app.app.postEvent(
        app._event_receiver,
        QtCore.QEvent(QtCore.QEvent.Type(
            app._file_change_rerender_event_type)))
    return app._class_rerender_response_queue.get()
示例#4
1
    def test_event(self):
        """
        Test the reimplemented event method
        """
        # GIVEN: A file path and a QEvent.
        file_path = os.path.join(TEST_PATH, 'church.jpg')
        mocked_file_method = MagicMock(return_value=file_path)
        event = QtCore.QEvent(QtCore.QEvent.FileOpen)
        event.file = mocked_file_method

        # WHEN: Call the vent method.
        result = self.openlp.event(event)

        # THEN: The path should be inserted.
        self.assertTrue(result, "The method should have returned True.")
        mocked_file_method.assert_called_once_with()
        self.assertEqual(self.openlp.args[0], file_path,
                         "The path should be in args.")
 def main(self):
     try:
         self.init_network()
     except UserCancelled:
         return
     except GoBack:
         return
     except:
         traceback.print_exc(file=sys.stdout)
         return
     self.timer.start()
     self.config.open_last_wallet()
     path = self.config.get_wallet_path()
     if not self.start_new_window(path, self.config.get('url')):
         return
     signal.signal(signal.SIGINT, lambda *args: self.app.quit())
     # main loop
     self.app.exec_()
     # Shut down the timer cleanly
     self.timer.stop()
     # clipboard persistence. see http://www.mail-archive.com/[email protected]/msg17328.html
     event = QtCore.QEvent(QtCore.QEvent.Clipboard)
     self.app.sendEvent(self.app.clipboard(), event)
     self.tray.hide()
示例#6
1
 def mousePressEvent(self, event):
     if event.button() == QtCore.Qt.LeftButton:
         self.dragPosition = event.globalPos() - self.frameGeometry(
         ).topLeft()
         QApplication.postEvent(self, QtCore.QEvent(174))
         event.accept()
示例#7
1
 def closeEvent(self, event):
     clipboard = QGuiApplication.clipboard()
     event = QtCore.QEvent(QtCore.QEvent.Clipboard)
     QGuiApplication.sendEvent(clipboard, event)
示例#8
0
 def clean_up():
     # Shut down the timer cleanly
     self.timer.stop()
     # clipboard persistence. see http://www.mail-archive.com/[email protected]/msg17328.html
     event = QtCore.QEvent(QtCore.QEvent.Clipboard)
     self.app.sendEvent(self.app.clipboard(), event)
     self.tray.hide()
示例#9
0
 def __init__(self):
     self.do_init = QtCore.QEvent.registerEventType()
     QtWidgets.QMainWindow.__init__(self)
     self.setWindowTitle("Camera config")
     self.setMinimumWidth(600)
     # quit shortcut
     quit_action = QtWidgets.QAction('Quit', self)
     quit_action.setShortcuts(['Ctrl+Q', 'Ctrl+W'])
     quit_action.triggered.connect(QtWidgets.qApp.closeAllWindows)
     self.addAction(quit_action)
     # main widget
     widget = QtWidgets.QWidget()
     widget.setLayout(QtWidgets.QGridLayout())
     widget.layout().setColumnStretch(0, 1)
     self.setCentralWidget(widget)
     # 'apply' button
     self.apply_button = QtWidgets.QPushButton('apply changes')
     self.apply_button.setEnabled(False)
     self.apply_button.clicked.connect(self.apply_changes)
     widget.layout().addWidget(self.apply_button, 1, 1)
     # 'cancel' button
     quit_button = QtWidgets.QPushButton('cancel')
     quit_button.clicked.connect(QtWidgets.qApp.closeAllWindows)
     widget.layout().addWidget(quit_button, 1, 2)
     # defer full initialisation (slow operation) until gui is visible
     self.camera = gp.Camera()
     QtWidgets.QApplication.postEvent(self, QtCore.QEvent(self.do_init),
                                      Qt.LowEventPriority - 1)
示例#10
0
 def on_structManager_cellPressed(self, i, j):
     #print "on_structManager_cellPressed ",  i,j
     mouse_state = QtGui.qApp.mouseButtons()
     if QtGui.qApp.mouseButtons() == QtCore.Qt.LeftButton:
         #print "on_structManager_cellPressed ", QtGui.qApp.mouseButtons()==QtCore.Qt.LeftButton, mouse_state==QtCore.Qt.NoButton
         QtGui.qApp.sendEvent(self.ui.structManager,
                              QtCore.QEvent(QtCore.QEvent.MouseButtonPress))
示例#11
0
 def _cleanup_before_exit(self):
     if self._cleaned_up:
         return
     self._cleaned_up = True
     self.app.new_window_signal.disconnect()
     self.efilter = None
     # If there are still some open windows, try to clean them up.
     for window in list(self.windows):
         window.close()
         window.clean_up()
     if self.network_dialog:
         self.network_dialog.close()
         self.network_dialog.clean_up()
         self.network_dialog = None
     self.network_updated_signal_obj = None
     if self.dash_net_dialog:
         self.dash_net_dialog.close()
         self.dash_net_dialog.clean_up()
         self.dash_net_dialog = None
     self.dash_net_sobj = None
     # Shut down the timer cleanly
     self.timer.stop()
     self.timer = None
     # clipboard persistence. see http://www.mail-archive.com/[email protected]/msg17328.html
     event = QtCore.QEvent(QtCore.QEvent.Clipboard)
     self.app.sendEvent(self.app.clipboard(), event)
     if self.tray:
         self.tray.hide()
         self.tray.deleteLater()
         self.tray = None
示例#12
0
    def __init__(self, parent = None):
        """Create a wizard or the mainwindow"""
        self._parent = parent

        super().__init__(self._parent)

        print("runner/HelperTool parent: ", self._parent, " -> self: ", self) if oPB.PRINTHIER else None

        QApplication.setAttribute(QtCore.Qt.AA_UseOpenGLES)
        self.app = QApplication(sys.argv)

        # instantiate configuration class
        confighandler.ConfigHandler(oPB.CONFIG_INI)

        # installing translators
        self.translator = Translator(self.app, "opsipackagebuilder")
        self.translator.install_translations(confighandler.ConfigHandler.cfg.language)

        # instantiate help viewer and translate it, if necessary
        self.helpviewer = Help(oPB.HLP_FILE, oPB.HLP_PREFIX)
        self.helpviewer.showHelp(oPB.HLP_DST_INDEX, False)
        event = QtCore.QEvent(QtCore.QEvent.LanguageChange)
        self.helpviewer._help.ui.changeEvent(event)

        # run main loop
        # return to os
        sys.exit(self.app.exec_())
def run(args):
    app = QtWidgets.QApplication(sys.argv)
    ex = OCShareTool(args)
    app.focusChanged.connect(ex.focus_changed)
    e = app.exec_()
    clipboard = QtWidgets.QApplication.clipboard()
    event = QtCore.QEvent(QtCore.QEvent.Clipboard)
    QtWidgets.QApplication.sendEvent(clipboard, event)
    sys.exit(e)
示例#14
0
 def _copyToClipboard(self, text_widget):
     """Copies the contents of a textbox to clipboard.
     Textbox to copy is based on the calling action name.
     """
     text = text_widget.toPlainText()
     clipboard = QtWidgets.QApplication.clipboard()
     clipboard.setText(text)
     event = QtCore.QEvent(QtCore.QEvent.Clipboard)
     QtWidgets.QApplication.sendEvent(clipboard, event)
示例#15
0
 def main(self):
     QTimer.singleShot(0, self.event_loop_started)
     self.app.exec_()
     # Shut down the timer cleanly
     self.timer.stop()
     # clipboard persistence
     # see http://www.mail-archive.com/[email protected]/msg17328.html
     event = QtCore.QEvent(QtCore.QEvent.Clipboard)
     self.app.sendEvent(self.app.clipboard(), event)
     self.tray.hide()
示例#16
0
 def clean_up():
     # Just in case we get an exception as we exit, uninstall the Exception_Hook
     Exception_Hook.uninstall()
     # Shut down the timer cleanly
     self.timer.stop()
     self.gc_timer.stop()
     # clipboard persistence. see http://www.mail-archive.com/[email protected]/msg17328.html
     event = QtCore.QEvent(QtCore.QEvent.Clipboard)
     self.app.sendEvent(self.app.clipboard(), event)
     self.tray.hide()
示例#17
0
    def quit(self):
        event = None
        if self.fostered:
            # Foster vessel's closeEvent will trigger "quit" which connected
            # to here.
            # Forward the event to window.
            event = QtCore.QEvent(QtCore.QEvent.Close)
            self.window.event(event)

        if event is None or event.isAccepted():
            super(Application, self).quit()
示例#18
0
 def _do_continuous(self):
     if not self.running:
         self._reset_config()
         return
     if self.camera_model == 'unknown':
         self._do_preview()
     else:
         self._do_capture()
     # post event to trigger next capture
     QtWidgets.QApplication.postEvent(
         self, QtCore.QEvent(self.do_next), Qt.LowEventPriority - 1)
示例#19
0
 def clean_up():
     # If there are still some open windows, try to clean them up.
     for window in list(self.windows):
         window.clean_up()
     # Shut down the timer cleanly
     self.timer.stop()
     # clipboard persistence. see http://www.mail-archive.com/[email protected]/msg17328.html
     event = QtCore.QEvent(QtCore.QEvent.Clipboard)
     self.app.sendEvent(self.app.clipboard(), event)
     if self.tray:
         self.tray.hide()
         self.tray.deleteLater()
         self.tray = None
        def on_done(f):
            assert f is future
            selfref = selfweakref()

            if selfref is None:
                return

            try:
                QtCore.QCoreApplication.postEvent(
                    selfref, QtCore.QEvent(FutureWatcher.__FutureDone))
            except RuntimeError:
                # Ignore RuntimeErrors (when C++ side of QObject is deleted)
                # (? Use QObject.destroyed and remove the done callback ?)
                pass
示例#21
0
    def test_application_activate_event(self, mocked_is_macosx):
        """
        Test that clicking on the dock icon on Mac OS X restores the main window if it is minimized
        """
        # GIVEN: Mac OS X and an ApplicationActivate event
        mocked_is_macosx.return_value = True
        event = QtCore.QEvent(QtCore.QEvent.ApplicationActivate)
        self.main_window.showMinimized()

        # WHEN: The icon in the dock is clicked
        result = self.main_window.eventFilter(MagicMock(), event)

        # THEN:
        assert result is True, "The method should have returned True."
        assert self.main_window.isMinimized() is False
    def right_click_menu(self, pos):
        """ Slot function:
        The right click menu with operation 'Copy'. 
        'Copy' is used to copy the selected item to the clipboard.
        """

        action = self.right_menu.exec_(QtGui.QCursor.pos())
        if action == self.action_copy:
            """ Case:
            Operation 'Copy'.
            """

            clipboard = QtWidgets.QApplication.clipboard()
            clipboard.setText(self.result_display.selectedItems()[0].text())
            event = QtCore.QEvent(QtCore.QEvent.Clipboard)
            QtWidgets.QApplication.sendEvent(clipboard, event)
示例#23
0
    def test_event(self):
        """
        Test the reimplemented event method
        """
        # GIVEN: A file path and a QEvent.
        file_path = str(RESOURCE_PATH / 'church.jpg')
        mocked_file_method = MagicMock(return_value=file_path)
        event = QtCore.QEvent(QtCore.QEvent.FileOpen)
        event.file = mocked_file_method

        # WHEN: Call the vent method.
        result = self.openlp.event(event)

        # THEN: The path should be inserted.
        assert result is True, "The method should have returned True."
        mocked_file_method.assert_called_once_with()
        assert self.openlp.args[0] == file_path, "The path should be in args."
示例#24
0
    def keyPressEvent(self, event):
        """ Detecting keypress events globally to setup tab selection"""
        # If tab has been pressed and the tab selections havent been setup
        if event.key() == QtCore.Qt.Key_Tab and not self.focus_enabled:
            self.focus_enabled = True
            child_count = self.grid_layout.count()
            # Set all clipboards focus policies
            for child_index in range(child_count):
                if self.grid_layout.itemAt(child_index).widget() is not None:
                    self.grid_layout.itemAt(child_index).widget().setFocusPolicy(QtCore.Qt.StrongFocus)
            # Set the focus to the first clipboard
            self.grid_layout.itemAt(0).widget().setFocus()

        # If enter is pressed and we have setup tab selection
        elif event.key() in [QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return] and self.focus_enabled:
            # Send a left click event to the currently focused widget
            event = QtCore.QEvent(QtCore.QEvent.MouseButtonPress)
            event.button = lambda: 1
            self.focusWidget().mousePressEvent(event)
    def setHoverMeasureEditor(
            self, measure_editor: Optional[BaseMeasureEditor],
            evt: Union[None, QtGui.QEnterEvent, QtGui.QMouseEvent]) -> None:
        if measure_editor is self.__hover_measure_editor:
            return

        if self.__hover_measure_editor is not None:
            measure_evt = QtCore.QEvent(QtCore.QEvent.Leave)
            self.__hover_measure_editor.leaveEvent(measure_evt)

        if measure_editor is not None:
            measure_evt = QtGui.QEnterEvent(
                evt.localPos() - measure_editor.topLeft(), evt.windowPos(),
                evt.screenPos())
            measure_editor.enterEvent(measure_evt)

        self.__hover_measure_editor = measure_editor
        self.hoveredMeasureChanged.emit(
            measure_editor.measure_reference.measure.id if self.isCurrent()
            and isinstance(measure_editor, MeasureEditor) else 0)
示例#26
0
    def run_app(self) -> None:
        when_started = datetime.datetime.now().astimezone().isoformat()
        app_state.config.set_key('previous_start_time', app_state.config.get("start_time"))
        app_state.config.set_key('start_time', when_started, True)
        self.update_check()

        threading.current_thread().setName('GUI')
        self.timer.setSingleShot(False)
        self.timer.setInterval(500)  # msec
        self.timer.timeout.connect(app_state.device_manager.timeout_clients)

        QTimer.singleShot(0, self.event_loop_started)
        self.exec_()

        logs.remove_handler(self.log_handler)
        # Shut down the timer cleanly
        self.timer.stop()
        # clipboard persistence
        # see http://www.mail-archive.com/[email protected]/msg17328.html
        event = QtCore.QEvent(QtCore.QEvent.Clipboard)
        self.sendEvent(self.clipboard(), event)
        self.tray.hide()
示例#27
0
    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.ChildAdded:
            logger.debug("%s: ChildAdded(%s)", obj, event.child())
            self._monitorObject(event.child())
        elif event.type() == QtCore.QEvent.ChildRemoved:
            logger.debug("%s: ChildRemoved(%s)", obj, event.child())
            self._unmonitorObject(event.child())
        elif event.type() == QtCore.QEvent.Paint:
            logger.debug("%s: Paint(%s)", obj, event.rect())
            if not self.in_render:
                region = event.region()
                region.translate(obj.mapTo(self.widget, QtCore.QPoint(0, 0)))
                self.dirty_region |= region
                QtCore.QCoreApplication.postEvent(self,
                                                  QtCore.QEvent(self.Render))
                return True
        else:
            logger.debug(
                "%s: %s", obj,
                event_names.get(
                    event.type(),
                    '%s(%d)' % (type(event).__name__, event.type())))

        return super().eventFilter(obj, event)
示例#28
0
    def openImage(self, path):
        if not path:
            return

        # close current image
        e = QtCore.QEvent(QtCore.QEvent.None_)
        self.closeEvent(e)
        if not e.isAccepted():
            return

        # read image
        matrix = cv2.imread(path, 0)
        if matrix is None:
            print("Could not open file or file is not an image.")
            return

        self.history = [{'matrix': matrix, 'histogram': None, 'saved': True}]
        self.historyIndex = 0

        layout = self.centralwidget.layout()
        # clean layout
        for i in reversed(range(layout.count())):
            item = layout.itemAt(i)
            widget = item.widget()
            if widget is None:
                layout.removeItem(item)
            else:
                widget.deleteLater()
            del item

        # show image
        self.scrollArea = QtWidgets.QScrollArea()
        self.imageLabel = ImageLabel(scrollArea=self.scrollArea)
        self.imageLabel.setBackgroundRole(QtGui.QPalette.Base)
        self.imageLabel.setSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored)
        self.imageLabel.setScaledContents(True)

        self.scrollArea.setAlignment(QtCore.Qt.AlignCenter)
        self.scrollArea.setWidget(self.imageLabel)
        layout.addWidget(self.scrollArea)
        layout.setContentsMargins(0, 0, 0, 0)

        self.zoom = 1
        self.updateImage(matrix)

        # adjust window's size
        height, width = matrix.shape
        adjustWindowSize(self.window, width + 2, height + 2)

        # center window
        geom = desktopGeometry()
        x = geom.x() + 0.5 * (geom.width() - self.window.frameSize().width())
        y = geom.y() + 0.5 * (geom.height() - self.window.frameSize().height())
        self.window.move(x, y)

        # create histogram window
        if self.windowHist is None or self.windowHist.isClosed():
            if self.windowHist is not None:
                del self.windowHist
            self.windowHist = WindowHistogram(self.window)
            self.windowHist.show()

        hist = [Histogram.hist(matrix)]
        legend = ["Source Image"]
        self.history[0]['histogram'] = {'plots': hist, 'legend': legend}

        self.windowHist.setHistogram(hist, legend)
        self.windowHist.adjustWindowSize()
        self.windowHist.adjustWindowPosition()

        self.window.activateWindow()
        self.window.setFocus()

        # enable _Save, Edit, View+, Transform+ and _Histogram
        self.actionSave.setEnabled(True)
        self.menuEdit.setEnabled(True)
        for a in self.menuView.actions():
            a.setEnabled(True)
        self.menuView.setEnabled(True)
        for a in self.menuTransform.actions():
            a.setEnabled(True)
        self.menuTransform.setEnabled(True)
        self.window.actionHistogram.setEnabled(True)
示例#29
0
 def renderLater(self):
     if not self.m_update_pending:
         self.m_update_pending = True
         QtGui.QGuiApplication.postEvent(
             self, QtCore.QEvent(QtCore.QEvent.UpdateRequest))
示例#30
-1
 def onItemAdded(self, _, item):
     """
     Executed whenever a connection is created/removed.
     :type _: Diagram
     :type item: AbstractItem
     """
     # Send a font change event to the item to update its font
     self.sendEvent(item, QtCore.QEvent(QtCore.QEvent.FontChange))
     if item.isEdge():
         # Execute the node identification procedure only if one of the
         # endpoints we are connecting is currently identified as NEUTRAL.
         if (item.source.identity() is Identity.Neutral) ^ (
                 item.target.identity() is Identity.Neutral):
             for node in (item.source, item.target):
                 self.sgnNodeIdentification.emit(node)