为树视图创建 Qt 模型

2023-10-18C/C++开发问题
1

本文介绍了为树视图创建 Qt 模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在用 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:

  • https://doc.qt.io/qt-5/qstandarditemmodel.html
  • https://doc.qt.io/qt-5/qstandarditem.html

这篇关于为树视图创建 Qt 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6