【目的】
- 使用 Qdir 列出所在所在目錄下的檔案。
- 搭配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; }
- 結果
【搭配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); } } }
- 結果
【參考】
- Qt4 Gossip: QTreeWidget 與 QTreeWidgetItem
http://caterpillar.onlyfun.net/Gossip/Qt4Gossip/QTreeWidgetQTreeWidgetItem.html - QDir Class Reference
http://doc.qt.nokia.com/4.6/qdir.html