Search code examples
pyqtpyqt5subclasssuperqmessagebox

How to pass a parent to a QMessage subclass


How can I properly pass the parent to the QMessgaeBox subclass? If I don't use the parent, the messagebox doesn't appear at the center of the window!

class onCloseMessage(QMessageBox):
    def __init__(self):
        QMessageBox.__init__(self, QMessageBox.Question, "title", "message",
                             buttons= QMessageBox.Close)

dlg = onCloseMessage()
dlg.exec()

When I pass a parent, and replace self in the __init__ by the parent, it gives errors. If I use super, how can I then __init__ the QMessageBox?

I tried:

class onCloseMessage(QMessageBox):
    def __init__(self, parent):
        super().__init__(parent)
        QMessageBox.__init__(self, QMessageBox.Question, "title", "message",
                             buttons= QMessageBox.Close)

But, it didn't work either.


Solution

  • When using super, you shouldn't call the base-class __init__ as well. Instead, pass all the required arguments to super itself, like this:

    class onCloseMessage(QMessageBox):
        def __init__(self, parent):
            super().__init__(QMessageBox.Question, "title", "message",
                             buttons=QMessageBox.Close, parent=parent)
    

    (NB: you can use Python keyword arguments wherever the Qt signature shows default arguments).