【Qt】QDir


【目的】

  1. 使用 Qdir 列出所在所在目錄下的檔案。
  2. 搭配QTreeWidget列出所在目錄下的檔案。

【基本方式】

  • 程式
    #include <QtGui/QApplication>
    #include <QDir>
    #include <iostream>
    
    int main(int argc, char *argv[])
    {
      QCoreApplication app(argc, argv);
      QDir dir;
      dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
      dir.setSorting(QDir::Size | QDir::Reversed);
    
      QFileInfoList list = dir.entryInfoList();
      std::cout << "     Bytes Filename" << std::endl;
      for (int i = 0; i < list.size(); ++i)
      {
        QFileInfo fileInfo = list.at(i);
        std::cout << qPrintable(QString("%1 %2").arg(fileInfo.size(), 10)
                                                .arg(fileInfo.fileName()));
        std::cout << std::endl;
      }
    return 0;
    }
  • 結果
    image

【搭配QTree】

  • 程式
    #include <QApplication>
    #include <QTreeWidget>
    #include <QTreeWidgetItem>
    #include <QStringList>
    #include <QFile>
    #include <QFileInfo>
    #include <QDir>
    
    int main(int argc, char *argv[])
    {
      QApplication app(argc, argv);
    
      QTreeWidget *treeWidget = new QTreeWidget;
      treeWidget->setWindowTitle("QTreeWidget & Item");
      treeWidget->resize(400, 250);
      QStringList columnTitle;
      columnTitle.append("Name");
      treeWidget->setHeaderLabels(columnTitle);
      QFileInfo fileInfo(QCoreApplication::applicationDirPath());
      QStringList fileColumn;
      fileColumn.append(fileInfo.fileName());
      QTreeWidgetItem *dir = new QTreeWidgetItem(fileColumn);
      treeWidget->addTopLevelItem(dir);
      listFile(dir, fileInfo);
      treeWidget->show();
      return app.exec();
    }
    
    void listFile(QTreeWidgetItem *parentWidgetItem, QFileInfo &parent)
    {
      QDir dir;
      dir.setPath(parent.filePath());
      dir.setFilter(QDir::Files | QDir::Dirs | QDir::NoSymLinks);
      dir.setSorting(QDir::DirsFirst | QDir::Name);
      const QFileInfoList fileList = dir.entryInfoList();
      for (int i = 0; i < fileList.size(); i++) 
      {
        QFileInfo fileInfo = fileList.at(i);
        QStringList fileColumn;
        fileColumn.append(fileInfo.fileName());
        if (fileInfo.fileName() == "." || fileInfo.fileName() == ".." );
        else if(fileInfo.isDir()) 
        {
          QTreeWidgetItem *child = new QTreeWidgetItem(fileColumn);
          parentWidgetItem->addChild(child);
          listFile(child, fileInfo);
        }
        else
        {
          QTreeWidgetItem *child = new QTreeWidgetItem(fileColumn);
          parentWidgetItem->addChild(child);
        }
      }
    }
  • 結果

    image

【參考】

 

Ed32. Copyright 2008 All Rights Reserved Revolution Two Church theme by Brian Gardner Converted into Blogger Template by Bloganol dot com