【问题标题】:QTextEdit: Overwrite Ctrl-Z with undo() in PyQt4QTextEdit:在 PyQt4 中用 undo() 覆盖 Ctrl-Z
【发布时间】:2013-08-02 09:42:21
【问题描述】:

我继承了 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

在我的其他班级:

self.textedit=Q_My_TextEdit()

def keyPressEvent(self,event):
    if event.key()==(Qt.Key_Control and Qt.Key_Z):
        self.textedit.undo()

如果您在 QTextEdit 中键入一些文本,然后按 CTRL-Z,它会被撤消,但不会调用函数“撤消”。那么具体是如何工作的呢?

背景是,在第二步中我想设置新文本(setText()),所以撤消堆栈被删除。我已经运行了可以自行撤消的代码,但我无法在 CTRL-Z 上触发它,因为使用“Z”键快捷键以某种方式被保留。例如,如果我用event.key()==(Qt.Key_Control and Qt.Key_Y) 调用我自己的撤消,它就可以工作。

【问题讨论】:

    标签: python qt pyqt undo


    【解决方案1】:

    啊,所以除了我第二堂课的 keyPressEvent 之外,你还必须把它放到子类中!

    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
    

    但是现在我不能再输入我的文本编辑器了!我该如何解决这个问题?

    --> 已解决。见Properly handling a keyPressEvent in a Subclassed PyQT LineEdit

    【讨论】:

      【解决方案2】:

      在 C++ 中,您必须安装一个事件过滤器,可能与 PyQt 类似(在您的编辑器类中覆盖 virtual bool eventFilter(QObject* pObject, QEvent* pEvent);)。 CTRL-Z 可能会被 QTextEdit 事件过滤器过滤,因此它永远不会到达 keyPressEvent。

      【讨论】:

      • 感谢您的回答!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 2011-09-26
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 2021-06-17
      相关资源
      最近更新 更多