/ PYTHON, TECH, PROGRAMMING

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_()