7.qfilesystemmodel rowcount 为什么为0? 一个简单的model类的例子

任务:

1.新建一个空的mainwindow项目

2.debug下编译得到一个文件夹,应用程序输出这个文件夹中的文件(不显示文件夹中的文件夹)

3.使用QFileSystemModel完成。

本例显示结果:

Makefile

Makefile.Debug

Makefile.Release

ui_mainwindow

(debug和release是文件夹,不在应用程序输出中)

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

#include <QDebug>
#include <QDir>
#include <QFileSystemModel>
#include <QModelIndex>
#include <QFileInfo>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
    
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    
private:
    Ui::MainWindow *ui;
    QFileSystemModel *model;
private slots:
    void findDirectory(const QString &path);
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"



MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    model = new QFileSystemModel();
    model->setRootPath(QDir::currentPath());
    //这里直接调用rowCount函数返回0,
    //QFileSystemModel是异步载入目录,当directoryLoaded信号发射之后,表示目录载入完成
    //所以我们在槽中调用rowCount,返回正确的值。
    connect(model, SIGNAL(directoryLoaded(QString)), this, SLOT(findDirectory(QString)));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::findDirectory(const QString &path)
{
    QModelIndex parentIndex = model->index(QDir::currentPath());
    int row = model->rowCount(parentIndex);

    for(int i = 0; i<row; i++) {

        QModelIndex index = model->index(i, 0, parentIndex);
        QString text = index.data(Qt::DisplayRole).toString();
        QString fullPath = QDir::currentPath().append("/").append(text);

        QFileInfo *fileInfo = new QFileInfo(fullPath);

        if(fileInfo->isFile())
            qDebug() << text;
    }
}

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    
    return a.exec();
}

程序输出:

      

原文地址:https://www.cnblogs.com/billxyd/p/6914883.html