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)
        self.setDefaultButton(QMessageBox.Cancel)
        self.setIcon(QMessageBox.Warning)

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")
    else:
        print ("handle checkbox not activated")

    app.exec_() 

PySide: Rightclick Button Menu

PySide (www.pyside.org) is an awesome Framework that allows you to use Qt with Python. Installation is as straightforward as typing

pip install pyside

I will be creating a menu that opens with a right click. This menu is called “Context Menu” in QT. In this example, the right-click menu on the button removes the button at runtime.

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

class RightClickMenuButton(QPushButton):

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

        self.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.addMenuActions();

    def addMenuActions(self):
        delete = QAction(self)
        delete.setText("remove")
        delete.triggered.connect(self.removeButton)
        self.addAction(delete)

    def removeButton(self):
        self.deleteLater()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    test = QWidget()
    test.resize(250, 150)

    layout = QHBoxLayout()
    layout.addWidget(RightClickMenuButton("Test Btn"))
    test.setLayout(layout)

    test.show()
    app.exec_()