在Qt中,QModelIndex用于表示我理解的索引。正式
此类用作从
QAbstractItemModel派生的项模型的索引。项视图、委托和选择模型使用索引来定位模型中的项。
但我看到它被用来表示父对象。例如,如果我想在QFileSystemModel对象中获取索引,则需要行、列和父级:
QModelIndex QFileSystemModel::index(int row, int column, const QModelIndex &parent = QModelIndex()) const我正在尝试获取一个QModelIndex对象,但是要做到这一点,我需要另一个QModelIndex对象吗?我只是在试图迭代这个模型。我没有单独的parent对象。如何从行/列编号创建索引?我不明白QModelIndex作为“家长”的角色。模型本身不应该知道父对象是什么吗?我们在创建模型时传递了一个指向构造函数的指针。
下面是一些显示问题的代码:
#include "MainWindow.hpp"
#include "ui_MainWindow.h"
#include <QFileSystemModel>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
auto* model = new QFileSystemModel{ui->listView};
ui->listView->setModel(model);
ui->listView->setRootIndex(model->setRootPath("C:\\Program Files"));
connect(ui->pushButton, &QPushButton::clicked, [this] {
auto* model = static_cast<QFileSystemModel*>(ui->listView->model());
int row_count = model->rowCount();
for (int i = 0; i != row_count; ++i) {
qDebug() << model->fileName(model->index(i, 0)) << '\n';
}
});
}这里有一个QListView对象(*listView)和一个QFileSystemModel对象(*model)。我想迭代模型并做一些事情,比如打印文件的名称。输出是
C:不管是哪个目录,根路径都是。我想那是因为我没有作为家长传递任何东西。
发布于 2019-07-24 17:28:40
当您在调用QFileSystemModel中将父节点默认为QModelIndex()时,您只是访问model->index(i, 0)根的子节点。
如果您还想列出这些项的子项,我们也要迭代它们:
#include <QApplication>
#include <QDebug>
#include <QFileSystemModel>
void list_files(const QFileSystemModel *model, QModelIndex ix = {},
QString indent = {})
{
auto const row_count = model->rowCount(ix);
for (int i = 0; i < row_count; ++i) {
auto const child = model->index(i, 0, ix);
qDebug() << qPrintable(indent) << model->fileName(child);
list_files(model, child, indent + " ");
}
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QFileSystemModel model;
model.setRootPath(".");
list_files(&model);
}查看如何在恢复到list_files()时将子索引作为新父级传递。
注意,这个模型在这个阶段很可能是不完整的,因为它实现了延迟阅读--所以不要期望看到这个简单程序中的所有文件。
https://stackoverflow.com/questions/57187113
复制相似问题