Python PyQt5.QtGui.QKeyEvent() Examples

The following are 30 code examples of PyQt5.QtGui.QKeyEvent(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PyQt5.QtGui , or try the search function .
Example #1
Source File: mainwindow.py    From track with Apache License 2.0 11 votes vote down vote up
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) 
Example #2
Source File: command.py    From qutebrowser with GNU General Public License v3.0 7 votes vote down vote up
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) 
Example #3
Source File: mdi_area.py    From asammdf with GNU Lesser General Public License v3.0 7 votes vote down vote up
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 
Example #4
Source File: videoslider.py    From vidcutter with GNU General Public License v3.0 7 votes vote down vote up
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) 
Example #5
Source File: keyutils.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #6
Source File: eventfilter.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: candle_demo.py    From Python-CTPAPI with MIT License 6 votes vote down vote up
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() 
Example #8
Source File: modeparsers.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #9
Source File: list.py    From asammdf with GNU Lesser General Public License v3.0 6 votes vote down vote up
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) 
Example #10
Source File: ModulatorDialog.py    From urh with GNU General Public License v3.0 6 votes vote down vote up
def keyPressEvent(self, event: QKeyEvent):
        if event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return:
            return
        else:
            super().keyPressEvent(event) 
Example #11
Source File: modeman.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #12
Source File: SelectableGraphicView.py    From urh with GNU General Public License v3.0 5 votes vote down vote up
def keyPressEvent(self, event: QKeyEvent):
        if event.key() == Qt.Key_Shift:
            self.shift_mode = True

            if self.hold_shift_to_drag:
                self.setCursor(Qt.OpenHandCursor)
            else:
                self.unsetCursor()
                self.grab_start = None

        super().keyPressEvent(event) 
Example #13
Source File: imageViewer.py    From CvStudio with MIT License 5 votes vote down vote up
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) 
Example #14
Source File: imageViewer.py    From CvStudio with MIT License 5 votes vote down vote up
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) 
Example #15
Source File: autokey_treewidget.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #16
Source File: ProtocolLabelDialog.py    From urh with GNU General Public License v3.0 5 votes vote down vote up
def keyPressEvent(self, event: QKeyEvent):
        if event.key() == Qt.Key_Enter:
            event.ignore()
        else:
            event.accept() 
Example #17
Source File: FuzzingTableView.py    From urh with GNU General Public License v3.0 5 votes vote down vote up
def keyPressEvent(self, event: QKeyEvent):
        if event.key() == Qt.Key_Delete:
            selected = self.selectionModel().selection()
            """:type: QtGui.QItemSelection """
            if selected.isEmpty():
                return

            min_row = numpy.min([rng.top() for rng in selected])
            max_row = numpy.max([rng.bottom() for rng in selected])
            self.deletion_wanted.emit(min_row, max_row)

        else:
            super().keyPressEvent(event) 
Example #18
Source File: TextEditProtocolView.py    From urh with GNU General Public License v3.0 5 votes vote down vote up
def keyPressEvent(self, event: QKeyEvent):
        if event.key() == Qt.Key_Delete:
            self.deletion_wanted.emit()
            event.ignore()
        else:
            super().keyPressEvent(event) 
Example #19
Source File: mainwidget.py    From spimagine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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) 
Example #20
Source File: GeneratorListView.py    From urh with GNU General Public License v3.0 5 votes vote down vote up
def keyPressEvent(self, event: QKeyEvent):
        if event.key() in (Qt.Key_Enter, Qt.Key_Return):
            selected = [index.row() for index in self.selectedIndexes()]
            if len(selected) > 0:
                self.edit_on_item_triggered.emit(min(selected))
        else:
            super().keyPressEvent(event) 
Example #21
Source File: mdi_area.py    From asammdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_region(self, widget, region):
        if self._region_source is None:
            self._region_source = widget
            for mdi in self.mdi_area.subWindowList():
                wid = mdi.widget()
                if isinstance(wid, Plot) and wid is not widget:
                    if wid.plot.region is None:
                        event = QtGui.QKeyEvent(
                            QtCore.QEvent.KeyPress,
                            QtCore.Qt.Key_R,
                            QtCore.Qt.NoModifier,
                        )
                        wid.plot.keyPressEvent(event)
                    wid.plot.region.setRegion(region)
            self._region_source = None 
Example #22
Source File: mdi_area.py    From asammdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def remove_region(self, widget):
        if self._region_source is None:
            self._region_source = widget
            for mdi in self.mdi_area.subWindowList():
                plt = mdi.widget()
                if isinstance(plt, Plot) and plt is not widget:
                    if plt.plot.region is not None:
                        event = QtGui.QKeyEvent(
                            QtCore.QEvent.KeyPress,
                            QtCore.Qt.Key_R,
                            QtCore.Qt.NoModifier,
                        )
                        plt.plot.keyPressEvent(event)
            self._region_source = None 
Example #23
Source File: main.py    From asammdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def plot_action(self, key, modifier=QtCore.Qt.NoModifier):
        event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, key, modifier)
        if self.stackedWidget.currentIndex() == 0:
            widget = self.files.currentWidget()
            if widget and widget.get_current_plot():
                widget.get_current_plot().keyPressEvent(event)
        elif self.stackedWidget.currentIndex() == 2:
            widget = self
            if widget and widget.get_current_plot():
                widget.get_current_plot().keyPressEvent(event) 
Example #24
Source File: plot_standalone.py    From asammdf with GNU Lesser General Public License v3.0 5 votes vote down vote up
def plot_action(self, key, modifier=QtCore.Qt.NoModifier):
        event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, key, modifier)
        self.plot.keyPressEvent(event) 
Example #25
Source File: modeman.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #26
Source File: browsertab.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #27
Source File: keyutils.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #28
Source File: keyutils.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
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()) 
Example #29
Source File: eventfilter.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #30
Source File: modeparsers.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
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