Best practices to use CRUD SQL in QML
-
I have implemented in a .cpp one QSqlQueryModel where step a name for QmlApplicationViewer.rootContext()->setContextProperty("ALIAS", myObject)
And main.qml carry in ListView in my model the myObject and runs smoothly.
But now I need to perform select, insert and update in QML and am trying to use QQuerySql but I can not run the model of the ListView.
My old implementation is one of this template:
https://wiki.qt.io/How_to_Use_a_QSqlQueryModel_in_QMLMy new implementation is something like this:
https://forum.qt.io/topic/51219/solved-qsqlquerymodel-for-qml-tableview/2What would be the best/efficient way via QML perform insert, update, delete and select:
-
@Cleiton-Bueno
QSqlQueryModel
provides setQuery to which you can pass your query string. Now since you have access of the cpp class which containsQSqlQueryModel
you can introduce anotherQ_INVOKABLE
function in that class which can be called directly from QML. And this function will internally callsetQuery
. Something like:void MyClass::executeQuery(QString query) //exposed to QML { QSqlQuery q; q.prepare(query); q.exec(); setQuery(q); }
-
@p3c0 said in Best practices to use CRUD SQL in QML:
executeQuery
But I can send a "INSERT ..." or "CREATE ..." or "UPDATE ..." for example via executeQuery ()
-
@Cleiton-Bueno Since this function takes a
QString
you can form a string on QML side and pass to this function. Or if you know the fields and its values on QML side you can create a JS object which can then be converted toQVariantMap
on C++ side. This map can then be iterated and your desired query can be created. -
@Cleiton-Bueno Yes. If the query string is correct it will work.