Display File Path After Choosing File From Dialog in Qt 6

Display File Path After Choosing File From Dialog in Qt 6

Qt, a powerful C++ framework, provides a user-friendly way to create cross-platform applications with a graphical user interface. One common requirement in applications is to allow users to choose a file using a file dialog, and then display the selected file's path for further processing. This tutorial explains how to display file path after choosing file from dialog in Qt 6.

The provided code creates a simple Qt application which consists of a window containing a horizontal layout, which includes a button and label. When the button is clicked, a file dialog is shown, allowing the user to select a file. If a file is chosen, the label's text is updated to include the selected file's path.

#include <QApplication>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QFileDialog>

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

    auto *window = new QWidget();
    QHBoxLayout layout(window);
    QPushButton button("Choose File", window);
    QLabel label("File Path:", window);

    QObject::connect(&button, &QPushButton::clicked, [&]() {
        QString filePath = QFileDialog::getOpenFileName(window, "Choose File");
        if (!filePath.isEmpty()) {
            label.setText("File Path: " + filePath);
        }
    });

    layout.addWidget(&button);
    layout.addWidget(&label);
    window->setLayout(&layout);
    window->show();

    return QApplication::exec();
}

Here's how the application looks:

File path after choosing file from dialog in Qt

Leave a Comment

Cancel reply

Your email address will not be published.