Question

I just want to process on database and add the result to a model and send it to another class and view it in GUI. Abstract code is:

I have a public class member:

QSqlQueryModel  *model;

Load data and add it to the model and return model:

QSqlQueryModel* PersistenceAdapter::loadServerList(){
    cout<<"Loading data"<<endl;
    QSqlQuery* qry = new QSqlQuery(db);
    qry->prepare("select * from student1.SERVERLIST");
    model = new QSqlQueryModel();
    model->setQuery(*qry);
    return model;
}

In other class I have a load list function. Error is coming from here:

void MainWindow::setServersList(QSqlQueryModel *myModel) {
    widget.serverListView->setModel(myModel);
}

Then I call it from constructor of same class and here is code:

MainWindow::MainWindow() {
    //Stablish connection to database
    PersistenceAdapter *p = new PersistenceAdapter();
    setServersList(p->loadServerList());
}

And error is:

RUN FINISHED; Segmentation fault; core dumped; real time: 210ms; user: 10ms; system: 40ms

Appreciate if anyone can help.

Was it helpful?

Solution

There are several mistakes in your code. Also, here are some tips'n'tricks for your situation:

  1. Are you sure that your model member was initialized/instantiated? To check it just do if model!=NULL check.
  2. Are you sure that your db (in PersistenceAdapter::loadServerList()) was instantiated? _To check it just do if model!=NULL check. Also, check if that db was successfully opened, and check if it isOpen at moment of use. Keep in mind that you can got some errors while doing multithreaded database access.
  3. I do not recommend create QSqlQuery, instead you can use another setQuery method.
  4. After you apply your query, do check: if (model.lastError().isValid()) qDebug() << model.lastError();
  5. Check order of calling your functions -- if instantiating db goes earlier than accessing db and so on.

Hope this tips will throw light upon. Good luck!

OTHER TIPS

widget.serverListView->setModel(myModel);

So, the crash can only be there. Since the widget seems to be on the heap (which is a bad idea), the only reason for the crash is that your server list view is not properly initialized at that stage, so it is either a null pointer or dangling.

This also looks logical since you do not seem to initialize the view of the widget in your main window constructor. If you do it so, the crash will go away.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top