我想这样做,以便可以将第三级(子级)扩展到顶层项(根)下的一个子级。我所能做的就是让多个孩子成为一个根。
这是在我的.cpp中
QStringList string1, string2;
string1 << "xxxxxxxx" << "xxxxxxxxxxx";
string2 << "yyyyyy" << "yy";
m_treeWidget->insertTopLevelItem(0, new QTreeWidgetItem(string1));
m_treeWidget->insertTopLevelItem(1, new QTreeWidgetItem(string2));
//here I add a child
AddChild(m_treeWidget->topLevelItem(0),"hello","world", m_treeWidget);
//here I make two attempts to make a sub child
AddChild(m_treeWidget->itemBelow(m_treeWidget->topLevelItem(0)),"hello_sub1","world_sub1", m_treeWidget);
AddChild(m_treeWidget->itemAt(0,0),"hello_sub2","world_sub2", m_treeWidget);
以下是我在同一.cpp文件中的“添加子方法”:
void Dialog::AddChild (QTreeWidgetItem *parent, QString name, QString Description, QTreeWidget* treeWidget)
{
QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget);
item->setText(0,name);
item->setText(1, Description);
parent->addChild(item);
}
最佳答案
为了建立树层次结构,可以使用QTreeWidgetItem
的API,尤其是其构造函数。构造函数可以接受QTreeWidget
或QTreeWidgetItem
作为父对象。在第一种情况下,顶层项目将被添加到树小部件,在第二种情况下,另一项目的子项将被添加。此API易于使用,因为您无需将任何项目显式地附加到树小部件。这是实现该想法的示例代码:
QStringList string1, string2;
string1 << "xxxxxxxx" << "xxxxxxxxxxx";
string2 << "yyyyyy" << "yy";
QTreeWidget tv;
// The top level items
QTreeWidgetItem *top1 = new QTreeWidgetItem(&tv, string1);
QTreeWidgetItem *top2 = new QTreeWidgetItem(&tv, string2);
// A child item.
QTreeWidgetItem *child1 =
new QTreeWidgetItem(top1, QStringList() << "Hello" << "World");
// The grandchildren.
new QTreeWidgetItem(child1, QStringList() << "Hello_sub1" << "World_sub1");
new QTreeWidgetItem(child1, QStringList() << "Hello_sub2" << "World_sub2");
关于c++ - 如何在QTreeWidget中为 child 创建子 child ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24660029/