setData for second column of QstandardItem

2.6k views Asked by At

How can i set the data for the second column of a QStandardItem which i then add to a QTreeview?

In my case I just want to place a checkbox or text for the sake of example.

enter image description here

enter image description here

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

There are 1 answers

0
ekhumoro On BEST ANSWER

You can pass a list of items to appendRow, with each item representing a column:

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