QSettings - File chooser should remember the last directory

陌路散爱 提交于 2019-11-27 21:29:01

问题


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?


回答1:


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 + "'");
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/3597900/qsettings-file-chooser-should-remember-the-last-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!