c++ - 使用新值更新 QTableView 中的单元格

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

最佳答案

如果您在自定义数据模型中(可能继承自 QAbstractTableModel,因为我们正在讨论 QTableView),您可以通知 View 更改通过发出 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);

更新整个列,但仅更新 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});

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

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

关于c++ - 使用新值更新 QTableView 中的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4696285/

相关文章:

c++ - 对于基于 Arduino Sketch 的照度计, 'loop' 之外的功能不会被触发/触发

c++ - 理解opencv中的Mat

qt - 如何将字符串添加到 QCombobox

c++ - QWidgetAction : how to make the menu disappear after the user completes his input

python - 如何让QTableView只有在双击时才进入编辑模式

c++ - 一个类的独立名称

c++ - 复制构造函数中的模板

Qt 样式表之谜

python - 如何设置 QTableView CSS 样式

c++ - QAbstractTableModel::data 方法调用次数过多