Des*_*ond 6 python pyqt pyqt5 pyqt6
我正在尝试将我的脚本从 PyQt5 移植到 PyQt6。由于这个答案,我已经弄清楚如何移植大部分内容,但是,我遇到了一个问题。
我发现 PyQt6 使用QtWidgets.QMessageBox.StandardButtons.Yes
而不是 PyQt5QtWidgets.QMessageBox.Yes
.
但是,当检查用户在 QMessageBox 打开后是否按下“是”时,替换QtWidgets.QMessageBox.Yes
为QtWidgets.QMessageBox.StandardButtons.Yes
不起作用(请检查下面的示例)。
例子:
PyQt5:
reply = QtWidgets.QMessageBox()
reply.setText("Some random text.")
reply.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
x = reply.exec_()
if x == QtWidgets.QMessageBox.Yes:
print("Hello!")
Run Code Online (Sandbox Code Playgroud)
打印“你好!” 这里工作正常。(16384 == 16384)
PyQt6:
reply = QtWidgets.QMessageBox()
reply.setText("Some random text.")
reply.setStandardButtons(QtWidgets.QMessageBox.StandardButtons.Yes |
QtWidgets.QMessageBox.StandardButtons.No)
x = reply.exec()
if x == QtWidgets.QMessageBox.StandardButtons.Yes:
print("Hello!")
Run Code Online (Sandbox Code Playgroud)
“你好!” 这里根本不打印。(16384 != StandardButtons.yes)
我知道我可以这样做:
x = reply.exec()
if x == 16384:
print("Hello!")
Run Code Online (Sandbox Code Playgroud)
因为,按“是”后,QMessageBox 等于 16384(请参阅此),但我不想使用这种方法,而是使用 PyQt5 示例之类的方法。
小智 6
StandardButtons 不是我可以为 QMessageBox 选择的属性/方法。不确定这是否在过去 4 个月内更新过,但对我来说,代码适用于StandardButton而不是StandardButtons。
from PyQt6.QtWidgets import QMessageBox
reply = QMessageBox()
reply.setText("Some random text.")
reply.setStandardButtons(QMessageBox.StandardButton.Yes |
QMessageBox.StandardButton.No)
x = reply.exec()
if x == QMessageBox.StandardButton.Yes:
print("Hello!")
Run Code Online (Sandbox Code Playgroud)
这有点奇怪。根据QMessageBox.exec的文档:
当使用带有标准按钮的 QMessageBox 时,此函数返回一个 StandardButton 值,指示单击的标准按钮。
您正在使用标准按钮,因此这应该返回一个QMessageBox.StandardButtons
枚举。
还值得一提的是,在 PyQt5 中比较整数和枚举不是问题,因为枚举是用enum.IntEnum
. 现在,它们是通过enum.Enum
. 来自Riverbank 计算网站:
所有枚举现在都实现为 enum.Enum (PyQt5 使用 enum.IntEnum 作为作用域枚举,并使用自定义类型作为传统命名枚举)。只要需要枚举,PyQt5 就允许使用 int,但 PyQt6 需要正确的类型。
但是,由于某种原因,QMessageBox.exec
返回一个整数(我刚刚用 尝试过PyQt6==6.0.0
)!
现在,您可以通过从返回的整数故意构造一个枚举对象来解决这个问题:
if QtWidgets.QMessageBox.StandardButtons(x) == QtWidgets.QMessageBox.StandardButtons.Yes:
print("Hello!")
Run Code Online (Sandbox Code Playgroud)
而且,由于您正在比较枚举,我建议使用is
而不是==
.
归档时间: |
|
查看次数: |
7380 次 |
最近记录: |