In this lesson we will learn how to use QFileDialog in qt.
The QFileDialog class provides a dialog that allow users to select files or directories.
First lets see how to use static function QFileDialog::getOpenFileName
Basic syntax of QFileDialog::getOpenFileName
1 |
[static] QString QFileDialog::getOpenFileName(QWidget *parent = Q_NULLPTR, const QString &caption = QString(), const QString &dir = QString(), const QString &filter = QString(), QString *selectedFilter = Q_NULLPTR, Options options = Options()) |
This is a convenience static function that returns an existing file selected by the user. If the user presses Cancel, it returns a null string.
1 2 3 |
QString fileName = QFileDialog::getOpenFileName(this, ("Open File"), "/home", ("Images (*.png *.xpm *.jpg)")); |
Now Lets create a Program and see how we can use QFileDialog::getOpenFileName in practice
File->New File or Project…
Applications->Qt Gui Application->Choose…
We keep the class as MainWindow as given by default.
Now write the code below in main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#include <QApplication> #include <QFileDialog> #include <QDebug> class QFileDialogTester : public QWidget { public: void openFile() { QString filename = QFileDialog::getOpenFileName( this, "Open Document", QDir::currentPath(), "All files (*.*) ;; Document files (*.doc *.rtf);; PNG files (*.png)"); if( !filename.isNull() ) { qDebug() << "selected file path : " << filename.toUtf8(); } } }; int main( int argc, char **argv ) { QApplication app( argc, argv ); QFileDialogTester test; test.openFile(); return 0; } |
Now build and run the program.

After selecting the file using open file dialog this code will print the path of the selected file in console.
OUTPUT
1 |
selected file path : "your/project/dir//coffee-cup-icon.png" |