Kos
Kos

Reputation: 11

QStandardItem doesn't add children on first row

Apparently, setting an item on the same row but on a new column, always adds a new row.

from PySide2 import QtCore, QtWidgets, QtGui

# Items for the first row
my_item = QtGui.QStandardItem('Row 0, Col 0')
sub_item = QtGui.QStandardItem('Row 0, Col 1')

# This should add my sub item on the row 0...
my_item.setChild(0, 1, sub_item)

# Model and view
view = QtWidgets.QTreeView()
model = QtGui.QStandardItemModel()
model.setHorizontalHeaderLabels(['col1', 'col2'])
view.setModel(model)


model.appendRow(my_item)    
view.show()

What I really want, is having my data in a single row, not adding a new row for displaying columns.

Important note: I don't have access to the model in the context I'm creating the Items.

Window screenshot

Upvotes: 1

Views: 326

Answers (1)

eyllanesc
eyllanesc

Reputation: 244282

From what you want to obtain it is clearly observed that "sub_item" is not a child of "my_item" but a sibling so you must add it using the following code:

from PySide2 import QtCore, QtWidgets, QtGui


if __name__ == "__main__":

    app = QtWidgets.QApplication()

    # Items for the first row
    my_item = QtGui.QStandardItem("Row 0, Col 0")
    sub_item = QtGui.QStandardItem("Row 0, Col 1")

    # Model and view
    view = QtWidgets.QTreeView()
    model = QtGui.QStandardItemModel()
    model.setHorizontalHeaderLabels(["col1", "col2"])
    view.setModel(model)

    model.appendRow([my_item, sub_item])
    view.show()

    app.exec_()

Upvotes: 1

Related Questions