7.qfilesystemmodel rowcount 為什麽為0? 一個簡單的model類的例子
阿新 • • 發佈:2017-05-28
不顯示 tro display ica directory find .cpp this int
任務:
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(); }
程序輸出:
7.qfilesystemmodel rowcount 為什麽為0? 一個簡單的model類的例子