我正在尝试将我的脚本从PyQt5移植到PyQt6。多亏了这个答案,我已经找到了如何移植大部分东西的方法,然而,我遇到了一个问题。
我发现PyQt6使用QtWidgets.QMessageBox.StandardButtons.Yes而不是PyQt5 5的QtWidgets.QMessageBox.Yes。
但是,在检查QMessageBox打开后用户是否按下“是”时,用QtWidgets.QMessageBox.StandardButtons.Yes替换QtWidgets.QMessageBox.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!")打印“你好!”这里正常工作。(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!")“你好!”这里一点也不打印。(16384 != StandardButtons.yes)
我知道我可以这么做:
x = reply.exec()
if x == 16384:
print("Hello!")因为,在按下“是”后,QMessageBox等于16384 (看看这个),但我不想使用这种方法,而是使用类似于PyQt5的示例。
发布于 2021-01-15 12:46:11
这有点奇怪。根据QMessageBox.exec的文档
当使用带有标准按钮的QMessageBox时,此函数返回一个StandardButton值,指示单击的标准按钮。
您使用的是标准按钮,因此应该返回一个QMessageBox.StandardButtons枚举。
还值得一提的是,在PyQt5中比较整数和枚举不是问题,因为枚举是用enum.IntEnum实现的。现在,它们是用enum.Enum实现的。来自河岸计算网站
所有枚举现在都实现为enum.Enum (PyQt5使用enum.IntEnum表示作用域枚举,并为传统命名枚举使用自定义类型)。PyQt5允许在需要枚举时使用int,但是PyQt6需要正确的类型。
但是,由于某种原因,QMessageBox.exec返回一个整数(我刚刚用PyQt6==6.0.0尝试过)!
现在,您可以通过有意地从返回的整数构造一个enum对象来解决这个问题:
if QtWidgets.QMessageBox.StandardButtons(x) == QtWidgets.QMessageBox.StandardButtons.Yes:
print("Hello!")而且,由于您比较枚举,我建议使用is而不是==。
发布于 2021-01-17 08:22:35
QtWidgets.QMessageBox.StandardButtons是在PyQt6中使用enum.Flag实现的,而QDialog.exec()则返回int。遗憾的是,这些不能直接比较,但您仍然可以使用:
if x == QtWidgets.QMessageBox.StandardButtons.Yes.value:
print("Hello!")注意,惯用的x == int(Yes)也不起作用。
PyQt5使用了一个包装的自定义StandardButtons类(输入Yes | No来查看这个类),而不是另一个答案所声称的enum.IntEnum。然而,IntEnum本来是一个合乎逻辑的选择,因为它专门允许int比较。
发布于 2021-05-29 17:36:15
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!")https://stackoverflow.com/questions/65735260
复制相似问题