简体   繁体   English

QStandardItem 不在第一行添加子项

[英]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.重要提示:在创建项目的上下文中,我无权访问 model。

窗口截图

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:从您想要获得的内容可以清楚地看出,“sub_item”不是“my_item”的子项,而是兄弟项,因此您必须使用以下代码添加它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM