×
Namespaces

Variants
Actions
Revision as of 09:34, 3 September 2009 by croozeus (Talk | contribs)

How to use QDir and QFileDialog in Qt

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Tested with
Devices(s): Nokia 5800 XpressMusic
Compatibility
Platform(s): S60 3rd Edition, FP1, FP2
S60 5th Edition
Symbian
Article
Keywords: QFileDialog::getExistingDirectory(), QDir::entryList()
Created: (18 Jun 2009)
Last edited: croozeus (03 Sep 2009)

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 the 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.

Preconditions

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

556 page views in the last 30 days.