Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QSettings - File chooser should remember the last directory

Tags:

qt

qsettings

I upload a file from a location, then the next upload has to point the last uploaded location. How can I accomplish thus using QSettings?

like image 948
user198725878 Avatar asked Aug 30 '10 04:08

user198725878


2 Answers

Before using QSettings, I would suggest, in your main() to set a few informations about your application and your company, informations that QSettings will be using :

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    a.setApplicationName("test");
    a.setOrganizationName("myorg");
    a.setOrganizationDomain("myorg.com");

    // etc...
    return a.exec();
}

Then, when selecting a file with QFile::getOpenFileName()(for instance), you can read from a key of QSetting the last directory. Then, if the selected file is valid, you can store/update the content of the key :

void Widget::on_tbtFile_clicked() {
    const QString DEFAULT_DIR_KEY("default_dir");

    QSettings MySettings; // Will be using application informations
                          // for correct location of your settings

    QString SelectedFile = QFileDialog::getOpenFileName(
        this, "Select a file", MySettings.value(DEFAULT_DIR_KEY).toString());

    if (!SelectedFile.isEmpty()) {
        QDir CurrentDir;
        MySettings.setValue(DEFAULT_DIR_KEY,
                            CurrentDir.absoluteFilePath(SelectedFile));

        QMessageBox::information(
            this, "Info", "You selected the file '" + SelectedFile + "'");
    }
}
like image 53
Jérôme Avatar answered Sep 29 '22 22:09

Jérôme


If you are talking about QFileDialog() you can specify the starting directory in the constructor:

QFileDialog::QFileDialog(QWidget * parent = 0, const QString & caption = 
  QString(), const QString & directory = QString(), const QString & filter =
  QString())

Or you can use one of the helper functions like this one which also allow you to specify the starting directory:

QString QFileDialog::getOpenFileName(QWidget * parent = 0,
    const QString & caption = QString(), const QString & dir = QString(), 
    const QString & filter = QString(), QString * selectedFilter = 0, 
    Options options = 0)

After each use, store the directory path that was selected and use it the next time you display the dialog.

like image 44
Arnold Spence Avatar answered Sep 29 '22 22:09

Arnold Spence