用新值更新 QTableView 中的单元格

Ric*_*cky 4 c++ qt qtableview

我是新手,我正在学习用 Qt 编程,我的英语不是很好,我的问题是当我更新 QTableView 中的一个单元格以在另一个单元格中使用它的值时,它使用以前的值而不是新的,我正在向他们展示代码,谢谢。

bool MainWindow::eventFilter(QObject * watched, QEvent * event)
{
    if(event->type() == QEvent::KeyPress)
    {
        QKeyEvent *ke = static_cast<QKeyEvent *>(event);
        qDebug() << ke->type();
        if(ke->key() == Qt::Key_Enter || ke->key() == Qt::Key_Return)
        {
            int fila = ui->tableView->currentIndex().row();
            int col = ui->tableView->currentIndex().column();
            double valor1 = ui->tableView->model()->data(ui->tableView->model()->index(fila,1)).toDouble();
            double valor2 = ui->tableView->model()->data(ui->tableView->model()->index(fila,3)).toDouble();
            if(col == 1 || col == 3)
            {
                ui->tableView->model()->setData(ui->tableView->model()->index(fila,col + 1),2.0*valor1);
                ui->tableView->model()->setData(ui->tableView->model()->index(fila,col + 3),200.0*valor1/valor2);
            }
        }
    }

return false;
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*rey 6

如果您在自定义数据模型中(可能继承自QAbstractTableModel,因为我们正在讨论QTableViews),您可以通过发出QAbstractItemModel::dataChanged()信号通知视图数据发生了更改。

这是我如何做到的。

更新整行:

QModelIndex startOfRow = this->index(row, 0);
QModelIndex endOfRow   = this->index(row, Column::MaxColumns);

//Try to force the view(s) to redraw the entire row.
emit QAbstractItemModel::dataChanged(startOfRow, endOfRow);
Run Code Online (Sandbox Code Playgroud)

更新一整列,但只更新 Qt::DecorationRole:

QModelIndex startOfColumn = this->index(0, mySpecificColumn);
QModelIndex endOfColumn = this->index(numRows, mySpecificColumn);

//Try to force the view(s) to redraw the column, by informing them that the DecorationRole data in that column has changed.
emit QAbstractItemModel::dataChanged(startOfColumn, endOfColumn, {Qt::DecorationRole});
Run Code Online (Sandbox Code Playgroud)

通过将 UpdateRow(row) 和 UpdateColumn(column) 等便利函数添加到您的项目模型中,如果您在外部更改数据,您可以从模型本身的外部调用这些函数。

您不想让视图自行更新 - 如果有多个视图查看同一个模型怎么办?让模型通知所有附加的视图它已更改。