How to Select a Directory in a Qt Widget Application in C++


In this article, we show how to select a diretory on a computer file system in a Qt widget application in C++.

So selecting a directory is very standard in many programs. Many programs utilize existing directories on a computer to work with in some form.

How can we select a directory on our computer in a Qt widget application?

Below is the program where we select a directory and then have its full path displayed on a line edit element.

Selecting a directory in a qt widget in c++

So you can see the 'Choose Directory' button on the right side of the application. Once this button is pressed, it opens up a standard file dialog window that allows you to select a directory.

Note that when you select this button, only directories are shown within the various file systems on your computer. There are non-directory files, such as text files, HTML files, image files, etc.

Once the directory is chosen, its full path then appears on the line edit element.

So the first thing you have to do is create a Qt widget application.

You will have to place 1 line edit element and 1 push button within this widget application.

We label one push button, 'Choose Directory', as it functions to select a file. We give this element an objectName of 'chooseDirectoryButton'.

With this, we now go to the heart of our code found in the 'widget.cpp' file.

Within this 'widget.cpp' file, we place the following contents shown below.

In order to select a directory on your computer and display its full path, we need to include the QFileDialog class.

We need the QFileDialog class in order to have the file dialog window open up when we click the 'Choose Directory' button in our program. This allows us to search our computer for an existing directory.

So we create a function, void Widget::on_chooseDirectoryButton_clicked(), which is executed when the 'Choose Directory' button is clicked.

We do a number of things within this function.

We create a variable, of type String, named filename. Into this variable, we will store the full path of the file. The getExistingDirectory() function gets all existing directories within a file system.

We make sure that the filename isn't empty by using an if statement with the isEmpty() function.

We then write the full file path to the line edit element using setText() function, passing in the filename as its parameter.

This is how we get the directory's full path to be displayed on the line edit element.

And this is how to select a directory in a Qt widget in C++.

Related Resources

How to Write to a File in C++

HTML Comment Box is loading comments...