我需要你宝贵的知识用于我的项目;) 我需要用至少3列做一棵树。 我所拥有的是一系列"行动"如下:
typedef struct Action
{
int ID;
int parentID;
char* ident;
char* text;
}
"行动" list(pListActions)如下所示:
ID ParentID ident text
1 0 "root" "this is my root"
2 1 "element1" "1st element"
3 1 "element2" "2nd element"
4 0 "root2" "this is another root"
...
...
我可以使用我的代码生成相应的树:
ID ident text
1
|-2
|-3
4
正如您所看到的,我只有第一列,但我需要有其他列。 我尝试过使用setItem方法,但我不知道如何找到正确的行... 事实上我需要"链接"一行的所有内容;如果我插入一个新行,我想保留ID和相应的标识/文本之间的链接。
生成树的代码(第1列):
QStandardItemModel *standardModel = new QStandardItemModel; //My model for the tree
standardModel->setColumnCount(3);
QStandardItem *rootNode = standardModel->invisibleRootItem();
for (auto it=std::begin(*this->pListActions);it!=std::end(*this->pListActions);it++) //I add all the elements in my list of actions
{
Action* pa = *it;
QStandardItem *myNewItem= new QStandardItem(QString::number(pa->ID)); //The new item ID
myNewItem->setCheckable(1);
//Looking for a potential parent (with the action->parentID value
//FindItemParent is the index of the element il the standardModel with the same ID as the current parentID (only one or zero because the ID is unique)
QModelIndexList FindItemParent= standardModel->match(standardModel->index(0,0),Qt::DisplayRole,QVariant::fromValue(QString::number(pa->parentID)),2,Qt::MatchRecursive);
if(!FindItemParent.empty())//If a parent exists
{
standardModel->itemFromIndex(FindItemParent.front())->appendRow(myNewItem);//add the current item to the parent in the standardModel
}
else { //No parents
rootNode->appendRow(myNewItem); //add the element to the root
}
}
//drawing the tree
QTreeView *tree = new QTreeView; //Arbre affiché à l'aide du QTreeView
tree->setModel(standardModel);
tree->expandAll();
tree->show();
我希望得到最终结果:
ID ident text
1 root this is my root
|-2 element1 1st element
|-3 element2 2nd element
4 root2 this is another root
答案 0 :(得分:0)
我终于找到了如何使用更容易的QTreeWidget。 以下是如何做到这一点:
QTreeWidget *finalTree = new QTreeWidget;
finalTree->setColumnCount(3);
QTreeWidgetItem *root = new QTreeWidgetItem; //Racine de la séquence
root->setText(0,"ROOT");
finalTree->addTopLevelItem(root);
for (auto it=std::begin(*this->pListActions);it!=std::end(*this->pListActions);it++)
{
Action* pa = *it;
QTreeWidgetItem *myNewItem = new QTreeWidgetItem;
myNewItem->setText(0,QString::number(pa->ID));
myNewItem->setText(1,pa->ident);
myNewItem->setText(1,pa->type);
QList<QTreeWidgetItem*> foundAParent;
foundAParent = finalTree->findItems(QString::number(pa->parentID),Qt::MatchContains | Qt::MatchRecursive,0);
if (!foundAParent.empty())
{
foundAParent.front()->addChild(myNewItem);
}
else
{
root->addChild(myNewItem);
}
finalTree->addTopLevelItem(root);
}
finalTree->show();