我正在用 Qt(使用 C++)编写一个应用程序,我需要在树视图中表示一个对象结构.一种方法是为此创建一个模型,但在阅读了有关该主题的 Qt 文档后,我仍然很困惑.
I'm writing an application in Qt (with C++) and I need to represent an object structure in a tree view. One of the ways to do this is to create a model for this, but I'm still quite confused after reading the Qt documentation about the subject.
我拥有的结构"非常简单 - 有一个 Project
对象,它在 std::vector
容器中保存 Task
对象.这些任务也可以包含子任务.
The "structure" I have is pretty simple - there's a Project
object that holds Task
objects in a std::vector
container. These tasks can also hold child tasks.
我已经编写了读取 & 的方法使用 Qt 的 XML 类将这些项目写入/从 XML 文件写入.
I've already written methods to read & write these projects to/from XML files using Qt's XML classes.
是否有更多文档或推荐阅读"可用于从头开始创建模型?您建议我如何开始实施?
Is there any more documentation or "recommended reading" for creating models from scratch? How do you recommend I start implementing this?
作为 Virgil 在对该问题的评论中所说的替代方案,您可以使用 QStandardItemModel 类用于您的模型,然后使用此类构建您的树.下面是一个例子:
As an alternative to what was said by Virgil in a comment to the question, you could use QStandardItemModel class for your model and just build your tree using this class. Below is an example:
QStandardItemModel* model = new QStandardItemModel();
QStandardItem* item0 = new QStandardItem(QIcon("test.png"), "1 first item");
QStandardItem* item1 = new QStandardItem(QIcon("test.png"), "2 second item");
QStandardItem* item3 = new QStandardItem(QIcon("test.png"), "3 third item");
QStandardItem* item4 = new QStandardItem("4 forth item");
model->appendRow(item0);
item0->appendRow(item3);
item0->appendRow(item4);
model->appendRow(item1);
ui->treeView->setModel(model);
当UI(视图)被销毁时,删除model
.文档:
When the UI (view) is destroyed, delete model
. Documentation:
这篇关于为树视图创建 Qt 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!