下面的代码创建了单个QTableView
. 有一个QItemDelegate
被指定为 PersistentEditor。创建了两种编辑器:QLineEdit
为第 0 列创建,为第 1 列创建“QComboBox”。
单击时,tableView
我想获取两个编辑器的实例:LineEdit 的实例和组合框的实例。如何做到这一点?
from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])
class Delegate(QtGui.QItemDelegate):
def __init__(self):
QtGui.QItemDelegate.__init__(self)
def createEditor(self, parent, option, index):
if index.column()==0:
lineedit=QtGui.QLineEdit(parent)
return lineedit
elif index.column()==1:
combo=QtGui.QComboBox(parent)
return combo
def setEditorData(self, editor, index):
row = index.row()
column = index.column()
value = index.model().items[row][column]
if isinstance(editor, QtGui.QComboBox):
editor.addItems(['Somewhere','Over','The Rainbow'])
editor.setCurrentIndex(index.row())
if isinstance(editor, QtGui.QLineEdit):
editor.setText('Somewhere over the rainbow')
class Model(QtCore.QAbstractTableModel):
def __init__(self):
QtCore.QAbstractTableModel.__init__(self)
self.items = [[1, 'one', 'ONE'], [2, 'two', 'TWO'], [3, 'three', 'THREE']]
def flags(self, index):
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable
def rowCount(self, parent=QtCore.QModelIndex()):
return 3
def columnCount(self, parent=QtCore.QModelIndex()):
return 3
def data(self, index, role):
if not index.isValid(): return
row = index.row()
column = index.column()
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
return self.items[row][column]
def tableViewClicked(index):
print 'clicked indedx: %s'%index
tableModel=Model()
tableView=QtGui.QTableView()
tableView.setModel(tableModel)
tableView.setItemDelegate(Delegate())
tableView.clicked.connect(tableViewClicked)
for row in range(tableModel.rowCount()):
for column in range(tableModel.columnCount()):
index=tableModel.index(row, column)
tableView.openPersistentEditor(index)
tableView.show()
app.exec_()