简体   繁体   中英

QFileDialog::getExistingDirectory does not close after choosing a folder

In Qt,

QFileDialog *dlg = new QFileDialog(); 
QDir dir = dlg->getExistingDirectory(this, tr("Choose folder"), qgetenv("HOME"));

opens a folder choose dialog. Once I select a folder (press choose button) the folder is not closing automatically. So I tried:

if(dlg->close() == true) delete(dlg);

When I debug the dlg->close() returns true and the code delete(dlg) is hit. Still the Folder chooser dialog box is not closing.

I am using Ubuntu 11.10 64 bit OS. Using Qt libraries from the repository.

My ultimate aim is just to show a folder chooser dialog and once the folder is chosen the dialog should close. After that processing should continue. How to do this?

Thanks in advance.

Even if QFileDialog::getExistingDirectory is static and doesn't need a QFileDialog object to work, it should close the dialog window when a directory is finally chosen. By default that function tries to open a native file dialog window, which seems to cause some problems on some platforms.

You should try forcing a non-native dialog by adding the option DontUseNativeDialog :

QString dir = QFileDialog::getExistingDirectory(
    this, 
    tr("Choose folder"),
    QDesktopServices::storageLocation(QDesktopServices::HomeLocation),
    QFileDialog::ShowDirsOnly | QFileDialog::DontUseNativeDialog);

And remove the two other lines (with new QFileDialog and if(dlg->close()) ... ).

getExistingDirectory(...)是静态函数。

To add to cmannett85's answer:

You should not make an instance of QDialog . If you do, it's up to you to hide it. Modify your code to read

const QString home = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
const QDir dir = QFileDialog:getExistingDirectory(this, tr("Choose folder"), home);

This code should be relatively portable. qgetenv("HOME") is Unix-specific. You should not introduce gratuituous platform-specific code in Qt-based projects -- it sort of defeats the purpose of using Qt in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM