我的项目需要您的宝贵知识;)我需要制作一棵至少有 3 列的树。我所拥有的是一个“操作”列表,如下所示:
typedef struct Action
{
int ID;
int parentID;
char* ident;
char* text;
}
“动作”列表 (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 和相应的 ident/text 之间的链接。
我生成树的代码(第一列):
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