使用QSqlQueryModel和QSortFilterProxyModel未正确更新QTableView

时间:2012-02-10 09:53:51

标签: c++ sql qt qtableview

我正在使用QTableView来显示QSqlQueryModel的结果。 DB中的数据是永久性更改的,因此我每次都运行相同的脚本并需要获取更新的数据。查询在另一个线程中执行,之后它将结果返回给主线程。

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;
}

当我尝试使用QSortFilterProxyModel引入排序时出现问题。由于我这样做,我的表没有收到任何更新的数据。 我检查了QSqlQueryModel没有收到任何更新的数据,而在DBMS中运行相同的脚本给了我新的结果。 如果我不使用QSortFilterProxyModel,则表格会正常更新。

1 个答案:

答案 0 :(得分:0)

我不知道你的其余代码,但这可能有所帮助。

    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);

}