How to use QDir and QFileDialog in Qt

From Qt Wiki
Jump to navigation Jump to search

Template:ArticleMetaData

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]

  1. include <QDir>
  2. include <QFileDialog>

Source[edit | edit source]

  1. include <QtGui/QApplication>
  2. include "mainwindow.h"

int main(int argc, char *argv[]) {

   QApplication a(argc, argv);
   MainWindow w;
   w.show();
   return a.exec();

}

  1. ifndef MAINWINDOW_H
  2. define MAINWINDOW_H
  1. include <QtGui/QMainWindow>
  2. 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;

};

  1. endif // MAINWINDOW_H

  1. include <QFileDialog>
  2. include "mainwindow.h"
  3. 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]

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