我想开始制作我自己的 Qt ListView 模型,我想我会先在我自己的 QAbstractItemModel
中包装一个 QStringListModel
,然后渲染它在 ListView 中。但是,它只呈现一个空白的白色方 block ,而不是我期望的列表。我真的不知道会发生什么,因为我所做的只是将所有调用委托(delegate)给 QStringListModel
。也许 QStringListModel
的某些方面由 QListView
调用,而 QAbstractItemModel
纯虚拟方法未强制要求?或者它可能与 QStringList
的存储有某种关系?
我的尝试如下。 header :
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();
}
最佳答案
只有当给定的索引链接到它的模型时,你的 View 才会从模型中获取数据。如果您在 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);
}
关于c++ - 在 QAbstractItemModel 中包装 QStringListModel 呈现一个空白列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55041767/