在QStyledItemDeleg下维护QComboBox的选择

2024-04-26 00:03:50 发布

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

下面是一个自定义委托QComboBox的示例。当我做出选择时,单击out(或者用QComboBox键失去焦点),然后按TAB键返回(gain focus),我就失去了原来的选择。例如,使用下面的代码,如果我选择"Item 2",单击out,然后TAB back in,选择将返回"Item 1."

如何维护选择?

我假设发生此问题是因为每次初始化TheEditorQComboBox类中都使用addItem(),除非我不太确定应该如何处理这个方法。我是否应该在EditDelegate__ init __类中初始化TheEditor,以便它只初始化一次而不是每次都初始化它?我该怎么做?在

import sys
from PySide import QtCore, QtGui, QtSql

class EditDelegate(QtGui.QStyledItemDelegate):
    def __init__(self, parent=None):
            super(EditDelegate, self).__init__(parent)
    def createEditor(self, parent, option, index):
            editor = TheEditor(parent)                  
            return editor

class TheEditor(QtGui.QComboBox):
    def __init__(self, parent=None):
            super(TheEditor, self).__init__(parent)
            self.addItem("Item 1")
            self.addItem("Item 2")
            self.addItem("Item 3")
            self.setEditable(True)

class TheTable(QtGui.QTableWidget):
    def __init__(self, columns, parent=None):
            super(TheTable, self).__init__(parent)
            self.setItemDelegate(EditDelegate())
            self.setEditTriggers(QtGui.QAbstractItemView.AllEditTriggers)
            self.setColumnCount(1)
            self.setRowCount(1)
            self.setHorizontalHeaderLabels(["QCombo"])

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)
            self.setCentralWidget(TheTable(self))

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    frame = MainWindow()
    frame.show()
    app.exec_()

注:PySide v1.2.0


Tags: selfnoneinitdefitemclassparentsuper
1条回答
网友
1楼 · 发布于 2024-04-26 00:03:50

正如QT介绍(Model/View Programming)所说

Note that we do not need to keep a pointer to the editor widget because the view takes responsibility for destroying it when it is no longer needed.

编辑器是临时对象。但您可以尝试从旧编辑器中捕获选定内容并将其传递给新编辑器,如下所示:

class EditDelegate(QtGui.QStyledItemDelegate):
    editorsLastIndex=None
    def __init__(self, parent=None):
        super(EditDelegate, self).__init__(parent)
    def createEditor(self, parent, option, index):
        editor = TheEditor(parent)             
        if self.editorsLastIndex != None:
            editor.setCurrentIndex(self.editorsLastIndex)
        editor.currentIndexChanged.connect(self.editorIndexChanged)
        return editor
    def editorIndexChanged(self, index):
        self.editorsLastIndex = index

相关问题 更多 >