首页 > 解决方案 > QMessageBox 上按钮的 buttonClicked() 方法

问题描述

当单击 QMessageBox 上的“确定”按钮时,我想调用“removeDuplicate”方法。但是当我单击按钮时,该方法不会执行。我应该怎么办?这是我的代码片段:

def removeDuplicate(self):
        curItem = self.listWidget_2.currentItem()
        self.listWidget_2.takeItem(curItem)

def error_popup(self):
        msg=QtWidgets.QMessageBox()
        msg.setText("You can't select more than one wicket-keeper.")
        msg.setWindowTitle(" ")
        msg.setIcon(QtWidgets.QMessageBox.Critical)
        x = msg.exec_()
        msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
        msg.buttonClicked.connect(self.removeDuplicate)

标签: pythonqtpyqt5qmessagebox

解决方案


试试看:

import sys
from PyQt5.Qt import *
from PyQt5 import QtGui, QtCore, QtWidgets


class Window(QWidget):
    def __init__(self):
        super().__init__()
        
        self.error_popup()

    def removeDuplicate(self):
        print('def removeDuplicate(self): ...')
#        curItem = self.listWidget_2.currentItem()
#        self.listWidget_2.takeItem(curItem)

    def error_popup(self):
        msg = QMessageBox.critical(
            self, 
            'Title', 
            "You can't select more than one wicket-keeper", 
            QMessageBox.Yes | QMessageBox.Cancel
        )
        if msg == QMessageBox.Yes:
#            msg.buttonClicked.connect(self.removeDuplicate)
            print('Ok')
            self.removeDuplicate()
        
if __name__ == "__main__":
    App = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(App.exec_())        

推荐阅读