Python源码示例:PyQt5.QtGui.QKeyEvent()

示例1
def keyPressEvent(self, e: QKeyEvent) -> None:
        """Override keyPressEvent to ignore Return key presses.

        If this widget is focused, we are in passthrough key mode, and
        Enter/Shift+Enter/etc. will cause QLineEdit to think it's finished
        without command_accept to be called.
        """
        text = self.text()
        if text in modeparsers.STARTCHARS and e.key() == Qt.Key_Backspace:
            e.accept()
            modeman.leave(self._win_id, usertypes.KeyMode.command,
                          'prefix deleted')
            return
        if e.key() == Qt.Key_Return:
            e.ignore()
            return
        else:
            super().keyPressEvent(e) 
示例2
def event(self, e):
        if not isinstance(e, (
                QtCore.QEvent,
                QtCore.QChildEvent,
                QtCore.QDynamicPropertyChangeEvent,
                QtGui.QPaintEvent,
                QtGui.QHoverEvent,
                QtGui.QMoveEvent,
                QtGui.QEnterEvent,
                QtGui.QResizeEvent,
                QtGui.QShowEvent,
                QtGui.QPlatformSurfaceEvent,
                QtGui.QWindowStateChangeEvent,
                QtGui.QKeyEvent,
                QtGui.QWheelEvent,
                QtGui.QMouseEvent,
                QtGui.QFocusEvent,
                QtGui.QHelpEvent,
                QtGui.QHideEvent,
                QtGui.QCloseEvent,
                QtGui.QInputMethodQueryEvent,
                QtGui.QContextMenuEvent,
                )):
            log().warning("unknown event: %r %r", e.type(), e)
        return super().event(e) 
示例3
def _remap_unicode(key: Qt.Key, text: str) -> Qt.Key:
    """Work around QtKeyEvent's bad values for high codepoints.

    QKeyEvent handles higher unicode codepoints poorly. It uses UTF-16 to
    handle key events, and for higher codepoints that require UTF-16 surrogates
    (e.g. emoji and some CJK characters), it sets the keycode to just the upper
    half of the surrogate, which renders it useless, and breaks UTF-8 encoding,
    causing crashes. So we detect this case, and reassign the key code to be
    the full Unicode codepoint, which we can recover from the text() property,
    which has the full character.

    This is a WORKAROUND for https://bugreports.qt.io/browse/QTBUG-72776.
    """
    _assert_plain_key(key)
    if _is_surrogate(key):
        if len(text) != 1:
            raise KeyParseError(text, "Expected 1 character for surrogate, "
                                "but got {}!".format(len(text)))
        return Qt.Key(ord(text[0]))
    return key 
示例4
def _handle_key_event(self, event: QKeyEvent) -> bool:
        """Handle a key press/release event.

        Args:
            event: The QEvent which is about to be delivered.

        Return:
            True if the event should be filtered, False if it's passed through.
        """
        active_window = QApplication.instance().activeWindow()
        if active_window not in objreg.window_registry.values():
            # Some other window (print dialog, etc.) is focused so we pass the
            # event through.
            return False
        try:
            man = modeman.instance('current')
            return man.handle_event(event)
        except objreg.RegistryUnavailableError:
            # No window available yet, or not a MainWindow
            return False 
示例5
def handle(self, e: QKeyEvent, *,
               dry_run: bool = False) -> QKeySequence.SequenceMatch:
        """Override to abort if the key is a startchar."""
        txt = e.text().strip()
        if self._inhibited:
            self._debug_log("Ignoring key '{}', because the normal mode is "
                            "currently inhibited.".format(txt))
            return QKeySequence.NoMatch

        match = super().handle(e, dry_run=dry_run)

        if match == QKeySequence.PartialMatch and not dry_run:
            timeout = config.val.input.partial_timeout
            if timeout != 0:
                self._partial_timer.setInterval(timeout)
                self._partial_timer.start()
        return match 
示例6
def _handle_keyrelease(self, event: QKeyEvent) -> bool:
        """Handle filtering of KeyRelease events.

        Args:
            event: The KeyPress to examine.

        Return:
            True if event should be filtered, False otherwise.
        """
        # handle like matching KeyPress
        keyevent = KeyEvent.from_event(event)
        if keyevent in self._releaseevents_to_pass:
            self._releaseevents_to_pass.remove(keyevent)
            filter_this = False
        else:
            filter_this = True
        if self.mode != usertypes.KeyMode.insert:
            log.modes.debug("filter: {}".format(filter_this))
        return filter_this 
示例7
def open_menu(self, position):

        item = self.itemAt(position)
        if item is None:
            return

        menu = QtWidgets.QMenu()
        menu.addAction(self.tr("Delete (Del)"))

        action = menu.exec_(self.viewport().mapToGlobal(position))

        if action is None:
            return

        if action.text() == "Delete (Del)":
            event = QtGui.QKeyEvent(
                QtCore.QEvent.KeyPress, QtCore.Qt.Key_Delete, QtCore.Qt.NoModifier,
            )
            self.keyPressEvent(event) 
示例8
def set_cursor(self, widget, pos):
        if self._cursor_source is None:
            self._cursor_source = widget
            for mdi in self.mdi_area.subWindowList():
                wid = mdi.widget()
                if isinstance(wid, Plot) and wid is not widget:
                    if wid.plot.cursor1 is None:
                        event = QtGui.QKeyEvent(
                            QtCore.QEvent.KeyPress,
                            QtCore.Qt.Key_C,
                            QtCore.Qt.NoModifier,
                        )
                        wid.plot.keyPressEvent(event)
                    wid.plot.cursor1.setPos(pos)
                elif isinstance(wid, Numeric) and wid is not widget:
                    wid.timestamp.setValue(pos)
            self._cursor_source = None 
示例9
def fake_key_press(self,
                       key: Qt.Key,
                       modifier: Qt.KeyboardModifier = Qt.NoModifier) -> None:
        """Send a fake key event to this tab."""
        press_evt = QKeyEvent(QEvent.KeyPress, key, modifier, 0, 0, 0)
        release_evt = QKeyEvent(QEvent.KeyRelease, key, modifier,
                                0, 0, 0)
        self.send_event(press_evt)
        self.send_event(release_evt) 
示例10
def from_event(cls, e: QKeyEvent) -> 'KeyInfo':
        """Get a KeyInfo object from a QKeyEvent.

        This makes sure that key/modifiers are never mixed and also remaps
        UTF-16 surrogates to work around QTBUG-72776.
        """
        key = _remap_unicode(Qt.Key(e.key()), e.text())
        modifiers = e.modifiers()
        _assert_plain_key(key)
        _assert_plain_modifier(modifiers)
        return cls(key, typing.cast(Qt.KeyboardModifier, modifiers)) 
示例11
def to_event(self, typ: QEvent.Type = QEvent.KeyPress) -> QKeyEvent:
        """Get a QKeyEvent from this KeyInfo."""
        return QKeyEvent(typ, self.key, self.modifiers, self.text()) 
示例12
def eventFilter(self, obj: QObject, event: QEvent) -> bool:
        """Handle an event.

        Args:
            obj: The object which will get the event.
            event: The QEvent which is about to be delivered.

        Return:
            True if the event should be filtered, False if it's passed through.
        """
        if not isinstance(obj, QWindow):
            # We already handled this same event at some point earlier, so
            # we're not interested in it anymore.
            return False

        typ = event.type()

        if typ not in self._handlers:
            return False

        if not self._activated:
            return False

        handler = self._handlers[typ]
        try:
            return handler(typing.cast(QKeyEvent, event))
        except:
            # If there is an exception in here and we leave the eventfilter
            # activated, we'll get an infinite loop and a stack overflow.
            self._activated = False
            raise 
示例13
def _handle_filter_key(self, e: QKeyEvent) -> QKeySequence.SequenceMatch:
        """Handle keys for string filtering."""
        log.keyboard.debug("Got filter key 0x{:x} text {}".format(
            e.key(), e.text()))
        if e.key() == Qt.Key_Backspace:
            log.keyboard.debug("Got backspace, mode {}, filtertext '{}', "
                               "sequence '{}'".format(self._last_press,
                                                      self._filtertext,
                                                      self._sequence))
            if self._last_press != LastPress.keystring and self._filtertext:
                self._filtertext = self._filtertext[:-1]
                self._hintmanager.filter_hints(self._filtertext)
                return QKeySequence.ExactMatch
            elif self._last_press == LastPress.keystring and self._sequence:
                self._sequence = self._sequence[:-1]
                self.keystring_updated.emit(str(self._sequence))
                if not self._sequence and self._filtertext:
                    # Switch back to hint filtering mode (this can happen only
                    # in numeric mode after the number has been deleted).
                    self._hintmanager.filter_hints(self._filtertext)
                    self._last_press = LastPress.filtertext
                return QKeySequence.ExactMatch
            else:
                return QKeySequence.NoMatch
        elif self._hintmanager.current_mode() != 'number':
            return QKeySequence.NoMatch
        elif not e.text():
            return QKeySequence.NoMatch
        else:
            self._filtertext += e.text()
            self._hintmanager.filter_hints(self._filtertext)
            self._last_press = LastPress.filtertext
            return QKeySequence.ExactMatch 
示例14
def handle(self, e: QKeyEvent, *,
               dry_run: bool = False) -> QKeySequence.SequenceMatch:
        """Handle a new keypress and call the respective handlers."""
        if dry_run:
            return super().handle(e, dry_run=True)

        assert not dry_run

        if (self._command_parser.handle(e, dry_run=True) !=
                QKeySequence.NoMatch):
            log.keyboard.debug("Handling key via command parser")
            self.clear_keystring()
            return self._command_parser.handle(e)

        match = super().handle(e)

        if match == QKeySequence.PartialMatch:
            self._last_press = LastPress.keystring
        elif match == QKeySequence.ExactMatch:
            self._last_press = LastPress.none
        elif match == QKeySequence.NoMatch:
            # We couldn't find a keychain so we check if it's a special key.
            return self._handle_filter_key(e)
        else:
            raise ValueError("Got invalid match type {}!".format(match))

        return match 
示例15
def handle_event(self, event: QEvent) -> bool:
        """Filter all events based on the currently set mode.

        Also calls the real keypress handler.

        Args:
            event: The KeyPress to examine.

        Return:
            True if event should be filtered, False otherwise.
        """
        handlers = {
            QEvent.KeyPress: self._handle_keypress,
            QEvent.KeyRelease: self._handle_keyrelease,
            QEvent.ShortcutOverride:
                functools.partial(self._handle_keypress, dry_run=True),
        }  # type: Mapping[QEvent.Type, Callable[[QKeyEvent], bool]]
        handler = handlers[event.type()]
        return handler(cast(QKeyEvent, event)) 
示例16
def keyPressEvent(self, event: QKeyEvent) -> None:
        if event.key() in {Qt.Key_F, Qt.Key_Escape}:
            event.accept()
            if self.parent is None:
                self.originalParent.toggleFullscreen()
            else:
                self.parent.toggleFullscreen()
        elif self.isFullScreen():
            self.originalParent.keyPressEvent(event)
        else:
            super(mpvWidget, self).keyPressEvent(event) 
示例17
def keyPressEvent(self, event: QKeyEvent) -> None:
        qApp.sendEvent(self.parent, event)

    # def mouseMoveEvent(self, event: QMouseEvent) -> None:
    #     opt = QStyleOptionSlider()
    #     self.initStyleOption(opt)
    #     handle = self.style().subControlRect(QStyle.CC_Slider, opt, QStyle.SC_SliderHandle, self)
    #     if handle.x() <= event.pos().x() <= (handle.x() + handle.width()):
    #         self.setCursor(Qt.PointingHandCursor)
    #         self._handleHover = True
    #     else:
    #         self.unsetCursor()
    #         self._handleHover = False
    #     self.initStyle()
    #     super(VideoSlider, self).mouseMoveEvent(event) 
示例18
def keyPressEvent(self, a0: QtGui.QKeyEvent) -> None:
        if a0.type() == QtCore.QEvent.KeyPress:
            if a0.key() == QtCore.Qt.Key_Up and self.nextFrequency != -1:
                a0.accept()
                self.setText(str(self.nextFrequency))
                self.textEdited.emit(self.text())
                return
            if a0.key() == QtCore.Qt.Key_Down and self.previousFrequency != -1:
                a0.accept()
                self.setText(str(self.previousFrequency))
                self.textEdited.emit(self.text())
                return
        super().keyPressEvent(a0) 
示例19
def keyPressEvent(self, a0: QtGui.QKeyEvent) -> None:
        m = self.getActiveMarker()
        if m is not None and a0.modifiers() == QtCore.Qt.NoModifier:
            if a0.key() == QtCore.Qt.Key_Down or a0.key() == QtCore.Qt.Key_Left:
                m.frequencyInput.keyPressEvent(QtGui.QKeyEvent(
                    a0.type(), QtCore.Qt.Key_Down, a0.modifiers()))
            elif a0.key() == QtCore.Qt.Key_Up or a0.key() == QtCore.Qt.Key_Right:
                m.frequencyInput.keyPressEvent(QtGui.QKeyEvent(
                    a0.type(), QtCore.Qt.Key_Up, a0.modifiers()))
        else:
            super().keyPressEvent(a0) 
示例20
def keyPressEvent(self, event: QtGui.QKeyEvent) -> None:
        key_press = event.key()
        # if key_press == Qt.Key_Up:
        #     self.snake.direction = 'u'
        # elif key_press == Qt.Key_Down:
        #     self.snake.direction = 'd'
        # elif key_press == Qt.Key_Right:
        #     self.snake.direction = 'r'
        # elif key_press == Qt.Key_Left:
        #     self.snake.direction = 'l' 
示例21
def keyPressEvent(self, event):
        if type(event) == QtGui.QKeyEvent:
            if event.modifiers()== QtCore.Qt.ControlModifier and  event.key() == QtCore.Qt.Key_Q:
                return
        # super(MainWidget,self).keyPressEvent(event) 
示例22
def keyPressEvent(self, evt: QtGui.QKeyEvent) -> None:
        self.keyPressed.emit(evt)
        super(MainWindow, self).keyPressEvent(evt) 
示例23
def keyPressEvent(self, event: QtGui.QKeyEvent) -> None:
        row = self.images_list_widget.currentRow()
        last_index = self.images_list_widget.count() - 1
        if event.key() == QtCore.Qt.Key_A:
            @gui_exception
            def done_work(result):
                _, err = result
                if err:
                    raise err
                if row > 0:
                    self.images_list_widget.setCurrentRow(row - 1)
                else:
                    self.images_list_widget.setCurrentRow(last_index)

            self.save_annotations(done_work)
        elif event.key() == QtCore.Qt.Key_D:
            @gui_exception
            def done_work(result):
                _, err = result
                if err:
                    raise err
                if row < last_index:
                    self.images_list_widget.setCurrentRow(row + 1)
                else:
                    self.images_list_widget.setCurrentRow(0)

            self.save_annotations(done_work)
        super(ImageViewerWidget, self).keyPressEvent(event) 
示例24
def keyPressEvent(self, event: QKeyEvent):
        if event.key() == QtCore.Qt.Key_Space:
            image_rect: QRectF = self._pixmap.sceneBoundingRect()
            if self.current_tool == SELECTION_TOOL.POLYGON and self._current_polygon:
                points = self._current_polygon.points
                self._polygon_guide_line.hide()
                self.setDragMode(QGraphicsView.ScrollHandDrag)
                if len(points) <= 2:
                    self._current_polygon.delete_item()
                self.current_tool = SELECTION_TOOL.POINTER
            elif self.current_tool == SELECTION_TOOL.EXTREME_POINTS and \
                    self._extreme_points.full():
                points = []
                image_offset = QPointF(image_rect.width() / 2, image_rect.height() / 2)
                for pt in self._extreme_points.queue:
                    pt: EditablePolygonPoint
                    center = pt.sceneBoundingRect().center()
                    x = math.floor(center.x() + image_offset.x())
                    y = math.floor(center.y() + image_offset.y())
                    points.append([x, y])
                self.points_selection_sgn.emit(points)
                self.current_tool = SELECTION_TOOL.POINTER
        else:
            event.ignore()

    # guide lines events 
示例25
def keyReleaseEvent(self, keyEvent):
        """Overrides to make sure key release passed on to other classes.

        :param QKeyEvent keyEvent: instance of |QKeyEvent|"""
        assert isinstance(keyEvent, QtGui.QKeyEvent)
        # print("graphicsView keyRelease count=%d, autoRepeat=%s" %
        # (keyEvent.count(), keyEvent.isAutoRepeat()))
        keyEvent.ignore()
        # super(SynchableGraphicsView, self).keyReleaseEvent(keyEvent) 
示例26
def keyPressEvent(self, keyEvent):
        """Overrides to enable panning while dragging.

        :param QKeyEvent keyEvent: instance of |QKeyEvent|"""
        assert isinstance(keyEvent, QtGui.QKeyEvent)
        if keyEvent.key() == QtCore.Qt.Key_Space:
            if (not keyEvent.isAutoRepeat() and
                    not self._imageViewer.handDragging):
                self._imageViewer.enableHandDrag(True)
            keyEvent.accept()
        else:
            keyEvent.ignore()
            super(MainWindow, self).keyPressEvent(keyEvent) 
示例27
def keyPressEvent(self, event: QKeyEvent):
        if self.window().is_dirty() \
                and (event.matches(QKeySequence.MoveToNextLine) or event.matches(QKeySequence.MoveToPreviousLine)):
            veto = self.window().central_widget.promptToSave()
            if not veto:
                QTreeWidget.keyPressEvent(self, event)
            else:
                event.ignore()
        else:
            QTreeWidget.keyPressEvent(self, event) 
示例28
def keyPressEvent(self, event: QtGui.QKeyEvent) -> None:
        """
        Reimplement this method of parent to move chart horizontally and zoom in/out.
        """
        if event.key() == QtCore.Qt.Key_Left:
            self._on_key_left()
        elif event.key() == QtCore.Qt.Key_Right:
            self._on_key_right()
        elif event.key() == QtCore.Qt.Key_Up:
            self._on_key_up()
        elif event.key() == QtCore.Qt.Key_Down:
            self._on_key_down() 
示例29
def keyPressEvent(self, event: QKeyEvent):
        if event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return:
            return
        else:
            super().keyPressEvent(event) 
示例30
def keyPressEvent(self, event: QKeyEvent):
        if event.key() == Qt.Key_Enter:
            event.ignore()
        else:
            event.accept()