Help a newbie to deal with QTreeView & Model
-
Hello!
Help build the tree from sql.
There is a table:
| id | id_parent | name |
| 1 | | footwear |
| 2 | 1 | sandals |
| 3 | 2 | red |
| 4 | 2 | blue |
| 5 | 1 | sneakers |
| bla | bla | bla |From this table, construct a tree:
++ footwear
++++ sandals
++++++ red
++++++ blue
++++ sneakers
++++ bla, bla, blaI already have the code that displays the contents of the table.
#include "mainwindow.h" #include "ui_mainwindow.h" #include "QMessageBox" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("../../task/task.sqlite3"); if(!db.open()) QMessageBox::critical(this, "Wirning DB", "No database connection!"); model = new QSqlTableModel(this); model->setTable("hierarhy"); model->select(); qDebug() << model->lastError().text(); ui->treeView->setModel(model); } MainWindow::~MainWindow() { db.close(); delete ui; }
What should be changed in the code to build the tree.
Sorry for my English. I use a translator. Please provide sample code. -
I don't know if there are any Qt models that support SQL for trees. I think they were all built for tables so you might have to build one yourself.
Have you checked out the Simple Tree Model example? I found it pretty helpful: http://doc.qt.io/qt-5/qtwidgets-itemviews-simpletreemodel-example.html . Also, if you find it easier, you can use a QStandardItemModel instead of a QAbstractItemModel.