0

下面是一个自定义委托的示例QComboBox。当我进行选择时,单击(或以其他方式失去焦点QComboBox),然后 TAB 回到(获得焦点),我失去了我原来的选择。例如,使用下面的代码,如果我选择"Item 2",点击退出,然后 TAB 重新进入,选择将回到"Item 1."

如何维护选择?

我假设发生此问题是因为每次初始化时我都addItem()TheEditor QComboBox课堂上使用它,除非我不太确定应该如何使用此方法。我是否应该TheEditorEditDelegate __ init __课堂上进行初始化,以便它只初始化一次,而不是每次聚焦时?我该如何正确地做到这一点?

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

4

1 回答 1

0

正如 QT Introduction to ( Model/View Programming ) 所说

请注意,我们不需要保留指向编辑器小部件的指针,因为视图会在不再需要时负责销毁它。

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

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
于 2013-07-18T15:58:04.953 回答