开发者

QSettings - File chooser should remember the last directory

I upload a file from a location, then the next upload has to point the last uploaded location. H开发者_如何学编程ow can I accomplish thus using QSettings?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜