PDA

View Full Version : QSqlQueryModel as return value



vittorio
15th November 2016, 22:16
Hi all,
I try to write a function, which generates a QSqlQueryModel and returns this model to the calling function. First I thought, this should be an easy thing but obviously I was wrong! :(
I searched the forum but found no information, which could help me...

My function:


QSqlQueryModel DBManager::loadConnectionData()
{
QSqlQuery *qry = new QSqlQuery(dbSQLite);
QSqlQueryModel model;
qry->prepare("select * from tbl_connections");
qry->exec();
model.setQuery(*qry);
return model;
}


When I try to compile the code I get following error message:
Fehler: C2280: 'QSqlQueryModel::QSqlQueryModel(const QSqlQueryModel &)': attempting to reference a deleted function

I didn't find an explanation on the net which helped me to understand the problem, so maybe someone here is so kind to help me a little bit?

Thanks in advance!!

Viktor

d_stranz
16th November 2016, 00:21
You cannot create a QSqlQueryModel on the stack and return it as the return value of a function. The class has neither a copy constructor nor an assignment operator, one of which would be required to accomplish this. Furthermore, your QSqlQuery is a memory leak. You might have more luck using something like this:



QSqlQueryModel * DBManager::loadConnectionData()
{
QSqlQuery qry(dbSQLite);
QSqlQueryModel * model = new QSqlQueryModel( this );
qry,prepare("select * from tbl_connections");
qry.exec();
model->setQuery(qry);
return model;
}

You probably also need a ";" at the end of your select statement for proper syntax. Remember to call delete on the "model" instance after you are done with it to avoid a memory leak on that.

anda_skoa
16th November 2016, 11:07
Or instead if fiddling with the transient QSqlQuery here use the setQuery() overload that takes a query string and database connection.

Cheers,
_

vittorio
16th November 2016, 11:41
thanks for your help, now it works!