我有一个 QTableView 和一个相应的 QAbtractTableModel 子实例。
我惊讶地发现,如果我的表模型实例发出一个命名单个单元格的 dataChanged,那么 Qt 框架将发出大量对我的表模型的 ::data() 成员函数的调用。这些调用的行/列范围似乎涵盖了屏幕上的整个范围+一些额外的内容。
这超出了我的预期。我原以为命名单个单元格的 dataChanged() 只会导致 ::data() 调用请求该单元格的数据。毕竟,这是我的表格模型所说的唯一改变的单元格。但是 Qt 框架似乎非常合群,并且会询问所有单元格。
我显然对 dataChanged() 信号的意图有一个破碎的理解。
有没有办法告诉 QTableView 只更新一个单元格和一个单元格,而无需将所有额外的喋喋不休发送到我的表格模型?
更新:包括代码示例 这里的示例是标题、源代码和用于创建表的代码块。对我来说,表格显示为 12 列和 29 行。在最后的“issueEmit”调用之后,::data 将被调用 1044 次,这都是因为单个单元格的 dataChanged() 信号。
// Declaration
#include <QAbstractTableModel>
class SimpleModel : public QAbstractTableModel
{
Q_OBJECT
private:
bool _post_emit;
public:
explicit SimpleModel(QObject *parent=0);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
void issueEmit();
};
// Implementation
#include <stdlib.h>
#include <stdio.h>
#include "simplemodel.h"
SimpleModel::SimpleModel(QObject *parent) : QAbstractTableModel(parent), _post_emit(false) { }
int SimpleModel::rowCount(const QModelIndex &parent) const {
return 100;
}
int SimpleModel::columnCount(const QModelIndex &parent) const {
return 100;
}
QVariant SimpleModel::data(const QModelIndex &index, int role) const {
if (role==Qt::DisplayRole) {
if (_post_emit) {
static unsigned s_calls=0;
s_calls++;
printf("Data calls: %d\n",s_calls);
}
return ((rand()%10000)/1000.00);
}
return QVariant();
}
void SimpleModel::issueEmit() {
_post_emit=true;
emit dataChanged(createIndex(1,1),createIndex(1,1));
}
// Usage
QTableView *table=new QTableView;
table->setMinimumSize(1200,900);
SimpleModel *model=new SimpleModel;
table->setModel(model);
table->show();
model->issueEmit();