0
votes

I'm using QTableView in order to display the results of QSqlQueryModel. The data in DB is permanently changed so I run the same script every time and need to get updated data. The query is executed in another thread after which it returns the result to main thread.

void SqlThread::setNewScript(QString script)
{
    QSqlQueryModel * sqlModel = new QSqlQueryModel();
    this->script = script;
    QSqlQuery query = QSqlQuery(this->script, db);
    sqlModel->setQuery(query);
    emit queryFinished(sqlModel);
}

void myTable::onQueryFinished(QSqlQueryModel * model)
{
    QAbstractItemModel * oldModel = this->table->model();
    QSortFilterProxyModel * sort = new QSortFilterProxyModel();
    sort->setSourceModel(model);
    this->table->setModel(sort);
    delete oldModel;
}

The problem appeared when I've tried to introduce sorting using QSortFilterProxyModel. Since I did it my table haven't received any updated data. I checked that QSqlQueryModel doesn't receive any updated data while running the same script in DBMS gives me new results. If I don't use QSortFilterProxyModel the table is updated normally.

1

1 Answers

0
votes

I dont know the rest of your code, but this may help.

    void SqlThread::setNewScript(QString script)
        {
            //QSqlQueryModel * sqlModel = new QSqlQueryModel();
            //It's better to implement your model as [QSortFilterSqlQueryModel][1]
            QSortFilterSqlQueryModel * sqlModel = new QSortFilterSqlQueryModel();
            this->script = script;
            QSqlQuery query = QSqlQuery(this->script, db);
            sqlModel->setQuery(query);
            //use select to start query
            sqlModel->select();
            emit queryFinished(sqlModel);
        }

  /*
      void myTable::onQueryFinished(QSqlQueryModel * model)
        {
            QAbstractItemModel * oldModel = this->table->model();
            QSortFilterProxyModel * sort = new QSortFilterProxyModel();
            sort->setSourceModel(model);
            this->table->setModel(sort);
            delete oldModel;
        }

rest of can be corrected like that if you really wanna pass model to 
the slot(this does not seems to be good idea as your model is already on the heap)*/
void myTable::onQueryFinished(QSortFilterSqlQueryModel * model)
{
            table->setModel(model)
            table->setSelectionMode(QAbstractItemView::SingleSelection);//other option(s) you like
            table->setSortingEnabled(true);

}