将QStringListModel包装在QABSTRACTITEMMODEL中,呈现一个空白列表

Wrapping a QStringListModel in a QAbstractItemModel renders a blank list

本文关键字:一个 列表 空白 包装 QStringListModel QABSTRACTITEMMODEL      更新时间:2023-10-16

我想开始为QT列表视图制作自己的模型,我认为我将首先将QStringListModel包装在我自己的QAbstractItemModel中,然后将其渲染在列表视图中。但是,它只会呈现一个空白的白色正方形,而不是我期望的列表。鉴于我要做的只是将所有电话委派给QStringListModel,我真的不知道会发生什么。也许QListView调用CC_5的某些方面不受QAbstractItemModel纯虚拟方法的要求?也许它与QStringList的存储有关?

我的尝试在下面。标题:

class DelegatingItemModel: public QAbstractItemModel {
public:
    DelegatingItemModel();
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
    int columnCount(const QModelIndex &parent = QModelIndex()) const override;
    int rowCount(const QModelIndex &parent = QModelIndex()) const override;
    QModelIndex parent(const QModelIndex &index) const override;
    QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
private:
    QAbstractItemModel* innerModel;
};

这是实现:

#include "delegating_item_model.hh"
DelegatingItemModel::DelegatingItemModel() {
    QStringList available = {"foo", "bar", "baz"};
    this->innerModel = new QStringListModel(available);
}
QVariant DelegatingItemModel::data(const QModelIndex &index, int role) const {
    return innerModel->data(index, role);
}
int DelegatingItemModel::columnCount(const QModelIndex &parent) const {
    return innerModel->columnCount(parent);
}
int DelegatingItemModel::rowCount(const QModelIndex &parent) const {
    return innerModel->rowCount(parent);
}
QModelIndex DelegatingItemModel::parent(const QModelIndex &index) const {
    return innerModel->parent(index);
}
QModelIndex DelegatingItemModel::index(int row, int column, const QModelIndex &parent) const {
    return innerModel->index(row, column, parent);
}

这是入口点:

int main(int argc, char** argv) {
    qDebug() << "Starting up";
    QApplication app(argc, argv);
    QMainWindow mainWindow;
    QListView* listView = new QListView;
    DelegatingItemModel* theModel = new DelegatingItemModel;
    listView->setModel(theModel);
    mainWindow.setCentralWidget(listView);
    mainWindow.show();
    return app.exec();
}

您的视图仅在给定索引链接到其模型时才从模型中获取数据。如果您在Data()方法中打印跟踪,您将看到它从未被调用。

因此,您无法返回内部列表模型创建的新索引,因为它将链接到列表,而不是您自己的模型。例如:

QModelIndex DelegatingItemModel::index(int row, int column, const QModelIndex &parent) const {
    //return innerModel->index(row, column, parent);
    if (parent.isValid()) // It's a list. Not a tree
        return QModelIndex();
    return createIndex(row, column); // Create a index for your own model.
}

要保持完整,您应该转换data()中的索引:

QVariant DelegatingItemModel::data(const QModelIndex &index, int role) const {
    QModelIndex const innerIndex(innerModel->index(index.row(), index.column()));
    return innerModel->data(innerIndex, role);
}