下面是一个自定义委托QComboBox
的示例。当我做出选择时,单击out(或者用QComboBox
键失去焦点),然后按TAB键返回(gain focus),我就失去了原来的选择。例如,使用下面的代码,如果我选择"Item 2"
,单击out,然后TAB back in,选择将返回"Item 1."
如何维护选择?
我假设发生此问题是因为每次初始化TheEditor
QComboBox
类中都使用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
正如QT介绍(Model/View Programming)所说
编辑器是临时对象。但您可以尝试从旧编辑器中捕获选定内容并将其传递给新编辑器,如下所示:
相关问题 更多 >
编程相关推荐