简体   繁体   中英

How to add custom button to a QMessageBox in PyQt4

I am coding a application which needs a custom buttons in QMessageBox. i managed to create an example in QT designer which is given below.

在此处输入图片说明

i wanted to do this in a QMessageBox.

I am using python 2.6.4 and PyQt4. please, can any one help.

Here is an example of building a custom message box from the ground up.

import sys
from PyQt4 import QtCore, QtGui


class Example(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Example, self).__init__(parent)

        msgBox = QtGui.QMessageBox()
        msgBox.setText('What to do?')
        msgBox.addButton(QtGui.QPushButton('Accept'), QtGui.QMessageBox.YesRole)
        msgBox.addButton(QtGui.QPushButton('Reject'), QtGui.QMessageBox.NoRole)
        msgBox.addButton(QtGui.QPushButton('Cancel'), QtGui.QMessageBox.RejectRole)
        ret = msgBox.exec_()


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

manuel-gutierrez , why do you inherit from QDilaog? You can inherit from QMessageBox. It's much simpler and less code

import sys
from PyQt4.QtGui import QMessageBox, QPushButton, QApplication
from PyQt4.QtCore import Qt

class ErrorWindow(QMessageBox):
    def __init__(self, parent=None):
        QMessageBox.__init__(self, parent)
        self.setWindowTitle("Example")

        self.addButton(QPushButton("Yes"), QMessageBox.YesRole )
        self.addButton(QPushButton("No"), QMessageBox.NoRole)
        self.addButton(QPushButton("Cancel"), QMessageBox.RejectRole)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = ErrorWindow()
    ex.setText("some error")
    ex.show()

    sys.exit(app.exec_())

The standard QMessageBox "impose an interpretation of the response", being accepted, rejected or canceled. Here is a version that allows arbitrary buttons, as much as wanted, and leave the interpreatation up to the user. And it simplifies the sourcecode a bit. The argument "buttons" gives a text list, this makes the buttons. The return value is the text of the clicked botton. So the user can do what he want's with that. Note: This might be against UI-Standards and therefore less robust, but hey. Note2: Since it's 2021, i use PyQt5 and python 3.7 I just posted this in case someone prefer this more generic approach.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

""" A more generic, a bit simplified message box also known as 'popup' """

from PyQt5 import QtWidgets as QW  
    
class Popup(QW.QMessageBox):
    def __init__(
            self, 
            title, 
            text, 
            buttons = ["Ok"]
        ):
        
        super(Popup, self).__init__()
        self.setWindowTitle(title)
        self.setText(text)
        self.buttons = buttons
        for txt in self.buttons:
            b = QW.QPushButton(txt)
            self.addButton(b, QW.QMessageBox.NoRole)
            
    def do(self):
        answer = self.exec_()
        text = self.buttons[answer]
        return text
    
if __name__ == "__main__": # test
    
    class Tester(QW.QWidget):
        def __init__(self):
            super(Tester, self).__init__()
    
            btn = QW.QPushButton("do it")
            btn.clicked.connect(self.klick)
            
            layout = QW.QHBoxLayout(self)
            layout.addWidget(btn)
            
        def klick(self, text):
            r = Popup(
                "choose a letter", 
                "What is your favorite\nLetter\namong a to e ?", 
                buttons = "a,b,c,d,e".split(","))

            print("result = ",r.do())
    
    import sys
    app = QW.QApplication(sys.argv)
    widget = Tester()
    widget.setGeometry(400,400,100,100)
    widget.show()
    sys.exit(app.exec_())
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM