Skip to content

Instantly share code, notes, and snippets.

@blink1073
Last active March 4, 2020 16:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blink1073/946df268c3685a3f443e to your computer and use it in GitHub Desktop.
Save blink1073/946df268c3685a3f443e to your computer and use it in GitHub Desktop.
Qt Keyboard Shortcut Editor
import sys
from PyQt4 import QtGui, QtCore
import warnings
class KeySequenceEdit(QtGui.QLineEdit):
"""
This class is mainly inspired by
http://stackoverflow.com/a/6665017
"""
def __init__(self, keySequence, *args):
super(KeySequenceEdit, self).__init__(*args)
self.setText(keySequence)
self.npressed = 0
self.keys = set()
def keyPressEvent(self, e):
if e.type() == QtCore.QEvent.KeyPress:
key = e.key()
self.npressed += 1
if key == QtCore.Qt.Key_unknown:
warnings.warn("Unknown key from a macro probably")
return
# the user have clicked just and only the special keys
# Ctrl, Shift, Alt, Meta.
if (key == QtCore.Qt.Key_Control or
key == QtCore.Qt.Key_Shift or
key == QtCore.Qt.Key_Alt or
key == QtCore.Qt.Key_Meta):
return
modifiers = e.modifiers()
if modifiers & QtCore.Qt.ShiftModifier:
key += QtCore.Qt.SHIFT
if modifiers & QtCore.Qt.ControlModifier:
key += QtCore.Qt.CTRL
self.npressed -= 1
if modifiers & QtCore.Qt.AltModifier:
key += QtCore.Qt.ALT
if modifiers & QtCore.Qt.MetaModifier:
key += QtCore.Qt.META
self.keys.add(key)
def keyReleaseEvent(self, e):
if e.type() == QtCore.QEvent.KeyRelease:
self.npressed -= 1
if self.npressed <= 0:
pt = QtGui.QKeySequence.PortableText
print("New KeySequence:",
QtGui.QKeySequence(*self.keys).toString(pt))
keySequence = QtGui.QKeySequence(*self.keys)
self.setText(keySequence.toString(pt))
self.keys = set()
self.npressed = 0
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
w = KeySequenceEdit('Ctrl+C')
w.show()
sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment