Qt Tutorials For Beginners – QFileDialog::getOpenFileName Example




Qt Tutorials For Beginners
Qt Tutorials For Beginners

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

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

  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

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

QFileDialog getOpenFileName Demo
QFileDialog getOpenFileName Demo

After selecting the file using open file dialog this code will print the path of the selected file in console.

OUTPUT

selected file path :  "your/project/dir//coffee-cup-icon.png"

 


Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





2 Comments

  1. to make a C # application on windows allows us to integrate a linux terminal, an analyzer and detect the networks equipment such as routers are …. this is possible? in fact to make in C # an application on windows allows us to integrate a linux terminal, an analyzer and detect the networks equipment such as routers are …. this is possible?

  2. hi i want to make a C # application on windows allows us to integrate a linux terminal, an analyzer and detect the networks equipment such as routers are …. this is possible? in fact to make in C # an application on windows allows us to integrate a linux terminal, an analyzer and detect the networks equipment such as routers are …. this is possible?

Leave a Reply

Your email address will not be published.


*