Make QSqlQueryModel editable: setData
-
Hello,
I have been searching quite a lot on this topic, but don't find a solution, and here is where you are coming in.
The QSqlQueryModel is designed to be read-only as default, but it is stated that it can be made editable by reimplementing flags and setData.
In flags, I return that any index that is a Qt::UserRole is editable, but for setData, it becomes more difficult. If I call QSqlQueryModel::setData, it obviously returns false because it does not exist. So how do I reimplement this function? If in my reimplemented function MyModel::setData writes to the database with update sentences, the data are updated and I can call a SqlQuery to update my list. But that is not what I want.
As I see the Qt model concept, there are (at least) three layers. First you have the data (file I/O, sql database, or something else that stores data). The next layer is a databuffer in the model, and then one or more views. So in the MyModel::setData I want to update the buffer for performance reasons.
In the view I have a list (QML ListView) listing data from the QSqlQueryModel. I click on an item which leads me to an edit field. Here I point the edit-data directly to model-data, and the setData function is automatically called. If I from here call a new QSqlQuery (select something), the list will be destroyed and rebuilt; and the application crashes because the model index I am at is no longer. So I just want to update the model buffer. If I emit dataChanged for the index after just updating the database, the cell will be updated with the buffered data value, which is wrong as long as the buffer has not yet been updated..
So how do I implement setData to update the QSqlQueryModel buffer?
QSqlTableModel is not an option since the queries are complex with many tables.
If the answer is that the cache of the QSqlQueryModel cannot be changed, which sounds funny, then how do you guys make your models of database data?
-
Hello,
I have just the same problems as above... Unfortunately I can't find solution and this is the most accurate description of what I want to do.Please provide some answers / guidelines.
-
I ended up with reimplementint the QAbstractListModel. Here are some hints: Make a query on an instance of the QSqlQueryModel. Then loop through the result set and add data for each role you have predefined. Each item in the QList<> items should have a QVariant data variable. The data() function should look up and return the data asked by role to the view. The setData function should commit changes to the database.