简体   繁体   中英

Allow user to select a file or a folder in QFileDialog

In PyQt you can do something like the following to allow the user to select a file

filename = QtGui.QFileDialog.getOpenFileName(self, "Choose file..")

However I would like a QFileDialog to open in which the user would be able to select either a file or a directory. I'm sure I've seen this feature in PyQt applications before, but I can't seem to find any way to do it.

From what I remember you need to write your own QFileDialog and set proper mode . I believe this should be QFileDialog.ExistingFile & QFileDialog.Directory .

You can try to write your own static method basing on the getExisitingDirectory (from C++ repository):

QString QFileDialog::getExistingDirectory(QWidget *parent,
                                          const QString &caption,
                                          const QString &dir,
                                          Options options)
{
    if (qt_filedialog_existing_directory_hook && !(options & DontUseNativeDialog))
        return qt_filedialog_existing_directory_hook(parent, caption, dir, options);
    QFileDialogArgs args;
    args.parent = parent;
    args.caption = caption;
    args.directory = QFileDialogPrivate::workingDirectory(dir);
    args.mode = (options & ShowDirsOnly ? DirectoryOnly : Directory);
    args.options = options;

#if defined(Q_WS_WIN)
    if (qt_use_native_dialogs && !(args.options & DontUseNativeDialog) && (options & ShowDirsOnly)
#if defined(Q_WS_WINCE)
        && qt_priv_ptr_valid
#endif
        ) {
        return qt_win_get_existing_directory(args);
    }
#endif

    // create a qt dialog
    QFileDialog dialog(args);
    if (dialog.exec() == QDialog::Accepted) {
        return dialog.selectedFiles().value(0);
    }
    return QString();
}

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