1

如何为 QStandardItem 的第二列设置数据,然后将其添加到 QTreeview?

以我为例,我只想放置一个复选框或文本。

在此处输入图像描述

在此处输入图像描述

import sys
from PySide import QtGui, QtCore

class Browser(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Browser, self).__init__(parent)

        self.initUI()

    def initUI(self):
        self.resize(200, 300)
        self.setWindowTitle('Assets')

        self.items_model = QtGui.QStandardItemModel()
        self.ui_items = QtGui.QTreeView()
        self.ui_items.setAlternatingRowColors(True)
        self.ui_items.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.ui_items.header().setResizeMode(QtGui.QHeaderView.ResizeToContents)
        self.ui_items.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self.ui_items.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.ui_items.setModel(self.items_model)

        grid = QtGui.QGridLayout()
        grid.setContentsMargins(0, 0, 0, 0)
        grid.addWidget(self.ui_items, 0, 0)
        self.setLayout(grid)

        self.update_model()

    def update_model(self):
        model = self.ui_items.model()
        model.clear()
        model.setHorizontalHeaderLabels(['Assets'])

        # Create Data
        for i in range(1,5):
            root = QtGui.QStandardItem()
            root.setData('Apple', role=QtCore.Qt.DisplayRole)
            root.setColumnCount(2)


            model.appendRow(root)

        self.ui_items.expandAll()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = Browser()
    ex.show()
    sys.exit(app.exec_())
4

1 回答 1

2

您可以将项目列表传递给appendRow,每个项目代表一列:

# Create Data
for i in range(1,5):
    column1 = QtGui.QStandardItem('Apple')
    column2 = QtGui.QStandardItem('Orange')
    column2.setCheckable(True)
    model.appendRow([column1, column2])
于 2017-01-09T04:38:07.720 回答