How to resolve this warning
-
Hi, I executed a query to display a list from the database. However, the model->setQuery(*qry) shows a warning
'setquery' is deprecated. QSqlQuery is not meant to be copied. Pass it my move instead.
How should I resolve this warning?
db = QSqlDatabase::database(); QSqlQueryModel * model = new QSqlQueryModel(); QSqlQuery *qry = new QSqlQuery(db); qry->prepare("select * from plan order by plandet desc"); qry->exec(); model->setQuery(*qry); delete qry; int rowcount = model->rowCount(); qDebug()<< rowcount; ui->listView->setModel(model); db.close();
-
Don't create the query on the heap but on the stack and then move it to setQuery()
model->setQuery(std::move(qry))
See also https://doc.qt.io/qt-6/qsqlquerymodel-obsolete.html#setQuery-1
-
@burrito1111 Do you use Qt6? See the signature: https://doc-snapshots.qt.io/qt6-dev/qsqlquerymodel.html#setQuery
You need to do it like this:QSqlQuery qry(db); // Do NOT allocate on the heap model->setQuery(std::move(qry));
-
Don't create the query on the heap but on the stack and then move it to setQuery()
model->setQuery(std::move(qry))
QSqlQuery qry(db); // Do NOT allocate on the heap
I wonder how Python/PyQt/PySide (everything is on the heap) handles this then? :)
-
@jsulm said in How to resolve this warning:
but after moving you will need to delete it
Which will result in a crash - a moved-out object is in an undefined state. And even if not it would call the QSqlQuery dtor and kill the moved object too.
-
@Christian-Ehrlicher said in How to resolve this warning:
and kill the moved object too
Are you sure about that?
If the move constructor is implemented properly the other QSqlQuery object should not be affected by destroying the original (moved) one. The destructor is also called when the stack allocated object goes out of scope. -
@Christian-Ehrlicher that's a stupid requirement to have, only God knows if the compiler will actually move something or not :D
It's really all just a suggestion, same as inline
-
@burrito1111
Going all the way back to your original code. Can't you get rid of your need to explicitly create aQSqlQuery
by just having the whole thing written as:QSqlQueryModel * model = new QSqlQueryModel(); model->setQuery("select * from plan order by plandet desc"); int rowcount = model->rowCount(); ...
? Much simpler, avoids all this stuff,
new
/delete
ing too. Are you trying to ensure theqry->prepare()
gets done? (I haven't looked at whethermodel->setQuery(QString)
does that anyway.) -
P Pl45m4 referenced this topic on