好吧,我有一个非常基本的QStandardItemModel,充满了一些数字。我设法将它显示在 aQTableView中,没关系。我创建了一个新模型( or 的子类QAbstractItemModel)QAbstractProxyModel,它是现有模型的某种层 - 需要设置源模型,并且这个新层应该对真实模型进行一些转换。
我的问题是,在顶层,说“层模型”data( const QModelIndex & index, int role )成员函数从未调用过,但是我想通过角色参数改变显示方法。
这是一个示例代码,它演示了data(index,role)始终调用原始模型,而data(index,role)从不调用层模型。为什么?QTableView 对象如何“跳过”顶层的data(index,role)?
#include <QtGui/QApplication>
#include <QtGui>
#include <QStandardItemModel>
MyModel 类:公共 QStandardItemModel
{
上市:
MyModel(const int r, const int c, QObject* parent = 0) : QStandardItemModel(r,c,parent) {}
QVariant 数据 ( const QModelIndex & index, int role = Qt::DisplayRole ) const {
qDebug() << "我的模型数据";
返回 this->itemFromIndex(index)->data(role);
}
};
MyProxyModel 类:公共 QAbstractProxyModel
{
上市:
MyProxyModel(QObject* parent = 0) : QAbstractProxyModel(parent) {}
QModelIndex 索引( int 行,int 列,const QModelIndex & parent = QModelIndex() ) const {
返回 this->sourceModel()->index(row,column,parent);
}
QModelIndex 父级 ( const QModelIndex & index ) const {
返回 this->sourceModel()->parent(index);
}
QModelIndex mapFromSource ( const QModelIndex & sourceIndex ) const
{
返回源索引;
}
QModelIndex mapToSource ( const QModelIndex & proxyIndex ) const
{
返回代理索引;
}
QVariant 数据 ( const QModelIndex & index, int role = Qt::DisplayRole ) const {
qDebug() << "myproxymodel 数据";
返回 this->sourceModel()->data(index,role);
}
int rowCount ( const QModelIndex & parent = QModelIndex() ) const {
返回 this->sourceModel()->rowCount(parent);
}
int columnCount ( const QModelIndex & parent = QModelIndex() ) const {
返回 this->sourceModel()->columnCount(parent);
}
};
int main(int argc, char *argv[])
{
QApplication 应用程序(argc,argv);
MyModel 模型(8, 2);
我的代理模型我的模型;
mymodel.setSourceModel(&model);
QTableView 表视图;
tableView.setModel(&mymodel);
tableView.horizontalHeader()->setStretchLastSection(true);
for (int row = 0; row < 8; ++row) {
for (int column = 0; column < 2; ++column) {
QModelIndex index = model.index(row, column, QModelIndex());
model.setData(index, QVariant((row+1) * (column+1)));
}
}
tableView.show();
返回 app.exec();
}