QML and QSqlTableModel
I wrote a simple class derived from QsqlRelationalTableModel to facilitate the use of such classes with QML, without manually defining the roles.
- {
- Q_OBJECT
- private:
- public:
- ~QLSqlTableModel();
- void generateRoleNames();
- }
- {
- if (!index.isValid())
- m.setTable(this->tableName());
- m.select();
- if(index.row() >= m.rowCount())
- for (int i = 0; i < columnCount(); i++) {
- if (relation.isValid()) {
- m.setRelation(i, relation);
- m.select();
- }
- }
- m.setTable(this->tableName());
- m.select();
- if(index.row() >= m.rowCount())
- }
The data method returns the value of the role used. If there is a relationship in the table, i search the column with relation and return the correct value.. Note that empty string is returned when the item is not found e not QVariant value, in order to have a correct visualization in QML.
- void QLSqlTableModel::generateRoleNames()
- {
- roles.clear();
- for (int i = 0; i < this->columnCount(); i++) {
- }
- setRoleNames(roles);
- }
The generateRoleNames method creates the roles called as the table columns specified in the header.
Example:
Tables:
- query.exec("create table IF NOT EXISTS items (id integer primary key autoincrement,
- name varchar(15), descr varchar(30))");
- query.exec("create table IF NOT EXISTS lista (id integer primary key autoincrement,
- qta varchar(30), item INTEGER, FOREIGN KEY(item) REFERENCES items(id))");
main.cpp
- QLSqlTableModel *model = new QLSqlTableModel;
- QLSqlTableModel *modelLista = new QLSqlTableModel;
- model->setTable("items");
- model->generateRoleNames();
- model->select();
- modelList->setTable("lists");
- modelList->select();
- modelList->generateRoleNames();
- QDeclarativeContext *ctxt = view.rootContext();
- ctxt->setContextProperty("modelListItems", model);
- ctxt->setContextProperty("modelList", modelLista);
In qml file
- Text {
- id: name
- text: model.name
- font.bold: true; font.pointSize: 16
- color: "white"
- }
- Text {
- text: "Amount: " + model.qta
- font.pointSize: 16
- opacity: 1
- color: "white"
- }
——————————————————-
Edit:
Nice post, however the performance can be tweaked. data() will be called very often. Most of the processing and object instantiation should be done only once.

