PyQt4 和 PyQt5 中的 QFileDialog 字符串有区别吗? [英] Is there a difference between QFileDialog strings in PyQt4 and PyQt5?

查看:21
本文介绍了PyQt4 和 PyQt5 中的 QFileDialog 字符串有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段使用 Python3 和 PyQt5 打开 QFileDialog 的代码块:

I have a block of code that opens a QFileDialog using Python3 and PyQt5:

from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFileDialog
import sys


class MCVE(QWidget):

    def __init__(self):
        super().__init__()
        self.initialize()

    def initialize(self):
        self.setWindowTitle('MCVE')
        self.setGeometry(50, 50, 400, 200)
        btn = QPushButton('Example', self)
        btn.clicked.connect(self.clicked)

        self.show()

    def clicked(self):
        filename = QFileDialog.getOpenFileName(
            self, "Open Template", "c:\",
            "Templates (*.xml);;All Files (*.*)")

        print(filename)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MCVE()
    sys.exit(app.exec_())

在使用 PyQt4 的 Python 2 中,print(filename) 语句在按下取消按钮后,输出为空字符串.当我使用 PyQt5 在 Python 3 中运行相同的代码时,我得到:

In Python 2 using PyQt4 the print(filename) statement, after pressing the cancel button, outputs as an empty string. When I run the same code in Python 3 using PyQt5 I get:

('', '')

注意:引号是单引号

谁能解释一下这是怎么回事?我在 PyQt4 和 PyQt5 之间的文档下找不到任何内容.我知道字符串在 Python 2 和 Python 3 之间发生了变化,但我不确定这些变化会导致这样的问题.谢谢!

Can someone explain what is going on? I couldn't find anything under the documentation between PyQt4 and PyQt5. I know that strings changed between Python 2 and Python 3, but I'm not sure those changes would cause an issue like this. Thanks!

推荐答案

PyQt4 中的getOpenFileName 函数返回一个字符串,该字符串是所选文件的名称,如果没有选择,则返回一个空字符串.

The getOpenFileName function in PyQt4 returns a string that is the name of the selected file, and if none is selected then it returns an empty string.

filename = QFileDialog.getOpenFileName(self, "Open Template", "c:\", "Templates (*.xml);;All Files (*.*)")

然而,在 PyQt5 中,这会返回一个包含 2 个元素的元组,其中第一个元素是一个与 PyQt4 中行为相同的字符串,第二个元素是使用的过滤器.

However in PyQt5 this returns a tuple of 2 elements where the first one is a string that has the same behavior as in PyQt4, and the second element is the filter used.

filename, filters = QFileDialog.getOpenFileName(self, "Open Template", "c:\", "Templates (*.xml);;All Files (*.*)")

注意:PyQt5 的大部分文档都在 Qt5 中,因为通常方法的名称、输入和结果是相似的.

这篇关于PyQt4 和 PyQt5 中的 QFileDialog 字符串有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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