6

I have a QTableView populated by QSqlRelationalTableModel.

There is a column that references another table, so when I edit/create a row, this column's editor is QCombobox which gets its data from the related table. The problem is that I want to filter the data with some predefined WHERE close on the related table.

Example:

Tables:

Person:
id, name, job_id;

Job:
id, title, salary

What I want is something like

model.setRelation(3,QSqlRelation("Job", "id", "title", "WHERE salary > 50000"))

So that the QCombobox will have only Job titles with salaries > 5000.

I cannot use QSqlQueryModel as suggested in SO question - I still need users to be able to add new data or edit existing data.

It seems that someone managed to achieve this 10 years ago by tweaking the QT source code, but my C++ is bad so I could not figure it out quite well.

Possible solutions:

  1. The first thing that comes to mind is to implement my own QSqlRelationalDelagate and populate QCombobox in the createEditor and set appropriate values in setModelData. I will try to do it myself and report the results back here. But it seems not very clean to me.

  2. The best way would be to Extend the functionality of the QSqlRelation or QSqlRelationalTableModel but the documentation on it seems to be not very clear. So the real question is for experienced QT/PyQT developers: How do I solve the problem this way?


Update

So filtering out the contents of the QCombobox in the createEditor of the delegate works, but it requires a database query every time the editor is created which seems a bit off. And also it was quite a mess to handle new indexes after filtering. But I still wonder about the second way of approaching the problem.

0 Answers0