我试图创建一个QTreeView,它应该在某个列的每一行上保存一个QComboBox,以便我可以从一个字符串列表中选择一个单元格的数据。我想做的是像
item = QtGui.QStandardItem(QtGui.QComboBox())
但这显然是不可能的。
这在GTK +工具包中相当容易,所以我想在Qt4中也应该可行。如果不是(容易)可能的话,会有什么选择呢?
目前,我没有代码可呈现。有人可以暗示去哪个方向吗? 我在python中编写代码。
答案 0 :(得分:0)
显然委派编辑角色是可行的方法。在剪切和粘贴并编辑我发现的例子后,我有一些工作:
import sys
from PyQt4 import QtGui, QtCore
class MyModel(QtGui.QStandardItemModel):
def __init__(self):
super(QtGui.QStandardItemModel, self).__init__()
self.setColumnCount(3)
self.setHorizontalHeaderLabels(['Col 1', 'Col2 2', 'Col 3'])
def setData(self, index, value, role=QtCore.Qt.DisplayRole):
item = self.itemFromIndex(index)
item.setData(value, role=QtCore.Qt.DisplayRole)
class ComboDelegate(QtGui.QItemDelegate):
def __init__(self, parent):
QtGui.QItemDelegate.__init__(self, parent)
def createEditor(self, parent, option, index):
combo = QtGui.QComboBox(parent)
combo.addItem('a')
combo.addItem('b')
combo.addItem('c')
combo.addItem('t')
combo.addItem('w')
return combo
def setEditorData(self, editor, index):
text = index.data().toString()
index = editor.findText(text)
editor.setCurrentIndex(index)
def setModelData(self, editor, model, index):
model.setData(index, editor.itemText(editor.currentIndex()))
def updateEditorGeometry(self, editor, option, index):
print option, option.rect
editor.setGeometry(option.rect)
def row_clicked(model_index):
row = model_index.row()
print model_index.data(0).toString()
if __name__ == '__main__':
myapp = QtGui.QApplication(sys.argv)
model = MyModel()
view = QtGui.QTreeView()
view.setUniformRowHeights(True)
view.setModel(model)
view.setItemDelegateForColumn(1, ComboDelegate(view))
view.show()
view.pressed.connect(row_clicked)
for n in [['q','w','e'],['r','t','y']]:
item_a = QtGui.QStandardItem(unicode(n[0]))
item_b = QtGui.QStandardItem(unicode(n[1]))
item_c = QtGui.QStandardItem(unicode(n[2]))
model.appendRow([item_a, item_b, item_c])
for row in range(0, model.rowCount()):
view.openPersistentEditor(model.index(row, 1))
myapp.exec_()
现在,问题是当我使用组合框来更改模型项的数据时,视图行的行高与组合的高度不匹配,直到我调整窗口大小。怎么了?