QModelIndex 作为父级?

QModelIndex as parent?

本文关键字:QModelIndex      更新时间:2023-10-16

在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:

无论根路径是哪个目录。我认为这是因为我作为父母没有传递任何东西。

当您在调用model->index(i, 0)中默认父节点为QModelIndex()时,您只是在访问QFileSystemModel根的子节点。

如果您还想列出这些项的子项,我们也希望迭代它们:

#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()时,我们如何将子索引作为新的父索引传递?

请注意,该模型在此阶段可能不完整,因为它实现了延迟阅读 - 所以不要指望用这个简单的程序看到所有文件。