PyQt6的“QMessageBox.Yes”替代方案

2024-10-01 07:40:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将我的脚本从PyQt5移植到PyQt6。多亏了this answer,我已经知道了如何移植大多数东西,但是,我遇到了一个问题

我发现PyQt6使用QtWidgets.QMessageBox.StandardButtons.Yes而不是PyQt5的QtWidgets.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!")

在这里打印“你好!”正常工作(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!")

因为,在按下“Yes”之后,QMessageBox等于16384(see this),但是我想使用这种方法,而是使用类似PyQt5示例的方法


Tags: 示例helloifsomethisreplypyqt5yes
3条回答

StandardButtons不是我可以为QMessageBox选择的属性/方法。不确定这是否在过去4个月内更新过,但对我来说,代码使用的是标准按钮,而不是标准按钮

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!")

QtWidgets.QMessageBox.StandardButtons在PyQt6中使用^{}实现,而QDialog.exec()返回一个int。遗憾的是,这些无法直接比较,但您仍然可以使用:

if x == QtWidgets.QMessageBox.StandardButtons.Yes.value:
    print("Hello!")

注意,惯用的x == int(Yes)也不起作用

PyQt5使用了一个包装的自定义StandardButtons类(键入Yes | No来查看),而不是另一个答案所声称的^{}。一个IntEnum本来是一个合乎逻辑的选择,但是因为它特别允许int比较

这有点奇怪。根据QMessageBox.exec的文件:

When using a QMessageBox with standard buttons, this function returns a StandardButton value indicating the standard button that was clicked.

您使用的是标准按钮,因此应该返回一个QMessageBox.StandardButtons枚举

还值得一提的是,在PyQt5中比较整数和枚举不是问题,因为枚举是用enum.IntEnum实现的。现在,它们是用enum.Enum实现的。从Riverbank Computing website开始:

All enums are now implemented as enum.Enum (PyQt5 used enum.IntEnum for scoped enums and a custom type for traditional named enums). PyQt5 allowed an int whenever an enum was expected but PyQt6 requires the correct type.

然而,由于某种原因,QMessageBox.exec返回一个整数(我刚刚用PyQt6==6.0.0尝试过它)

目前,您可以通过故意从返回的整数构造枚举对象来解决此问题:

if QtWidgets.QMessageBox.StandardButtons(x) == QtWidgets.QMessageBox.StandardButtons.Yes:
            print("Hello!")

而且,由于您正在比较枚举,我建议使用is而不是==

相关问题 更多 >