In QT, chaining models does not work as expected

时光总嘲笑我的痴心妄想 提交于 2019-12-05 09:23:44

Because QTableView uses the model index to retrieve the data, probably something like this.

QModelIndex index = model->index(row, column, parentIndex); 
index.data(Qt::DisplayRole);

And you are returning the model index of the source model instead of an index to your proxy model:

QModelIndex index ( int row, int column, const QModelIndex & parent = QModelIndex() ) const {
    return this->sourceModel()->index(row,column,parent);
}

Try to convert the model index into an index to your proxy model

QModelIndex index ( int row, int column, const QModelIndex & parent = QModelIndex() ) const {
    return this->createIndex(row,column,row);
}

Don't forget to rewrite the map to source and map from source functions.


Solution

class MyTableProxyModel : public QAbstractProxyModel
{
    Q_OBJECT
public:
    MyTableProxyModel (QObject* parent = 0) 
        : QAbstractProxyModel(parent) {
    }

    QModelIndex index(int row, int column, const QModelIndex& parent=QModelIndex()) const {
        return createIndex(row,column,row);
    }

    QModelIndex parent(const QModelIndex &index) const {
        //Works only for non-tree models
        return QModelIndex();
    }

    QModelIndex mapFromSource(const QModelIndex &source) const {
        return index(source.row(), source.column(), source.parent());
    }

    QModelIndex mapToSource(const QModelIndex &proxy) const {
        return (sourceModel()&&proxy.isValid())
            ? sourceModel()->index(proxy.row(), proxy.column(), proxy.parent()) 
            : QModelIndex();
    }

    QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const {
        qDebug() << "myproxymodel data";
        return mapToSource(index).data(role);
    }

    int rowCount ( const QModelIndex & parent = QModelIndex() ) const {
        return sourceModel() ? sourceModel()->rowCount(parent) : 0;
    }

    int columnCount ( const QModelIndex & parent = QModelIndex() ) const {
        return sourceModel() ? sourceModel()->columnCount(parent) : 0;
    }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!