简体   繁体   English

允许用户在QFileDialog中选择文件或文件夹

[英]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 在PyQt中,您可以执行以下操作以允许用户选择文件

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. 但是我希望打开一个QFileDialog ,用户可以在其中选择文件或目录。 I'm sure I've seen this feature in PyQt applications before, but I can't seem to find any way to do it. 我确定我之前在PyQt应用程序中看过这个功能,但我似乎无法找到任何方法。

From what I remember you need to write your own QFileDialog and set proper mode . 从我记得你需要编写自己的QFileDialog并设置正确的模式 I believe this should be QFileDialog.ExistingFile & QFileDialog.Directory . 我相信这应该是QFileDialog.ExistingFile & QFileDialog.Directory

You can try to write your own static method basing on the getExisitingDirectory (from C++ repository): 您可以尝试基于getExisitingDirectory(来自C ++存储库)编写自己的静态方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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