【问题标题】:Check which button in an QMessageBox was clicked检查 QMessageBox 中的哪个按钮被点击
【发布时间】:2020-10-16 18:43:00
【问题描述】:

我应该如何检查以下 QMessageBox 中的哪个按钮被点击了? button == QMessageBox.Ok 不起作用。

class WarningWindow(QMessageBox):

    nextWindowSignal = pyqtSignal()

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

        self.setWindowTitle('A title')
        self.setText("Generic text")
        self.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        self.buttonClicked.connect(self.nextWindow)

    def nextWindow(self, button):
        if button == QMessageBox.Ok:
            print('ok')
        elif button == QMessageBox.Cancel:
            print('cancel')
        else:
            print('other)

        self.nextWindowSignal.emit()

【问题讨论】:

    标签: python button pyqt pyqt5 qmessagebox


    【解决方案1】:

    您必须将 QAbstractButton 转换为 QMessageBox::StandardButton 然后进行比较:

    def nextWindow(self, button):
        sb = self.standardButton(button)
        if sb == QMessageBox.Ok:
            print("ok")
        elif sb == QMessageBox.Cancel:
            print("cancel")
        else:
            print("other")
        self.nextWindowSignal.emit()
    

    【讨论】: