tags:

views:

207

answers:

1

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.

Thank you :)

+1  A: 

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();
}
gruszczy