Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Qt models for tree views

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.

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.

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?

like image 208
Veeti Avatar asked Dec 31 '09 16:12

Veeti


People also ask

What is QTreeView?

A QTreeView implements a tree representation of items from a model. This class is used to provide standard hierarchical lists that were previously provided by the QListView class, but using the more flexible approach provided by Qt's model/view architecture.

What is QModelIndex?

The QModelIndex class is used to locate data in a data model.

What is a widget in Qt?

Widgets are the primary elements for creating user interfaces in Qt. Widgets can display data and status information, receive user input, and provide a container for other widgets that should be grouped together. A widget that is not embedded in a parent widget is called a window.

What is a view in Qt?

Model/View is a technology used to separate data from views in widgets that handle data sets. Standard widgets are not designed for separating data from views and this is why Qt has two different types of widgets. Both types of widgets look the same, but they interact with data differently.


1 Answers

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);

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
like image 130
serge_gubenko Avatar answered Sep 18 '22 15:09

serge_gubenko