Qt 6.11 is out! See what's new in the release
blog
Customize QSqlRelation to filter results
-
In Qt 6.8.0 I have a
QSqlDatabase(SQLite) with two tables.Table "songs":
QString sql = "CREATE TABLE songs \ (id INT NOT NULL, \ name TEXT, \ enabled BOOLEAN, \ duration INT NOT NULL, \ extension TEXT NOT NULL, \ PRIMARY KEY (id));";and table "events":
QString sql = "CREATE TABLE events \ (id INT NOT NULL, \ idSong INT NOT NULL DEFAULT 0, \ duration INT NOT NULL DEFAULT 1, \ PRIMARY KEY (id), \ FOREIGN KEY (idSong) REFERENCES songs(id));";I omitted other fields for clarity.
Then I show the "events" table in aQTableViewand I set it up in the following way:QSqlRelationalTableModel *_model = nullptr; // ... QSqlDatabase db = QSqlDatabase::database("mydb"); _model = new QSqlRelationalTableModel(this, db); _model->setTable("events"); _model->setEditStrategy(QSqlRelationalTableModel::OnRowChange); view->setSortingEnabled(false); connect(_model, &QSqlRelationalTableModel::beforeInsert, this, [=](QSqlRecord record) { emit rowInserted(_model->rowCount(), record); }); connect(_model, &QSqlRelationalTableModel::beforeDelete, this, [=](int row) { emit rowRemoved(row, _model->record(row)); }); _model->setRelation(1, QSqlRelation("songs", "id", "name")); _model->select();Basically, I replicated the SQL relation at Qt-level.
So far so good.In the
QTableViewI see aQComboBoxthat lists all the names of the table "songs".Now I want to customize (filter) this list, for example showing only the rows with the field "enabled" set to
true.Is it possible to add such a constraint to the relation call?
If is not possible, how can I do the same? -
Hi,
I would check the implementation of QSqlRelationalDelegate, mimic it and add the filter there.
-
M Mark81 has marked this topic as solved on