我的项目需要你的宝贵知识;我需要做一个至少有3列的树。我所拥有的是一个"Actions"列表,如下所示:
typedef struct Action
{
int ID;
int parentID;
char* ident;
char* text;
}
"Actions"列表(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和相应的标识/文本之间的链接。
生成树(第一列)的代码:
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
我终于找到了如何使用更容易的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();