Search code examples
c++cqtqtguiqfiledialog

Is there a native "file explorer" in Qt that I can use to have the user select path to a specific file?


I have a small application that requires the pathway to a specific file that will be given at run-time by the user. All I need is the path. I image this to be some form of a file explorer in which the user may traverse through the directory tree.

Is there a way to do this in Qt, or must I call the native OS implementation (if that is possible). If not in Qt, how can I make use of the local OS implementation?


Solution

  • This is what QFileDialog is trying to achieve, so I would suggest to use that if it is a widget based application. All you will need to write is something like this:

    fileName = QFileDialog::getOpenFileName(this,
    tr("Open Image"), "/home/jana", tr("Image Files (*.png *.jpg *.bmp)"));
    

    This will bring up a dialog for selection that the user can use for navigation.

    If you happen to use QML, you could give a try to the FileDialog component. Then, you would write something like this:

    import QtQuick 2.2
    import QtQuick.Dialogs 1.0
    
    FileDialog {
        id: fileDialog
        title: "Please choose a file"
        onAccepted: {
            console.log("You chose: " + fileDialog.fileUrls)
            Qt.quit()
        }
        onRejected: {
            console.log("Canceled")
            Qt.quit()
        }
        Component.onCompleted: visible = true
    }