qtqtableviewqsqlquerymodel

In other files(except mainwindow.cpp),how to opertate on ui components?


There are three .cpp files in my project:
enter image description here

Now, i reimplmented QSqlQueryModel to make it editable which means i reimplemented function QSqlQueryModel::setData() and function QSqlQueryModel::flags() and i use a QTableview to show the data.
In the end of reimplemented function QSqlQueryModel::setData(),there is a refreshing step to populate data into model again:

bool ScoreModel::setData(const QModelIndex &index, const QVariant &value, int /* role */)
{
   if (index.column() == 0 || index.column() == 11)
        return false;

    QModelIndex primaryKeyIndex = QSqlQueryModel::index(index.row(), 0);
    int id = data(primaryKeyIndex).toInt();
    qDebug()<<"id:"<<id;
    clear();

    bool ok;
    switch(index.column()){
    case 1:
        ok = setYear(id,value.toString());
        break;
    case 2:
        ok = setStudentName(id,value.toString());
        break;
    ...
    case 10:
        ok = setTeacherRemark(id,value.toString());
        break;
    default:
        ok = false;
    }
    refresh();// <---
    return ok;
}


void ScoreModel::refresh()
{
    qDebug()<<"sqlToQueryScore in refresh:"<<MainWindow::sqlToQueryScore;
    setQuery(MainWindow::sqlToQueryScore);
    setHeaderData(0, Qt::Horizontal, tr("序号"));
    setHeaderData(1, Qt::Horizontal, tr("年份"));
    ...
    setHeaderData(11, Qt::Horizontal, tr("数据插入时间"));
}

but i decorated the tableView with following code in mainwindow.cpp(where ui->tableView can be referenced):

ui->tableView->setModel(scoreModel);
//ui->tableView->setEditTriggers(QAbstractItemView::DoubleClicked);
ui->tableView->verticalHeader()->hide();
ui->tableView->resizeColumnsToContents();
ui->tableView->resizeRowsToContents();
//ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView->horizontalHeader()->setStretchLastSection(true);  

In order to maintain the consistency of appearance of the tableView, i also want to make such operations in refreshing step.
In my limited experience with Qt/C++,i can't not deal with it efficiently. I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.Thanks!


Solution

  • The idea of the MVC pattern (or in Qt terms Model/View Programming) is to keep your model separated from your view controller. Sloppy said: "The model should only handle the data itself and has no idea how it will be displayed." but I definitely suggest you go throw the above link.

    Possible solution to your question is to emit a signal in your ScoreModel::refresh() method, in your view controller (in your case the mainwindow.cpp) you define and connect then the corresponding slot method to refresh your tableview, cf. signals & slots.