在QTreeView中使用QComboBox?

1 投票
1 回答
1259 浏览
提问于 2025-05-01 02:58

我想创建一个QTreeView,在某一列的每一行上放一个QComboBox,这样我就可以从一个字符串列表中选择单元格的数据。我想做的事情大概是这样的:

item = QtGui.QStandardItem(QtGui.QComboBox())

但这显然是不可能的。

在GTK+工具包中,这个操作相对简单,所以我觉得在Qt4中也应该可以做到。如果不(容易)实现,那有什么替代的方法吗?

目前我没有代码可以展示。有人能给我一些方向上的提示吗?我是在用python写代码。

暂无标签

1 个回答

1

看起来把编辑器的角色交给别人是个不错的选择。在我剪切、粘贴和编辑一些找到的例子后,我终于搞定了一些东西:

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_()

现在,问题是当我使用下拉框来更改模型项的数据时,视图中行的高度和下拉框的高度不一致,直到我调整窗口大小。这个问题出在哪里呢?

撰写回答