In C++ you would have to install an event filter, probably with PyQt this is similar (overwrite virtual bool eventFilter(QObject* pObject, QEvent* pEvent); in your editor class). CTRL-Z gets probably filtered by the QTextEdit event filter thus it never gets to keyPressEvent.
QTextEdit: Overwrite Ctrl-Z with undo() in PyQt4
Question
I subclassed QTextEdit
class Q_My_TextEdit(QtGui.QTextEdit):
def __init__(self, *args):
QtGui.QTextEdit.__init__(self, *args)
def undo(self):
print("undo")
#my own undo code
In my other class:
self.textedit=Q_My_TextEdit()
def keyPressEvent(self,event):
if event.key()==(Qt.Key_Control and Qt.Key_Z):
self.textedit.undo()
If you type some text into your QTextEdit, and hit CTRL-Z, it gets undo-ed, but without calling the function "undo". So how does it work in detail?
The background is, in a second step I want to set new Text (setText()), so the undo stack is deleted. I already have running code that makes the undo itself, but I can't trigger it on CTRL-Z, because with the "Z" the keyshortcut is somehow reserved. For example, if I call my own undo with event.key()==(Qt.Key_Control and Qt.Key_Y)
, it works.
Solution 2
OTHER TIPS
Ah, So additionally to the keyPressEvent which I have in my second class, you have to put it also into the Subclass!
class Q_My_TextEdit(QtGui.QTextEdit):
def __init__(self, *args):
QtGui.QTextEdit.__init__(self, *args)
def keyPressEvent(self,event):
if event.key()==(Qt.Key_Control and Qt.Key_Z):
self.undo()
#To get the remaining functionality back (e.g. without this, typing would not work):
QTextEdit.keyPressEvent(self,event)
def undo(self):
print("undo")
#my own undo code
But now I can't type into my textedit any more! How can I solve this?
--> Solved. See Properly handling a keyPressEvent in a Subclassed PyQT LineEdit