QFiledialog 返回错误的目录
我正在使用的代码片段如下所示
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;
无论我最终进入哪个目录,输出都是完全错误的。但是,错误的目录总是相同的。
AFAICT 我在这里没有做错任何事。这是怎么回事?干杯
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
getOpenFileName()
是一个静态函数,立即打开“文件选择器”对话框,并在用户完成该对话框后返回“用户选择的现有文件”。您可以像这样使用它(请注意使用::
和类名QFileDialog
而不是对象名称):directory()
是非静态的,返回“当前在对话框中显示的目录”。该函数应该在对话框仍然打开时调用,它适用于静态调用未涵盖的用例。这里发生的事情是您实例化了一个对象,在其上调用静态函数(这不会影响其状态),然后调用
directory()
这将仅反映该对象的原始状态,这可能是工作目录。相反,您需要将getOpenFileName()
调用的返回值存储在变量中,如上所示。如果您想让用户只选择一个目录,您可以考虑使用
getExistingDirectory()
相反。或者,如果您想从文件名中提取目录,则QDir
类有一些对此有用的函数。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 nameQFileDialog
instead of the object name):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 thegetOpenFileName()
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, theQDir
class has some functions useful for this.