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()
时,我们如何将子索引作为新的父索引传递?
请注意,该模型在此阶段可能不完整,因为它实现了延迟阅读 - 所以不要指望用这个简单的程序看到所有文件。
相关文章:
- 从 QFileSystemModel 中的文件路径和文件名获取 QModelIndex
- QModelIndex 作为父级?
- 无法通过 QModelIndex 从 QTreeView 获取项目
- Qt QModelIndex::sibling return parent QModelIndex
- 重载的 QAbstractItemModel::flags 应该为无效的 QModelIndex 返回什么
- 如何从 QML 访问 QModelIndex 行
- QModelIndex to QJSValue
- Wrong QModelIndex on QTreeView using custom QSortFilterProxy
- QModelIndex::数据不工作
- QAbstractModel - 无法获取 QAbstractModelItem with getItem an QModelIndex
- 是否可以从列和行中获取QModelIndex
- 是否可以从QModelIndex获取Qpoint
- 在 QModelIndex 中存储两种不同的类型
- QmodelIndex和标头数据
- 在Model中查找新条目的QModelIndex
- Qt -获得一个没有视图的QModelIndex
- 更容易在QTreeView中找到QModelIndex的可见行
- 获取索引时qmodelindex的父参数
- 如何使用QModelIndex访问QStandardItemModel及其数据?
- 删除行时,QModelIndex无效