Python源码示例:PyQt5.QtCore.QEvent.KeyPress()
示例1
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
示例2
def eventFilter(self, obj, e):
if obj == self.command and e.type() == QEvent.KeyPress:
history = self.device.history
if e.modifiers() & Qt.ControlModifier:
if e.key() == Qt.Key_H:
d = DeviceConsoleHistory(self.device.env.devices)
if d.exec_() == QDialog.Accepted:
self.command.setText(d.command)
elif len(history) > 0:
if e.key() == Qt.Key_E:
self.command.setText(history[0])
if e.key() == Qt.Key_Down:
self.command.completer().setModel(QStringListModel(history))
self.command.setText(' ')
self.command.completer().complete()
return False
return QDockWidget.eventFilter(self, obj, e)
示例3
def test_surrogates(key, modifiers, text, expected):
evt = QKeyEvent(QKeyEvent.KeyPress, key, modifiers, text)
assert str(keyutils.KeyInfo.from_event(evt)) == expected
示例4
def test_append_event(self, old, key, modifiers, text, expected):
seq = keyutils.KeySequence.parse(old)
event = QKeyEvent(QKeyEvent.KeyPress, key, modifiers, text)
new = seq.append_event(event)
assert new == keyutils.KeySequence.parse(expected)
示例5
def test_append_event_invalid(self, key):
seq = keyutils.KeySequence()
event = QKeyEvent(QKeyEvent.KeyPress, key, Qt.NoModifier, '')
with pytest.raises(keyutils.KeyParseError):
seq.append_event(event)
示例6
def test_key_info_from_event():
ev = QKeyEvent(QEvent.KeyPress, Qt.Key_A, Qt.ShiftModifier, 'A')
info = keyutils.KeyInfo.from_event(ev)
assert info.key == Qt.Key_A
assert info.modifiers == Qt.ShiftModifier
示例7
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())
示例8
def __init__(self, parent: QObject = None) -> None:
super().__init__(parent)
self._activated = True
self._handlers = {
QEvent.KeyPress: self._handle_key_event,
QEvent.KeyRelease: self._handle_key_event,
QEvent.ShortcutOverride: self._handle_key_event,
}
示例9
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))
示例10
def eventFilter(self, source, event):
if event.type() == QEvent.KeyPress:
if event.key():
# show new keys in window
self.capturedKeyLabel.setText(str(QKeySequence(event.modifiers() | event.key()).toString()))
return super(KeyCapturingWindow, self).eventFilter(source, event)
示例11
def eventFilter(self, obj, event):
if obj == self.edtCommand:
if event.type() == QEvent.KeyPress:
if event.key() == Qt.Key_Up:
self.prev_command()
return True
elif event.key() == Qt.Key_Down:
self.next_command()
return True
return False
else:
return super().eventFilter(obj, event)
示例12
def handleEvent(self, event):
if event.type() == QEvent.KeyPress:
e = KeyEvent(KeyEvent.KeyPressEvent, self._qtKeyToUMKey(event.key()))
self.event.emit(e)
elif event.type() == QEvent.KeyRelease:
e = KeyEvent(KeyEvent.KeyReleaseEvent, self._qtKeyToUMKey(event.key()))
self.event.emit(e)
示例13
def eventFilter(self, source, evt):
t = evt.type()
if t == QEvent.Wheel:
self.new_entry_flag = True
self.mouse_scroll_event(evt)
return True
elif t == QEvent.KeyPress:
self.new_entry_flag = True
if evt.key() == QtCore.Qt.Key_Return:
self.update_entry(evt)
return True
return False
示例14
def eventFilter(self, receiver, event):
# catch up/down arrow key presses in hosts table
if event.type() == QEvent.KeyPress and receiver in self.hosts_table_views:
return self.filterKeyPressInHostsTableView(event.key(), receiver)
elif event.type() == QEvent.Close and receiver == self.main_window:
event.ignore()
self.view.appExit()
return True
else:
parent = super(MyEventFilter, self)
return parent.eventFilter(receiver, event) # normal event processing
示例15
def simulateKeyPress(self, key_event):
self.mock_event.type = Mock(return_value=QEvent.KeyPress)
self.mock_event.key = Mock(return_value=key_event)
示例16
def eventFilter(self, receiver, event):
"""
send event (if keypress) to main window
"""
if(event.type() == QEvent.KeyPress):
self.sendEvent.emit(event)
return True
else:
return False
示例17
def eventFilter(self, receiver, event):
"""
send event (if keypress) to main window
"""
if(event.type() == QEvent.KeyPress):
self.sendEvent.emit(event)
return True
else:
return False
示例18
def eventFilter(self, sender, event):
if event.type() == QEvent.ChildRemoved:
self.internalMove.emit()
elif event.type() == QEvent.KeyPress and event.key() in (Qt.Key_Delete, Qt.Key_Backspace)\
and self.currentItem() is not None:
item = self.currentRow()
item_name = self.currentItem().text()
self.active_element_text = item_name
self.takeItem(item)
self.deleteElement.emit()
return False
示例19
def _handle_keypress(self, event: QKeyEvent, *,
dry_run: bool = False) -> bool:
"""Handle filtering of KeyPress events.
Args:
event: The KeyPress to examine.
dry_run: Don't actually handle the key, only filter it.
Return:
True if event should be filtered, False otherwise.
"""
curmode = self.mode
parser = self.parsers[curmode]
if curmode != usertypes.KeyMode.insert:
log.modes.debug("got keypress in mode {} - delegating to "
"{}".format(curmode, utils.qualname(parser)))
match = parser.handle(event, dry_run=dry_run)
has_modifier = event.modifiers() not in [
Qt.NoModifier,
Qt.ShiftModifier,
] # type: ignore[comparison-overlap]
is_non_alnum = has_modifier or not event.text().strip()
forward_unbound_keys = config.cache['input.forward_unbound_keys']
if match:
filter_this = True
elif (parser.passthrough or forward_unbound_keys == 'all' or
(forward_unbound_keys == 'auto' and is_non_alnum)):
filter_this = False
else:
filter_this = True
if not filter_this and not dry_run:
self._releaseevents_to_pass.add(KeyEvent.from_event(event))
if curmode != usertypes.KeyMode.insert:
focus_widget = QApplication.instance().focusWidget()
log.modes.debug("match: {}, forward_unbound_keys: {}, "
"passthrough: {}, is_non_alnum: {}, dry_run: {} "
"--> filter: {} (focused: {!r})".format(
match, forward_unbound_keys,
parser.passthrough, is_non_alnum, dry_run,
filter_this, focus_widget))
return filter_this
示例20
def eventFilter(self, target, event):
def match(s1, s2):
for x in s2:
if s1.matches(x) == QKeySequence.ExactMatch:
return True
return False
if target == self.inputTextBox:
if isinstance(event, QKeyEvent):
if event.type() == QKeyEvent.KeyPress:
event_sequence = QtHelper.key_event_sequence(event)
if match(event_sequence, Settings().new_line_key):
return False
if match(event_sequence, Settings().send_key):
self.send_input()
return True
if event.key() == Qt.Key_Tab:
self.inputTextBox.insertPlainText(" "*Settings().terminal_tab_spaces)
return True
if event.key() == Qt.Key_Up and (event.modifiers() & Qt.ControlModifier):
if self._input_history_index > 0:
self._input_history_index -= 1
self.inputTextBox.clear()
self.inputTextBox.setPlainText(self.terminal.input(self._input_history_index))
if event.key() == Qt.Key_Down and (event.modifiers() & Qt.ControlModifier):
if self._input_history_index < self.terminal.last_input_idx():
self._input_history_index += 1
self.inputTextBox.clear()
self.inputTextBox.setPlainText(self.terminal.input(self._input_history_index))
elif target == self.outputTextEdit:
if isinstance(event, QKeyEvent):
if event.type() == QEvent.KeyPress:
if event.key() == Qt.Key_Up:
self.connection.send_bytes(b"\x1b[A")
if event.key() == Qt.Key_Down:
self.connection.send_bytes(b"\x1b[B")
else:
t = event.text()
if t:
self.connection.send_character(t)
return True
elif target == self.outputTextEdit.verticalScrollBar():
if isinstance(event, QHideEvent):
return True
return False
示例21
def eventFilter(self, obj, event):
"""Reimplemented."""
if self.__popupIsShown and \
event.type() == QEvent.MouseMove and \
self.view().isVisible() and self.__initialMousePos is not None:
diff = obj.mapToGlobal(event.pos()) - self.__initialMousePos
if diff.manhattanLength() > 9 and \
self.__blockMouseReleaseTimer.isActive():
self.__blockMouseReleaseTimer.stop()
# pass through
if self.__popupIsShown and \
event.type() == QEvent.MouseButtonRelease and \
self.view().isVisible() and \
self.view().rect().contains(event.pos()) and \
self.view().currentIndex().isValid() and \
self.view().currentIndex().flags() & Qt.ItemIsSelectable and \
self.view().currentIndex().flags() & Qt.ItemIsEnabled and \
self.view().currentIndex().flags() & Qt.ItemIsUserCheckable and \
self.view().visualRect(self.view().currentIndex()).contains(event.pos()) and \
not self.__blockMouseReleaseTimer.isActive():
model = self.model()
index = self.view().currentIndex()
state = model.data(index, Qt.CheckStateRole)
model.setData(index,
Qt.Checked if state == Qt.Unchecked else Qt.Unchecked,
Qt.CheckStateRole)
self.view().update(index)
self.update()
self.flagChanged.emit(index.row(),state == Qt.Unchecked)
return True
if self.__popupIsShown and event.type() == QEvent.KeyPress:
if event.key() == Qt.Key_Space:
# toogle the current items check state
model = self.model()
index = self.view().currentIndex()
flags = model.flags(index)
state = model.data(index, Qt.CheckStateRole)
if flags & Qt.ItemIsUserCheckable and \
flags & Qt.ItemIsTristate:
state = Qt.CheckState((int(state) + 1) % 3)
elif flags & Qt.ItemIsUserCheckable:
state = Qt.Checked if state != Qt.Checked else Qt.Unchecked
model.setData(index, state, Qt.CheckStateRole)
self.view().update(index)
self.update()
self.flagChanged.emit(index.row(),state != Qt.Unchecked)
return True
# TODO: handle Qt.Key_Enter, Key_Return?
return super(CheckComboBox, self).eventFilter(obj, event)