QTreeWidgetItem.insertChild 在索引 0

QTreeWidgetItem.insertChild at index 0

我正在尝试在项目组的顶部插入一个新的子项目。索引值似乎没有得到遵守,并且该项目转到列表的末尾。我在 QTreeWidgets 中搜索并没有找到很多此类操作的命中。我确实找到了一个简单的程序来进行实验:

"""
simple test of treewidget
"""
import sys
from PySide2 import QtWidgets

class Testclass():
    """
    test
    """
    def __init__(self):
        """
        test
        """
        app = QtWidgets.QApplication(sys.argv)
        window = QtWidgets.QWidget()
        layout = QtWidgets.QVBoxLayout(window)

        trw = QtWidgets.QTreeWidget()
        trw.setHeaderLabels(['Name', 'Date', 'Cost ($)'])
        chg = QtWidgets.QTreeWidgetItem(trw, ['carrots', None, None])
        datrows = [[None, '2020-00-00', '0.33'],
                   [None, '2020-00-00', '0.35'],
                   [None, '2020-00-00', '0.36']]
        for datrow in datrows:
            __ = QtWidgets.QTreeWidgetItem(chg, datrow)
        __ = chg.insertChild(0, QtWidgets.QTreeWidgetItem(chg, [None, '2020-00-00', '0.30']))


        layout.addWidget(trw)
        window.show()
        sys.exit(app.exec_())

Testclass()

我试过更改树形小部件项中的父引用,更改索引。它添加了一个空白项目,然后在末尾添加了新项目。我唯一得到预期效果的是获取所有项目,将新项目添加到列表顶部并重建树:

"""
simple test of treewidget
"""
import sys
from PySide2 import QtWidgets

class Testclass():
    """
    test
    """
    def __init__(self):
        """
        test
        """
        app = QtWidgets.QApplication(sys.argv)
        window = QtWidgets.QWidget()
        layout = QtWidgets.QVBoxLayout(window)

        trw = QtWidgets.QTreeWidget()
        trw.setHeaderLabels(['Name', 'Date', 'Cost ($)'])
        chg = QtWidgets.QTreeWidgetItem(trw, ['carrots', None, None])
        datrows = [[None, '2020-00-00', '0.33'],
                   [None, '2020-00-00', '0.35'],
                   [None, '2020-00-00', '0.36']]
        for datrow in datrows:
            __ = QtWidgets.QTreeWidgetItem(chg, datrow)
        chi_list = []
        for chgiix, chgii in enumerate(QtWidgets.QTreeWidgetItemIterator(chg)):
            chg_item = chgii.value()
            if chgiix:
                coldata = []
                for colix in range(chg_item.columnCount()):
                    coldata.append(chg_item.text(colix))
                chi_list.append(coldata)
        chi_list.insert(0, [None, '2020-00-00', '0.30'])
        _ = trw.takeTopLevelItem(0)
        chg = QtWidgets.QTreeWidgetItem(trw, ['carrots', None, None])
        for datrow in chi_list:
            __ = QtWidgets.QTreeWidgetItem(chg, datrow)
        print(chi_list)
        layout.addWidget(trw)
        window.show()
        sys.exit(app.exec_())

Testclass()

有更好的方法吗?

问题是您使用了错误的构造函数,例如根据您的代码,您使用的是 this constructor:

QTreeWidgetItem::QTreeWidgetItem(QTreeWidgetItem *parent, const QStringList &strings, int type = Type)
Constructs a tree widget item and append it to the given parent. The given list of strings will be set as the item text for each column in the item.

也就是说,使用 QtWidgets.QTreeWidgetItem(chg, [None, '2020-00-00', '0.30']) 您已经将项目附加为“chg”的 child。

然后正如 insertChild() 指出的那样:

void QTreeWidgetItem::insertChild(int index, QTreeWidgetItem *child)
Inserts the child item at index in the list of children.

If the child has already been inserted somewhere else it won't be inserted again.

(强调我的)

即是"chg"的child则不会插入到开头

解决方案不是传递“chg”而是使用this other constructor:

QTreeWidgetItem::QTreeWidgetItem(const QStringList &strings, int type = Type)
Constructs a tree widget item of the specified type. The item must be inserted into a tree widget. The given list of strings will be set as the item text for each column in the item.

import sys
from PySide2 import QtWidgets


class Testclass:
    def __init__(self):
        app = QtWidgets.QApplication(sys.argv)
        window = QtWidgets.QWidget()
        layout = QtWidgets.QVBoxLayout(window)

        trw = QtWidgets.QTreeWidget()
        trw.setHeaderLabels(["Name", "Date", "Cost ($)"])
        chg = QtWidgets.QTreeWidgetItem(trw, ["carrots", None, None])
        datrows = [
            [None, "2020-00-00", "0.33"],
            [None, "2020-00-00", "0.35"],
            [None, "2020-00-00", "0.36"],
        ]
        for datrow in datrows:
            QtWidgets.QTreeWidgetItem(chg, datrow)
        <b>chg.insertChild(0, QtWidgets.QTreeWidgetItem([None, "2020-00-00", "0.30"]))</b>

        layout.addWidget(trw)
        window.show()
        sys.exit(app.exec_())


Testclass()