zoukankan      html  css  js  c++  java
  • 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();
    }

    程序输出:

          

  • 相关阅读:
    TensorFlow学习('utf-8' codec can't decode byte 0xff in position 0: invalid start byte)
    Python常用库之三:Matplotlib
    线性回归 Python实现
    go 算法 查询字符在字符串中的位置
    Python与Go快速排序
    Python与Go斐波那契数列
    Python与Go选择排序
    Python与Go插入排序
    Python与Go冒泡排序
    git clone直接提交用户名和密码
  • 原文地址:https://www.cnblogs.com/billxyd/p/6914883.html
Copyright © 2011-2022 走看看