How to use QDir and QFileDialog in Qt
Overview[edit | edit source]
This code snippets shows how to get a list of files from a given directory and how to use QFileDialog to select directories. The method QDir::entryList() returns a list of the names of all the files and directories in the directory. QFileDialog::getExistingDirectory() will return an existing directory selected by the user, this dialog can allow you to select directory of your choice.
This snippet can be self-signed as it does not use any API which require developer/certified signing.
Headers required[edit | edit source]
- include <QDir>
- include <QFileDialog>
Source[edit | edit source]
- include <QtGui/QApplication>
- include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
- ifndef MAINWINDOW_H
- define MAINWINDOW_H
- include <QtGui/QMainWindow>
- include <QDir>
namespace Ui
{
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void changeDirectory();
void fillList();
private:
Ui::MainWindow *ui;
QDir directory;
};
- endif // MAINWINDOW_H
- include <QFileDialog>
- include "mainwindow.h"
- include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow), directory("/")
{
ui->setupUi(this);
connect(ui->actionChange_directory, SIGNAL(triggered()), this, SLOT(changeDirectory()));
fillList();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::changeDirectory()
{
/* select a directory using file dialog */
QString path = QFileDialog::getExistingDirectory (this, tr("Directory"), directory.path());
if ( path.isNull() == false )
{
directory.setPath(path);
fillList();
}
}
/*get list of file from given directory and the append it to listWidget */
void MainWindow::fillList()
{
ui->listWidget->clear();
ui->listWidget->addItems(directory.entryList());
}
Postconditions[edit | edit source]
The code snippet is expected to show get a list of files in a given directory.
Select/change Directory using QFileDialog
File:SelectDirectory.JPG
Get list of files using QDir
File:GetFileList.JPG
External Links[edit | edit source]
- QDir: QDir reference
- QFileDialog: QFileDialog reference
Code Example[edit | edit source]
- The Code Example will show how to get list of files from given directory and is tested on Nokia 5800 XpressMusic.
Related Links[edit | edit source]
pt:Archived:Como usar QDir e QFileDialog, em Qt