Search code examples
c++qtqfiledialogqsettings

Qt File Dialog doesn't remember the last directory after restarting project


I'm loading some files for my project....but every time the fileDialog directory is my root directory...

I want the fileDialog to remember my path and I've tried the solution in the following link qsettings-file-chooser-should-remember-the-last-directory but this worked for me for the same session only.

Is there a way to save the directory for other sessions?(when closing the application and re-opening it)?


Solution

  • You can use the QSettings class.
    This is simple example:
    widget.h

    #define WIDGET_H
    
    #include <QWidget>
    #include <QSettings>
    
    class Widget : public QWidget
    {
        Q_OBJECT
    
    public:
        Widget(QWidget *parent = 0);
        ~Widget();
    
    private:
        QString lastDir;
        QSettings *settings;
        void settingsLoader();
        void settingsSaver();
    };
    
    #endif // WIDGET_H
    

    widget.cpp

    #include <QFileDialog>
    #include "widget.h"
    
    Widget::Widget(QWidget *parent)
        : QWidget(parent)
    {
        settings = new QSettings("MyCompany", "My soft name", this);
        settingsLoader();
        lastDir = QFileDialog::getExistingDirectory(this, tr("Open directory"), lastDir);
    }
    
    void Widget::settingsLoader()
    {
        lastDir = settings->value("LastDir", QDir::homePath()).toString();
    }
    
    void Widget::settingsSaver()
    {
        settings->setValue("LastDir", lastDir);
    }
    
    Widget::~Widget()
    {
        settingsSaver();
    }