QstandardItem 的第二列的 setData

setData for second column of QstandardItem

如何为 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_())

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

# Create Data
for i in range(1,5):
    column1 = QtGui.QStandardItem('Apple')
    column2 = QtGui.QStandardItem('Orange')
    column2.setCheckable(True)
    model.appendRow([column1, column2])