允许用户在 QFileDialog 中选择文件或文件夹 [英] Allow user to select a file or a folder in QFileDialog

查看:118
本文介绍了允许用户在 QFileDialog 中选择文件或文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PyQt 中,您可以执行以下操作以允许用户选择文件

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

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

但是,我希望打开一个 QFileDialog,用户可以在其中选择文件或目录.我确定我以前在 PyQt 应用程序中看到过这个功能,但我似乎找不到任何方法来做到这一点.

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.

推荐答案

据我所知,您需要编写自己的 QFileDialog 并设置适当的 模式.我相信这应该是 QFileDialog.ExistingFile &QFileDialog.Directory.

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

您可以尝试基于 getExisitingDirectory(来自 C++ 存储库)编写自己的静态方法:

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

这篇关于允许用户在 QFileDialog 中选择文件或文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆