新建QtGUI應用,基於QDialog,取消界面建立this
#include "dialog.h" Dialog::Dialog(QWidget *parent) : QDialog(parent) { setWindowTitle(tr("File View")); fileLineEdit = new QLineEdit(tr("/")); fileListWidget = new QListWidget; mainLayout = new QVBoxLayout(this); mainLayout->addWidget(fileLineEdit); mainLayout->addWidget(fileListWidget); connect(fileLineEdit,SIGNAL(returnPressed()),this,SLOT(slotShow(QDir))); connect(fileListWidget,SIGNAL(itemDoubleClicked(QListWidgetItem*)),this,SLOT(slotDirShow(QListWidgetItem*))); QString root = "/"; QDir rootDir(root); QStringList string; string << "*"; QFileInfoList list = rootDir.entryInfoList(string); showFileInfoList(list); } Dialog::~Dialog() { } //顯示dir下的全部文件 void Dialog::slotShow(QDir dir) { QStringList string; string<<"*"; QFileInfoList list=dir.entryInfoList(string,QDir::AllEntries,QDir::DirsFirst); //文件名的過濾方式。列出目錄,文件,磁盤驅動器。目錄優先排序 showFileInfoList(list); } //用戶雙擊進入下一級目錄,單擊".."返回上級,頂部的編輯框顯示當前所在的目錄,類表顯示該目錄下全部文件 void Dialog::showFileInfoList(QFileInfoList list) { fileListWidget->clear(); for(unsigned int i = 0; i < list.count(); i++) //從類表中依次取出全部項 { QFileInfo tmpFileInfo = list.at(i); if(tmpFileInfo.isDir()) { QIcon icon("dir.png"); QString fileName = tmpFileInfo.fileName(); QListWidgetItem *tmp = new QListWidgetItem(icon, fileName); fileListWidget->addItem(tmp); } else if(tmpFileInfo.isFile()) { QIcon icon("file.png"); QString fileName=tmpFileInfo.fileName(); QListWidgetItem *tmp = new QListWidgetItem(icon,fileName); fileListWidget->addItem(tmp); } } } //顯示下一級目錄中的全部文件 void Dialog::slotDirShow(QListWidgetItem * item) { QString str = item->text(); //將下一級的目錄名保存在str中 QDir dir; dir.setPath(fileLineEdit->text());//設置QDir對象的路徑爲當前目錄路徑 dir.cd(str);//切換路徑 fileLineEdit->setText(dir.absolutePath());//刷新當前的目錄路徑 slotShow(dir); }
entryInfoList按照某種過濾方式獲取目錄下的文件列表code