Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How can I replace the default action for QTextEdit's Ctrl + Z shortcut?



  • Hi!

    I want to replace my QTextEdit's default Ctrl + Z action with one of my own. For some reason overriding the function did not work.

    If I simply add a shortcut as I would normally do if it didn't already exist, it works for, say, "Ctrl+M" but not "Ctrl+Z". I am assuming this is because it is already assigned. How can I disable it?

    Thanks a lot!


  • Lifetime Qt Champion

    Hi,

    Which function did you override ?



  • Thanks a lot for replying!

    "undo". Is that not the right one?


  • Lifetime Qt Champion

    That method is not virtual so you can't do that.

    Depending on what you wan't to do, you can re-implement the keyPressEvent method and catch there the QKeySequence::Undo.

    Just take into account that your users will likely be very surprised if undo does not do its job in a standard fashion.



  • Thanks for the advice. This will only be used internally!

    Do I just do

    if event.key() == QKeySequence.Undo:
    

    or do I check for Z and the Ctrl modifier?

            if event.key() == Qt.Key_Z:
                modifiers = QApplication.keyboardModifiers()
    
                if modifiers == Qt.Key_Control:
                    print('here')
    

    Neither one worked, unfortunately


  • Lifetime Qt Champion

    Even if internal, your coworkers may come at you with pitchforks and torches ;-)

    You should use the matches function.



  • Unfortunately the following did not work either. The two key checks below work just fine:

        def key_pressed_event(self, event):
            if event.matches(QKeySequence.Undo):
                print('here')
    
            if event.key() == Qt.Key_Shift:
                if self.underMouse():
                    self.toggle_paragraph_select()
    
            elif event.key() == Qt.Key_Alt:
                if self.underMouse():
                    self.toggle_clicked_word()
    

    key_pressed_event is called by keyPressEvent in my main window.


  • Lifetime Qt Champion

    You should implement that in a subclass of QTextEdit.


Log in to reply