在QStyledItemDelegate中正确使用信号closeEditor的方法?

1 投票
1 回答
2093 浏览
提问于 2025-04-16 17:25

我正在重写QStyledItemDelegate这个类,并重新实现eventFilter函数,这样我就可以在检测到按下Tab键时自定义编辑器的行为。不过,下面的代码没有起作用。请问正确的方式是什么来触发closeEditor信号?

class CustomDelegate(QStyledItemDelegate):
    def __init__(self, parent=None):
        super(CustomDelegate, self).__init__(parent)

    def eventFilter(self, editor, event):
        if (event.type() == QEvent.KeyPress and
            event.key() == Qt.Key_Tab):
            print "Tab captured in editor"
            self.commitData.emit(editor) #This is working
            self.closeEditor.emit(editor) #This does not seem to do anything??
            return True
        return QStyledItemDelegate.eventFilter(self,editor,event)

1 个回答

4

这是一个老问题,但我刚遇到同样的情况,所以找到了这个问题。

我通过把

self.closeEditor.emit(editor)

这一行改成

self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint)来解决了。

这里的 commitData 调用会执行 setModelData。如果你不调用 closeEditor,那么 setModelData 会再次被调用,因为编辑器本身会关闭。

撰写回答