PySide: QMessageBox with QCheckBox

The QMessageBox is very useful for creating standard filesystem dialogs (it even comes with alert sounds) and is limited to display an icon, text and standard buttons. If you want to add something extra like a checkbox for “do not ask me again”, you need to extend the base class.

import sys
from PySide.QtCore import *
from PySide.QtGui import *

class DialogWithCheckBox(QMessageBox):

    def __init__(self, parent= None):
        super(DialogWithCheckBox, self).__init__()

        self.checkbox = QCheckBox()
        #Access the Layout of the MessageBox to add the Checkbox
        layout = self.layout()
        layout.addWidget(self.checkbox, 1,2)

    def exec_(self, *args, **kwargs):
        Override the exec_ method so you can return the value of the checkbox
        return QMessageBox.exec_(self, *args, **kwargs), self.checkbox.isChecked()

class ExampleCheckbox(DialogWithCheckBox):

    def __init__(self, parent=None):
        super(ExampleCheckbox, self).__init__()
        self.setWindowTitle("Dialog with CheckBox")
        self.setText("Isn't this checkbox beautiful?")
        self.checkbox.setText("Do not ask again")
        self.setStandardButtons(QMessageBox.Cancel |QMessageBox.Ok)

if __name__ == '__main__':
    app = QApplication(sys.argv)

    dialog = ExampleCheckbox()
    answer = dialog.exec_()

    # Example how to handle the response
    if answer[1] == True:
        if answer[0] == int(QMessageBox.Ok):
            print ("Ok button pressed")
        print ("handle checkbox has been activated")
        print ("handle checkbox not activated")