Qt/PyQt/PySide:重新实现QLineEdit子类的撤消框架时出现问题

2024-04-18 07:14:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个自定义行编辑小部件,这样我就可以将其上的撤消/重做命令合并到应用程序的常规撤消堆栈中(而不是使用QLineEdit小部件附带的内置撤消/重做功能)。撤销/重做逻辑相当简单:当line edit小部件接收到焦点时,它的内容会立即分配给一个实例变量(self.init_文本);以及当line edit小部件失去焦点时,如果文本内容与存储在self.init_文本,然后创建一个新的QUndoCommand对象。undo()方法将把内容重新设置为self.init_文本,而redo()方法会将内容重新设置为当line edit小部件失去焦点时捕获的内容。(在这两种方法中,line edit将再次获得焦点,这样用户就可以清楚地看到undo或redo命令实际影响了什么。)

它似乎工作得很好,但有一个例外:如果用户非常快地通过qpushbutton循环执行undo或redo命令,那么框架就会崩溃。我无法更好地描述它,因为我不确定Qt引擎盖下发生了什么,但是,例如,qndostack的count()可能会被完全更改。应用程序继续运行,终端上没有报告错误,但它仍然是一个损坏的撤消堆栈。在

我已经创建了一个小QDialog应用程序,你可以尝试重新创建问题。(使用Python 2.7.3/PySide 1.2.1。。。如果您安装了最近的PyQt绑定,我认为除了前两个import语句之外,您不需要替换任何内容。)例如,在第一个选项卡的QLineEdit中,如果您键入“hello”,然后键入tab out,然后单击back in并键入“world”,然后再次单击tab out,尝试非常迅速地单击undo按钮(向下或超出undo堆栈的底部)和redo按钮(直到undo堆栈顶部)。对我来说,这足以打破它。在

#!/usr/bin/python
#coding=utf-8
from PySide.QtCore import *
from PySide.QtGui import *
import sys

class CustomRightClick(QObject):

    customRightClicked = Signal()

    def __init__(self, parent=None):
        QObject.__init__(self, parent)

    def eventFilter(self, obj, event):
        if event.type() == QEvent.ContextMenu:
            # emit signal so that your widgets can connect a slot to that signal
            self.customRightClicked.emit()
            return True
        else:
            # standard event processing
            return QObject.eventFilter(self, obj, event)

class CommandLineEdit(QUndoCommand):

    def __init__(self, line_edit, init_text, tab_widget, tab_index, description):
        QUndoCommand.__init__(self, description)
        self._line_edit = line_edit
        self._current_text = line_edit.text()
        self._init_text = init_text
        self._tab_widget = tab_widget
        self._tab_index = tab_index

    def undo(self):
        self._line_edit.setText(self._init_text)
        self._tab_widget.setCurrentIndex(self._tab_index)
        self._line_edit.setFocus(Qt.OtherFocusReason)

    def redo(self):
        self._line_edit.setText(self._current_text)
        self._tab_widget.setCurrentIndex(self._tab_index)
        self._line_edit.setFocus(Qt.OtherFocusReason)

class CustomLineEdit(QLineEdit):

    def __init__(self, parent, tab_widget, tab_index):
        super(CustomLineEdit, self).__init__(parent)
        self.parent = parent
        self.tab_widget = tab_widget
        self.tab_index = tab_index
        self.init_text = self.text()
        self.setContextMenuPolicy(Qt.CustomContextMenu)

        undoAction=QAction("Undo", self)
        undoAction.triggered.connect(self.parent.undo_stack.undo)

        self.customContextMenu = QMenu()
        self.customContextMenu.addAction(undoAction)

        custom_clicker = CustomRightClick(self)
        self.installEventFilter(custom_clicker)
        self.right_clicked = False
        custom_clicker.customRightClicked.connect(self.menuShow)

    def menuShow(self):
        self.right_clicked = True   # set self.right_clicked to True so that the focusOutEvent won't push anything to the undo stack as a consequence of right-clicking
        self.customContextMenu.popup(QCursor.pos())
        self.right_clicked = False

    # re-implement focusInEvent() so that it captures as an instance variable the current value of the text *at the time of the focusInEvent(). This will be utilized for the undo stack command push below
    def focusInEvent(self, event):
        self.init_text = self.text()
        QLineEdit.focusInEvent(self, event)

    # re-implement focusOutEvent() so that it pushes the current text to the undo stack.... but only if there was a change!
    def focusOutEvent(self, event):
        if self.text() != self.init_text and not self.right_clicked:
            print "Focus out event. (self.text is %s and init_text is %s). Pushing onto undo stack. (Event reason is %s)" % (self.text(), self.init_text, event.reason())
            command = CommandLineEdit(self, self.init_text, self.tab_widget, self.tab_index, "editing a text box")
            self.parent.undo_stack.push(command)
        QLineEdit.focusOutEvent(self, event)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Z:
            if event.modifiers() & Qt.ControlModifier:
                self.parent.undo_stack.undo()
            else:
                QLineEdit.keyPressEvent(self, event)
        elif event.key() == Qt.Key_Y:
            if event.modifiers() & Qt.ControlModifier:
                self.parent.undo_stack.redo()
            else:
                QLineEdit.keyPressEvent(self, event)
        else:
            QLineEdit.keyPressEvent(self, event)

class Form(QDialog):

    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.undo_stack = QUndoStack()

        self.tab_widget = QTabWidget()

        self.line_edit1 = CustomLineEdit(self, self.tab_widget, 0)
        self.line_edit2 = CustomLineEdit(self, self.tab_widget, 1)
        self.undo_counter = QLineEdit()

        tab1widget = QWidget()
        tab1layout = QHBoxLayout()
        tab1layout.addWidget(self.line_edit1)
        tab1widget.setLayout(tab1layout)

        tab2widget = QWidget()
        tab2layout = QHBoxLayout()
        tab2layout.addWidget(self.line_edit2)
        tab2widget.setLayout(tab2layout)

        self.tab_widget.addTab(tab1widget, "Tab 1")
        self.tab_widget.addTab(tab2widget, "Tab 2")

        self.undo_button = QPushButton("Undo")
        self.redo_button = QPushButton("Redo")
        layout = QGridLayout()
        layout.addWidget(self.tab_widget, 0, 0, 1, 2)
        layout.addWidget(self.undo_button, 1, 0)
        layout.addWidget(self.redo_button, 1, 1)
        layout.addWidget(QLabel("Undo Stack Counter"), 2, 0)
        layout.addWidget(self.undo_counter)
        self.setLayout(layout)

        self.undo_button.clicked.connect(self.undo_stack.undo)
        self.redo_button.clicked.connect(self.undo_stack.redo)
        self.undo_stack.indexChanged.connect(self.changeUndoCount)

    def changeUndoCount(self, index):
        self.undo_counter.setText("%s / %s" % (index, self.undo_stack.count()))

app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

这是Qt窃听器吗?PySide虫?或者我的重新执行有问题吗?感谢任何帮助!在

(我在查看代码时突然想到,与其安装事件过滤器,不如重新实现contextMenuEvent,但我想这与问题没有关系。)


Tags: textselfeventindexinitstackdefline
1条回答
网友
1楼 · 发布于 2024-04-18 07:14:36

出现此问题的原因是您正在撤消/重做期间设置QLineEdit的焦点。documentation表示当命令被推送到QUndoStack时,redo会被调用,因此一旦您从QLineEdit中移除焦点(比如单击“撤消”时),焦点将立即通过自动调用redo恢复。在此之后,undo命令运行(由我刚才提到的单击按钮触发)。由于小部件已经有焦点,当从undo调用_line_edit.setFocus()时,line editfocusInEvent方法不运行,因此_line_edit.init_text没有得到适当的更新。这意味着当您单击redo按钮时,行编辑将失去焦点,并且一个新命令将排队,因为focusOutEventif语句中的比较被中断,因为init_text存储了不正确的值。然后,一个新的命令被添加到撤消堆栈中,它将覆盖您试图恢复的堆栈!在

有道理吗?在

一个简单的解决方案是在设置_line_edit的文本之后,向CommandLineEdit中的undo/redo方法添加以下行。在

def undo(self):
    self._line_edit.setText(self._init_text)
    self._line_edit.init_text = self._line_edit.text()
    self._tab_widget.setCurrentIndex(self._tab_index)
    self._line_edit.setFocus(Qt.OtherFocusReason)

def redo(self):
    self._line_edit.setText(self._current_text)
    self._line_edit.init_text = self._line_edit.text()
    self._tab_widget.setCurrentIndex(self._tab_index)
    self._line_edit.setFocus(Qt.OtherFocusReason)

然后可以删除focusInEvent的重新实现。在

一旦你仔细考虑了这个问题,也许值得从头开始构建撤销框架的架构,而不是尝试实现我的“hacky”解决方案,因为可能有更干净的方法来解决它!在

相关问题 更多 >