How to Select and Display the Full Path of a File in a Qt Widget Application in C++


C++


In this article, we show how to select a file on a computer and display the full path of the file in a Qt widget application in C++.

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

How can we select a file on our computer and display the file's full path?

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

Selecting and displaying the full path of a file in a qt widget in c++

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

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

You can then do things such as make a copy of this file or whatever task you want to achieve. We're not going to do anything with this file that we select. In this article, we simply show how to select a file and then display its full path.

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 buttons within this widget application.

We label one push button, 'Select File', as it functions to select a file. We give this element an objectName of 'selectFileButton'.

We label the line edit element the objectName of 'selectedFile', since this represents the original file that you select.

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 file on your computer and display its full path, we need to include a few classes.

We need the QFile class in order to work with files on your computer. This allows us to do things such as open and save files.

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

So we create a function, void Widget::on_selectFileButton_clicked(), which is executed when the 'Select File' 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.

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 file's full path to be displayed on the line edit element.

And this is how to select a file and display the full path of the file in a Qt widget in C++.


Related Resources

How to Write to a File in C++

HTML Comment Box is loading comments...