×
Namespaces

Variants
Actions

How to use QDir and QFileDialog in Qt

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Code ExampleTested with
Devices(s): Nokia 5800 XpressMusic
Compatibility
Platform(s): Qt
Symbian
Article
Keywords: QFileDialog::getExistingDirectory(), QDir::entryList()
Created: ebra (16 Jun 2009)
Last edited: hamishwillee (11 Oct 2012)

Contents

Overview

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

#include <QDir>
#include <QFileDialog>

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

The code snippet is expected to show get a list of files in a given directory.

Select/change Directory using QFileDialog

SelectDirectory.JPG

Get list of files using QDir

GetFileList.JPG

External Links

Code Example

  • The Code Example will show how to get list of files from given directory and is tested on Nokia 5800 XpressMusic.

Related Links

This page was last modified on 11 October 2012, at 04:17.
571 page views in the last 30 days.