开发者

QFiledialog returns the incorrect directory

开发者 https://www.devze.com 2023-02-06 18:35 出处:网络
A snippet of what i\'m using looks like this QDir lastDir; QFileDialog dial(this); dial.getOpenFileName(this,

A snippet of what i'm using looks like this

QDir lastDir;
QFileDialog dial(this);

dial.getOpenFileName(this,
                     tr("Open File"),
                     QString("/home"),
                     tr("Raw Images (*.nef *.NEF *.dng *.DNG)"));

lastDir = dial.开发者_运维问答directory();
qDebug() << lastDir;

The output, is completely wrong, no matter which directory I end up in. However, the incorrect directory is always the same.

AFAICT i'm doing nothing wrong here. What is going on here? Cheers


getOpenFileName() is a static function which immediately opens a "file picker" dialog and returns, once the user is finished with the dialog, "an existing file selected by the user". You use it like this (note the use of :: and the class name QFileDialog instead of the object name):

QString fileName = QFileDialog::getOpenFileName(this,
                 tr("Open File"),
                 QString("/home"),
                 tr("Raw Images (*.nef *.NEF *.dng *.DNG)"));

directory() is non-static and returns "the directory currently being displayed in the dialog". This function is meant to be called while the dialog is still open, it's intended for use cases which are not covered by the static calls.


What is happening here is you have instantiated an object, called a static function on it (which won't affect its state), and then called directory() which will just reflect the original state of the object, which is probably the working directory. Instead, you need to store the return value of the getOpenFileName() call in a variable, as shown above.

If you want to ask the user to just choose a directory, you could consider using getExistingDirectory() instead. Alternatively, if you want to extract the directory from the filename, the QDir class has some functions useful for this.

0

精彩评论

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

关注公众号