簡體   English   中英

QModelIndex作為父級?

[英]QModelIndex as parent?

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

無論rootpath在哪個目錄中。 我認為那是因為我沒有作為父母通過任何事情。

在調用model->index(i, 0)中將父節點默認為QModelIndex()時,您只是在訪問QFileSystemModel根的子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()時如何將子級索引作為新的父級傳遞?

請注意,該模型在此階段可能很不完整,因為它實現了延遲讀取-因此,不要指望通過此簡單程序即可看到所有文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM