I'm currently facing problems with populating a QML Combobox
with a QSqlTableModel
.
Example Database:
Table Customer Table Project
| id | name | | id | name | fk_customer |
|........|..........| |........|.........|...............|
| 1 | name1 | | 1 | pro1 | 1 |
| 2 | name2 | | 2 | pro2 | 1 |
| 3 | name3 | | 3 | pro3 | 3 |
I want to show a form with a QML Combobox
to select the customer by name.
Therefore I am setting the combobox model to a QSqlTableModel
with table="customer"
and textRole="name"
.
My Problem now resides in setting the Combobox.currentindex
to the correct value from the database and of course to read the selected ID
back from the combobox.
The Comboboxes
documentation states that whenever the combobox is populated with a new model, its current index is set to 1
.
I tried to set the currentindex with Component.onCompleted
Signal from combobox and its parent but the selected index was always set to 1
.
So I think I might have made conceptional mistake when implementing the model or the QML-file.
Does anyone know a suggested way when and how to pre set a QML Combobox with a given value from c++ model?
I do not understand what the problem is since you do not provide an MCVE, so my response will try to show the correct solution.
Assuming you understand that the
QSqlTableModel
can not be used directly in QML but you have to add roles that correspond to the fields and overwrite thedata()
androleNames()
method.To obtain the information of the given
ID
thecurrentIndex
of the view must use thedata()
method of the model so the correspondingQModelIndex
and the role must be created, in this case to simplify that task I have implemented a function that given the row and the name of the field returns the data.Using the above I have implemented the following class:
sqltablemodel.h
So you must create the model and export it to QML:
And the connection is made in QML:
The complete example can be found in the following link.