def keyPressEvent(self, event): key = event.key() cursor = self.textCursor() if key == Qt.Key_Backspace and event.modifiers() & Qt.GroupSwitchModifier: # Workaround for https://bugreports.qt.io/browse/QTBUG-49771 event = QKeyEvent(event.type(), event.key(), event.modifiers() ^ Qt.GroupSwitchModifier) if key == Qt.Key_Tab: documentIndentMore(self.document(), cursor) elif key == Qt.Key_Backtab: documentIndentLess(self.document(), cursor) elif key == Qt.Key_Return and not cursor.hasSelection(): if event.modifiers() & Qt.ShiftModifier: # Insert Markdown-style line break markupClass = self.tab.getActiveMarkupClass() if markupClass == MarkdownMarkup: cursor.insertText(' ') if event.modifiers() & Qt.ControlModifier: cursor.insertText('\n') self.ensureCursorVisible() else: self.handleReturn(cursor) else: if event.text() and self.tableModeEnabled: cursor.beginEditBlock() QTextEdit.keyPressEvent(self, event) if event.text() and self.tableModeEnabled: cursor.endEditBlock()
def keyPressEvent(self, event: QKeyEvent) -> None: if self.vim_mode_enabled and self._nvim: response = self._nvim.request("nvim_get_mode") mode = response["mode"] blocking = response["blocking"] if self._z_mode and event.text() == "p": self._api.cmd.run_cmdline("play-region -s=a.s -e=a.e") self._z_mode = False elif not blocking: if mode == "n" and event.text() == "z": self._z_mode = True else: self._z_mode = False row, _col = self._nvim.current.window.cursor if mode == "n" and event.text() == "k" and row == 1: self._api.cmd.run_cmdline("sub-select one-above") return if (mode == "n" and event.text() == "j" and row == len(self._nvim.current.buffer)): self._api.cmd.run_cmdline("sub-select one-below") return super().keyPressEvent(event)
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
def keyPressEvent(self, event): key = event.key() cursor = self.textCursor() if key == Qt.Key_Backspace and event.modifiers( ) & Qt.GroupSwitchModifier: # Workaround for https://bugreports.qt.io/browse/QTBUG-49771 event = QKeyEvent(event.type(), event.key(), event.modifiers() ^ Qt.GroupSwitchModifier) if key == Qt.Key_Tab: documentIndentMore(self.document(), cursor) elif key == Qt.Key_Backtab: documentIndentLess(self.document(), cursor) elif key == Qt.Key_Return: markupClass = self.tab.getActiveMarkupClass() if event.modifiers() & Qt.ControlModifier: cursor.insertText('\n') self.ensureCursorVisible() elif self.tableModeEnabled and tablemode.handleReturn( cursor, markupClass, newRow=(event.modifiers() & Qt.ShiftModifier)): self.setTextCursor(cursor) self.ensureCursorVisible() else: if event.modifiers( ) & Qt.ShiftModifier and markupClass == MarkdownMarkup: # Insert Markdown-style line break cursor.insertText(' ') self.handleReturn(cursor) else: if event.text() and self.tableModeEnabled: cursor.beginEditBlock() QTextEdit.keyPressEvent(self, event) if event.text() and self.tableModeEnabled: cursor.endEditBlock()
def append_event(self, ev: QKeyEvent) -> 'KeySequence': """Create a new KeySequence object with the given QKeyEvent added.""" key = Qt.Key(ev.key()) _assert_plain_key(key) _assert_plain_modifier(ev.modifiers()) key = _remap_unicode(key, ev.text()) modifiers = int(ev.modifiers()) if key == _NIL_KEY: raise KeyParseError(None, "Got nil key!") # We always remove Qt.GroupSwitchModifier because QKeySequence has no # way to mention that in a binding anyways... modifiers &= ~Qt.GroupSwitchModifier # We change Qt.Key_Backtab to Key_Tab here because nobody would # configure "Shift-Backtab" in their config. if modifiers & Qt.ShiftModifier and key == Qt.Key_Backtab: key = Qt.Key_Tab # We don't care about a shift modifier with symbols (Shift-: should # match a : binding even though we typed it with a shift on an # US-keyboard) # # However, we *do* care about Shift being involved if we got an # upper-case letter, as Shift-A should match a Shift-A binding, but not # an "a" binding. # # In addition, Shift also *is* relevant when other modifiers are # involved. Shift-Ctrl-X should not be equivalent to Ctrl-X. if (modifiers == Qt.ShiftModifier and _is_printable(key) and not ev.text().isupper()): modifiers = Qt.KeyboardModifiers() # type: ignore[assignment] # On macOS, swap Ctrl and Meta back # # We don't use Qt.AA_MacDontSwapCtrlAndMeta because that also affects # Qt/QtWebEngine's own shortcuts. However, we do want "Ctrl" and "Meta" # (or "Cmd") in a key binding name to actually represent what's on the # keyboard. if utils.is_mac: # FIXME:qt6 Reevaluate the type ignores below if modifiers & Qt.ControlModifier and modifiers & Qt.MetaModifier: pass elif modifiers & Qt.ControlModifier: modifiers &= ~Qt.ControlModifier modifiers |= Qt.MetaModifier # type: ignore[assignment] elif modifiers & Qt.MetaModifier: modifiers &= ~Qt.MetaModifier modifiers |= Qt.ControlModifier # type: ignore[assignment] keys = list(self._iter_keys()) keys.append(key | int(modifiers)) return self.__class__(*keys)
def keyPressEvent(self, e: QtGui.QKeyEvent) -> None: cursor = self.textCursor() text_change = '' if e.text(): print(e.text(), len(e.text())) print(e.text().encode('utf-8')) if 32 <= ord(e.text()[0]) <= 126: self.pt.insert(cursor.position(), e.text()) self.send_cmd('insert %d %s' % (cursor.position(), e.text())) # self.socket.write(('insert %d %s' % (cursor.position(), e.text())).encode('utf-8')) elif e.key() == QtCore.Qt.Key_Return: self.pt.insert(cursor.position(), '\n') self.send_cmd('insert %d %s' % (cursor.position(), '\n')) # self.socket.write(('insert %d %s' % (cursor.position(), '\n')).encode('utf-8')) elif e.key() == QtCore.Qt.Key_Tab: self.pt.insert(cursor.position(), '\t') self.send_cmd('insert %d %s' % (cursor.position(), '\t')) # self.socket.write(('insert %d %s' % (cursor.position(), ' ' * self.tab_width)).encode('utf-8')) elif e.key() == QtCore.Qt.Key_Backspace or e.text().encode( 'utf-8') == b'\x08': print(cursor.position()) self.pt.delete(cursor.position() - 1, cursor.position() - 1) self.send_cmd('backspace %d' % cursor.position()) # self.socket.write(('backspace %d' % cursor.position()).encode('utf-8')) elif e.key() == QtCore.Qt.Key_Delete or e.text().encode( 'utf-8') == b'\x7f': self.pt.delete(cursor.position(), cursor.position()) t = QtWidgets.QPlainTextEdit.keyPressEvent(self, e) print(self.pt.get_sequence().encode('utf-8')) print('-' * 20) return t
def append_event(self, ev: QKeyEvent) -> 'KeySequence': """Create a new KeySequence object with the given QKeyEvent added.""" key = Qt.Key(ev.key()) _assert_plain_key(key) _assert_plain_modifier(ev.modifiers()) key = _remap_unicode(key, ev.text()) modifiers = int(ev.modifiers()) if key == _NIL_KEY: raise KeyParseError(None, "Got nil key!") # We always remove Qt.GroupSwitchModifier because QKeySequence has no # way to mention that in a binding anyways... modifiers &= ~Qt.GroupSwitchModifier # We change Qt.Key_Backtab to Key_Tab here because nobody would # configure "Shift-Backtab" in their config. if modifiers & Qt.ShiftModifier and key == Qt.Key_Backtab: key = Qt.Key_Tab # We don't care about a shift modifier with symbols (Shift-: should # match a : binding even though we typed it with a shift on an # US-keyboard) # # However, we *do* care about Shift being involved if we got an # upper-case letter, as Shift-A should match a Shift-A binding, but not # an "a" binding. # # In addition, Shift also *is* relevant when other modifiers are # involved. Shift-Ctrl-X should not be equivalent to Ctrl-X. if (modifiers == Qt.ShiftModifier and _is_printable(key) and not ev.text().isupper()): modifiers = Qt.KeyboardModifiers() # type: ignore[assignment] # On macOS, swap Ctrl and Meta back # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-51293 if utils.is_mac: if modifiers & Qt.ControlModifier and modifiers & Qt.MetaModifier: pass elif modifiers & Qt.ControlModifier: modifiers &= ~Qt.ControlModifier modifiers |= Qt.MetaModifier elif modifiers & Qt.MetaModifier: modifiers &= ~Qt.MetaModifier modifiers |= Qt.ControlModifier keys = list(self._iter_keys()) keys.append(key | int(modifiers)) return self.__class__(*keys)
def keyPressEvent(self, event: QKeyEvent) -> None: if self.vim_mode_enabled and self._nvim: with self._ignore_ui_signals(), self._reconnect_guard(): if event.key() in KEYMAP: self._nvim.input(KEYMAP[event.key()]) self._sync_ui() elif event.text(): self._nvim.input(event.text()) self._sync_ui() else: super().keyPressEvent(event) else: super().keyPressEvent(event)
def keyPressEvent(self, a0: QKeyEvent) -> None: #print(a0.text()) modifiers = QApplication.keyboardModifiers() alt = False if not modifiers & Qt.AltModifier: QTextEdit.keyPressEvent(self, a0) return else: a0.ignore() print("Alt-", end='') print(a0.text()) if a0.key() == Qt.Key_Return or a0.key() == Qt.Key_Enter: print("ENter") else: self.PickDict.emit(a0.text().lower())
def keyPressEvent(self, a0: QKeyEvent) -> None: if a0.text() == "f": buttons = self.buttongroup.buttons() id = self.buttongroup.checkedId() buttons[(id+1)%len(buttons)].setChecked(True) self.buttongroup_buttonClicked() if a0.text() == 'g': self.checkbox.toggle() self.painter.is_paint_atop = self.checkbox.isChecked() if a0.text() == "s": self.is_save_after_closed = True self.close() if a0.text() == "q": self.is_save_after_closed = False self.close()
def keyPressEvent(self, e: QKeyEvent): # table state # https://doc.qt.io/archives/qt-4.8/qabstractitemview.html#State-enum state = self.state() key = e.key() index = self.currentIndex() if self.dialog.isVisible(): if key == Qt.Key_N: self.nextMatch() return elif key == Qt.Key_R: self.replace() return if state == QAbstractItemView.EditingState: if e.modifiers() == Qt.ControlModifier: if key in key_remap: self.commitData(self.focusWidget()) self.closeEditor(self.focusWidget(), QAbstractItemDelegate.NoHint) e = QKeyEvent(QEvent.KeyPress, key_remap.get(key), Qt.NoModifier, e.text()) super(TableView, self).keyPressEvent(e) self.edit(self.currentIndex()) return if state == QAbstractItemView.NoEditTriggers: if key in (Qt.Key_I, Qt.Key_S): self.edit(index) return if key in key_remap.keys(): e = QKeyEvent(QEvent.KeyPress, key_remap.get(key), e.modifiers(), e.text()) if key == Qt.Key_G: # press shift+g go to bottom of row if e.modifiers() == Qt.ShiftModifier: row_cnt = self.model().rowCount() - 1 sibling = index.sibling(row_cnt, index.column()) else: # press g go to top of row sibling = index.sibling(0, index.column()) self.setCurrentIndex(sibling) return if key == Qt.Key_Delete or key == Qt.Key_D: self.deleteKeyPress.emit(self.currentIndex(), '', '') return super(TableView, self).keyPressEvent(e)
def keyPressEvent(self, event): # hack -- force uppercase if event.text().upper() != event.text().lower(): from PyQt5.QtGui import QKeyEvent event = QKeyEvent(QKeyEvent.KeyPress, event.key(), event.modifiers(), event.text().upper(), False, 1) tc = self.textCursor() if event.key() == Qt.Key_Return and self.completer.popup().isVisible(): self.completer.insertText.emit(self.completer.getSelected()) self.completer.setCompletionMode(QCompleter.PopupCompletion) return QPlainTextEdit.keyPressEvent(self, event) tc.select(QTextCursor.WordUnderCursor) cr = self.cursorRect() if len(tc.selectedText()) > 0: self.completer.setCompletionPrefix(tc.selectedText()) popup = self.completer.popup() popup.setCurrentIndex(self.completer.completionModel().index(0,0)) cr.setWidth(self.completer.popup().sizeHintForColumn(0) + self.completer.popup().verticalScrollBar().sizeHint().width()) self.completer.complete(cr) else: self.completer.popup().hide()
def on_key_pressed(self, key_event: QKeyEvent): key = key_event.key() if c := self.window.get_selected_cell(): value = key_event.text() if key == Qt.Key_Escape: self.window.unselect_current_cell() elif key == Qt.Key_Delete or value in self.matrix.get_input_values( ): delete = key == Qt.Key_Delete empty_val = self.matrix.get_empty_value() collisions = self.matrix.insert(c.get_grid_x(), c.get_grid_y(), empty_val if delete else value) c.set_value('0' if delete else value) self.window.unselect_current_cell() self.window.update_cells(collision_positions=collisions) elif key == Qt.Key_W: next_item = self.matrix.get_next_input_for( c.get_grid_x(), c.get_grid_y()) collisions = self.matrix.insert(c.get_grid_x(), c.get_grid_y(), next_item) c.set_value(next_item) self.window.update_cells(collision_positions=collisions) elif key == Qt.Key_S: previous_item = self.matrix.get_previous_input_for( c.get_grid_x(), c.get_grid_y()) collisions = self.matrix.insert(c.get_grid_x(), c.get_grid_y(), previous_item) c.set_value(previous_item) self.window.update_cells(collision_positions=collisions)
def keyPressEvent(self, event: QKeyEvent) -> None: """ Parse keyboard input events for special cases. """ key = event.key() if key == Qt.Key_Up: # Up - replace user text with the previous command history item. self._history_prev() elif key == Qt.Key_Down: # Down - replace user text with the next command history item. self._history_next() elif key in (Qt.Key_Return, Qt.Key_Enter): # Enter - submit user text as terminal input. self._submit() elif event.modifiers() & Qt.ControlModifier: # Ctrl shortcuts have spurious event text. if key == Qt.Key_C and not self.textCursor().selectedText(): # Ctrl-C is an interrupt if no text is selected; otherwise it is a copy. self.interrupted.emit() else: super().keyPressEvent(event) else: # In all other cases, process the event as normal. if event.text(): # Reset the cursor before inserting actual text. self._set_cursor_valid() super().keyPressEvent(event)
def keyReleaseEvent(self, event: QtGui.QKeyEvent) -> None: if self.rfb: text = event.text() if len(text) == 1: self.rfb.key_event(ord(text), False) else: self.rfb.key_event(event.key(), False)
def keyPressEvent(self, event: QtGui.QKeyEvent) -> None: if self.rfb: text = event.text() if len(text) == 1: self.rfb.key_event(ord(text), True) else: self.rfb.key_event(event.key(), True)
def handle(self, e: QKeyEvent, *, dry_run: bool = False) -> QKeySequence.SequenceMatch: """Override to always match the next key and use the register.""" match = super().handle(e, dry_run=dry_run) if match or dry_run: return match if keyutils.is_special(Qt.Key(e.key()), e.modifiers()): # this is not a proper register key, let it pass and keep going return QKeySequence.NoMatch key = e.text() tabbed_browser = objreg.get('tabbed-browser', scope='window', window=self._win_id) try: if self._register_mode == usertypes.KeyMode.set_mark: tabbed_browser.set_mark(key) elif self._register_mode == usertypes.KeyMode.jump_mark: tabbed_browser.jump_mark(key) elif self._register_mode == usertypes.KeyMode.record_macro: macros.macro_recorder.record_macro(key) elif self._register_mode == usertypes.KeyMode.run_macro: macros.macro_recorder.run_macro(self._win_id, key) else: raise ValueError("{} is not a valid register mode".format( self._register_mode)) except cmdexc.Error as err: message.error(str(err), stack=traceback.format_exc()) self.request_leave.emit( self._register_mode, "valid register key", True) return QKeySequence.ExactMatch
def keyPressEvent(self, event: QKeyEvent): if self._completedAndSelected and self.handledCompletedAndSelected( event): return self._completedAndSelected = False if self._completer.popup().isVisible(): ignoredKeys = [ Qt.Key_Up, Qt.Key_Down, Qt.Key_Enter, Qt.Key_Return, Qt.Key_Tab, Qt.Key_Escape, ] if event.key() in ignoredKeys: event.ignore() return self._completer.popup().hide() super().keyPressEvent(event) if not self._enableAutoCompletion: return ctrlOrShift = (event.modifiers() & Qt.ShiftModifier == Qt.ShiftModifier or event.modifiers() & Qt.ControlModifier == Qt.ControlModifier) if ctrlOrShift and not event.text(): return if self.textCursor().atBlockEnd(): self.suggestCompletions()
def _get_base_keysequence(event: QKeyEvent) -> SequenceT: """Get main keyname part of QKeyEvent. Converts special keys to usable names and uses event.text() otherwise. Is a sequence to allow prepending <shift> to special keys. Args: event: The emitted QKeyEvent. Returns: Name of the main key press escaping special keys. """ special_keys = { Qt.Key_Space: "<space>", Qt.Key_Backtab: "<tab>", Qt.Key_Tab: "<tab>", Qt.Key_Escape: "<escape>", Qt.Key_Enter: "<enter>", Qt.Key_Return: "<return>", Qt.Key_Backspace: "<backspace>", Qt.Key_Left: "<left>", Qt.Key_Right: "<right>", Qt.Key_Up: "<up>", Qt.Key_Down: "<down>", Qt.Key_Home: "<home>", Qt.Key_End: "<end>", Qt.Key_PageUp: "<page-up>", Qt.Key_PageDown: "<page-down>", Qt.Key_Home: "<home>", Qt.Key_End: "<end>", } separator_keys = { Qt.Key_Colon: "<colon>", Qt.Key_Equal: "<equal>", } if event.key() in special_keys: # Parse shift here as the key does not support it otherwise text = special_keys[event.key()] # type: ignore if event.modifiers() & Qt.ShiftModifier: # type: ignore return "<shift>", text return (text, ) if event.key( ) in separator_keys: # Required as configparser crashes otherwise return (separator_keys[event.key()], ) # type: ignore if event.text().isprintable(): return (event.text(), ) return (QKeySequence(event.key()).toString().lower(), )
def event(key, text, modifiers, scancode=0): ev = QKeyEvent(QKeyEvent.KeyPress, key, modifiers, text) return { "key": ev.key(), "nativeScanCode": scancode, "text": ev.text(), "modifiers": ev.modifiers(), }
def keyPressEvent(self, event: QKeyEvent): """ Обработка нажатий на кнопки клавиатуры """ key = event.key() # ключ нажатой кнопки text = event.text().lower() # текст нажатой кнопки # замена вводимых латинских букв на кириллицу и Ё на Е # комментарий ниже указывает PyCharm не проверять строки на опечатки # noinspection SpellCheckingInspection _eng_chars = u"`qwertyuiop[]asdfghjkl;'zxcvbnm,." \ u"QWERTYUIOP{}ASDFGHJKL:\"|ZXCVBNM<>" _rus_chars = u"ёйцукенгшщзхъфывапролджэячсмитьбю" \ u"ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭ/ЯЧСМИТЬБЮ" _trans_table = dict(zip(_eng_chars, _rus_chars)) text = text.join([_trans_table.get(c, c) for c in text]) if text == 'ё': text = 'е' # выход из программы по нажатию Escape if key == Qt.Key_Escape: self.close() # запуск алгоритма по нажатию Enter elif key == Qt.Key_Return: self._start_button.animateClick() # сброс по нажатию Backspace elif key == Qt.Key_Backspace: self._drop_button.animateClick() # если нажатая кнопка - один символ elif len(text) == 1: # если это "а"-"я" if 1072 <= ord(text) <= 1103: # если кнопка выключена, приложение не на начальном экране # и строка выбранных фишек не заполнена, # выводим сообщение, что кончились фишки с такой буквой if not self._letters_buttons[ord(text) - 1072].isEnabled() \ and self._start_button.isEnabled(): if sum(self._chosen_letters.values()) != 7: self._msg_label.setText(self._msg_max_chip_error + text.upper()) # если 7 фишек уже выбрано, выводим об этом сообщение else: self._msg_label.setText(self._msg_max_chips_error) # иначе производим нажатие нужной кнопки else: self._letters_buttons[ord(text) - 1072].animateClick() # аналогично, обработка звездочки elif text == '*' and self._asterisk_active: if not self._letters_buttons[32].isEnabled() \ and self._start_button.isEnabled(): if sum(self._chosen_letters.values()) != 7: self._msg_label.setText(self._msg_max_chip_aster_error) else: self._msg_label.setText(self._msg_max_chips_error) else: self._letters_buttons[32].animateClick()
def __makeKeyEvent(self, measure_editor: BaseMeasureEditor, evt: QtGui.QKeyEvent) -> QtGui.QKeyEvent: measure_evt = QtGui.QKeyEvent(evt.type(), evt.key(), evt.modifiers(), evt.nativeScanCode(), evt.nativeVirtualKey(), evt.nativeModifiers(), evt.text(), evt.isAutoRepeat(), evt.count()) measure_evt.setAccepted(False) return measure_evt
def keyPressEvent1(self, e: QtGui.QKeyEvent) -> None: print(e.text(), e.key()) cursor = self.textCursor() cursor_move_length = 0 print('old pos:', cursor.position()) # if e.key() == QtCore.Qt.Key_Left: # print('left') # cursor_move_length = -1 # cursor.setPosition(cursor.position() + cursor_move_length, QtGui.QTextCursor.MoveAnchor) # # self.setPlainText(self.pt.get_sequence()) # self.setTextCursor(cursor) # print('new pos:', cursor.position()) # return if e.text(): # self.parent.server.send('1') if 32 <= ord( e.text()[0]) <= 126 or e.key() == QtCore.Qt.Key_Return: print('ord') self.insert(e.text(), cursor.position()) cursor_move_length = 1 elif e.key() == QtCore.Qt.Key_Tab: self.insert(e.text(), cursor.position()) cursor_move_length = self.tab_width elif e.key() == QtCore.Qt.Key_Backspace: print( 'delete:', self.pt.subsequence(cursor.position() - 1, cursor.position() - 1)) print(cursor.position()) self.pt.delete(cursor.position(), cursor.position()) self.setPlainText(self.pt.get_sequence()) cursor_move_length = -1 if cursor_move_length != 0: cursor.setPosition(cursor.position() + cursor_move_length, QtGui.QTextCursor.MoveAnchor) self.setTextCursor(cursor) print('new pos:', cursor.position()) return # print(cursor) # print(e) t = QtWidgets.QPlainTextEdit.keyPressEvent(self, e) print(type(t), t) return t
def keyPressEvent(self, event: QKeyEvent): """event.key() seems to be capital only? Args: event (TYPE): Description """ # print("press", ord('g')) if event.text() == 'g': print("hey het") return QGraphicsItem.keyPressEvent(self, event)
def keyPressEvent(self, event: QKeyEvent): """event.key() seems to be capital only? Args: event: the key event """ # print("press", ord('g')) if event.text() == 'g': print("hey het") return QGraphicsItem.keyPressEvent(self, event)
def __init__(self, key_event: QtGui.QKeyEvent): if key_event is None: self.key = None self.char = '' self.count = 0 self.modifiers = QtCore.Qt.NoModifier else: self.key = key_event.key() self.char = key_event.text() self.count = key_event.count() self.modifiers = key_event.modifiers()
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, modifiers)
def keyPressEvent(self, event: QtGui.QKeyEvent) -> None: if event.text() or event.key() in (Qt.Key_Left, Qt.Key_Right): QtWidgets.QLineEdit.keyPressEvent(self, event) self.reset_ac_suggestions.emit() self.reset_history_travel.emit() elif event.key() == Qt.Key_Up: self.history_up.emit() elif event.key() == Qt.Key_Down: self.history_down.emit() else: return super().keyPressEvent(event)
def keyPressEvent(self, event: QKeyEvent): # Eventos de teclado button_key = event.text().upper() print(button_key) if button_key in self.BUTTONS or event.key() == Qt.Key_Enter: for button in self.buttons: value = self.buttons[button] if value == button_key or (event.key() == Qt.Key_Enter and value == "="): button.click() elif event.key() == Qt.Key_Backspace: self.buffer - 1 self.result_label.set_label_text(f"{self.buffer}")
def keyPressEvent(self, event: QtGui.QKeyEvent): """Bugfix, disables SHIFT+RETURN misbehaviour.""" if (event.key() == QtCore.Qt.Key_Enter or event.key() == 16777220) and \ ((event.modifiers() & QtCore.Qt.ShiftModifier) == QtCore.Qt.ShiftModifier): # clone object but without shift # current modifiers & all possible modifiers, but SHIFT,ALT,CTRL event = QtGui.QKeyEvent( event.type(), event.key(), event.modifiers() & QtCore.Qt.MetaModifier & QtCore.Qt.KeypadModifier, event.text(), event.isAutoRepeat(), event.count()) super().keyPressEvent(event)
def keyPressEvent(self, event: QtGui.QKeyEvent) -> None: if not self._vim_mode_enabled: super().keyPressEvent(event) elif self.insert_mode: if event.text() == '\\' and not self.in_leader: def exit_leader() -> None: if self.in_leader: self.textCursor().insertText('\\') self.in_leader = False QtCore.QTimer.singleShot(500, exit_leader) self.in_leader = True elif event.key() == Qt.Key_Escape or (self.in_leader and event.text() == 'e'): self.in_leader = False self.insert_mode = False else: super().keyPressEvent(event) elif self.normal_mode_key_event is not None: self.normal_mode_key_event(event)
def keyPressEvent(self, a0: QKeyEvent) -> None: if a0.key() == self.BACKSPACE_KEY_ID and isinstance( self.centralWidget(), GameWidget): self.centralWidget().change_meta_menud_state() if isinstance(self.centralWidget(), EndGameWinWidget): if a0.key() == self.ESC_KEY_ID: self.centralWidget().remove_name_symbol() return txt = a0.text() if len(txt) == 1: self.centralWidget().add_name_symbol(txt)
def keyPressEvent(self, e: QtGui.QKeyEvent) -> None: cursor = self.textCursor() # 获取当前光标 if e.text(): if 32 <= ord(e.text()[0]) <= 126: # 输入普通字符 self.pt.insert(cursor.position(), e.text()) self.send_cmd('insert %d %s' % (cursor.position(), e.text())) # 向其他客户端发送当前的操作 elif e.key() == QtCore.Qt.Key_Return: # 输入回车 self.pt.insert(cursor.position(), '\n') self.send_cmd('insert %d %s' % (cursor.position(), '\n')) # 向其他客户端发送当前的操作 elif e.key() == QtCore.Qt.Key_Tab: # 输入制表符 self.pt.insert(cursor.position(), '\t') self.send_cmd('insert %d %s' % (cursor.position(), '\t')) # 向其他客户端发送当前的操作 elif e.key() == QtCore.Qt.Key_Backspace or e.text().encode( 'utf-8') == b'\x08': # 退格 self.pt.delete(cursor.position() - 1, cursor.position() - 1) self.send_cmd('backspace %d' % cursor.position()) # 向其他客户端发送当前的操作 elif e.key() == QtCore.Qt.Key_Delete or e.text().encode( 'utf-8') == b'\x7f': # 删除后一个字符 self.pt.delete(cursor.position(), cursor.position()) return QtWidgets.QPlainTextEdit.keyPressEvent(self, e)
def keyPressEvent(self, event: QKeyEvent): """Must intercept invalid input events. Make changes here """ a = event.key() text = event.text() if a in [Qt.Key_Space, Qt.Key_Tab]: return elif a in [Qt.Key_Escape]: self.updateLabel() self.focusOut() return elif a in [Qt.Key_Return, Qt.Key_Enter]: self.inputMethodEvent(event) return elif text.isalpha(): return else: return QGraphicsTextItem.keyPressEvent(self, event)