如何使用QItemDelegate将QComboBox添加到QTreeView

时间:2018-11-16 19:23:28

标签: python qtreeview qitemdelegate

如何使用Pyside中的QitemDelegate将QComboBox添加到QTreeView中指定行的第二列?

此屏幕截图演示了我的目标是

enter image description here

到目前为止,我有这个:

enter image description here

这是我的代码,我的目标是复制上图中显示的内容:

import sys
from PySide import QtGui, QtCore

items = {
    'Category A': {
        'Fruit' : ['Oranges', 'Watermellons', 'Apples'],
        'Vegetables' : ['Peppers','Potatoes','Carrots']
    },
    'Category B': {
        'Sweets' : ['Donuts', 'Icecream', 'Candies']
    }
}


class Window(QtGui.QDialog):

    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.resize(400,400)

        # controls
        self.button = QtGui.QPushButton('Print')
        self.treeview = QtGui.QTreeView()
        self.treeview.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.treeview.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self.treeview.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.treeview.setModel(QtGui.QStandardItemModel())

        # layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.treeview)
        layout.addWidget(self.button)
        self.setLayout(layout)

        # populate ui
        self.populate_treeview()


    def populate_treeview(self):
        model = self.treeview.model()
        self.treeview.setSortingEnabled(False)

        for catKey, catValues in items.items():
            print catKey
            item = QtGui.QStandardItem()
            fnt = item.font()
            fnt.setBold(True)
            item.setFont(fnt)
            item.setCheckable(False)
            item.setData(catKey, role=QtCore.Qt.UserRole)
            item.setData(catKey, role=QtCore.Qt.DisplayRole)

            for key, keyValues in catValues.items():
                print '\t', key, keyValues
                itemName = QtGui.QStandardItem()
                itemName.setCheckable(False)
                itemName.setData(key, role=QtCore.Qt.UserRole)
                itemName.setData(key, role=QtCore.Qt.DisplayRole)
                item.appendRow(itemName)

            model.appendRow(item)

        self.treeview.setSortingEnabled(True)
        self.treeview.sortByColumn(0, QtCore.Qt.AscendingOrder)
        self.treeview.expandAll()


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    win = Window()
    win.show()
    app.exec_()

0 个答案:

没有答案