Custom style for menu items

Heads up! You've already completed this tutorial.

RaSt | 2021-03-21 21:19:48 UTC | #1

python
import sys

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *


class MainWindow(QMainWindow):

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

        self.setWindowTitle("Custom Menu Item")

        availableGeometry = self.screen().availableGeometry()
        self.resize(640, 480)
        self.move( int((availableGeometry.width() - self.width()) / 2), int((availableGeometry.height() - self.height()) / 2))

        action1 = QAction("QAction Item 1", self)

        action2 = QAction("QAction Item 2", self)
        action2.setCheckable(True)

        action3 = QAction("QAction Item 3", self)


        checkBox = QCheckBox("QWidgetAction", self)
        checkBox.setStyleSheet("background-color: tomato;")

        widgetAction = QWidgetAction(self)
        widgetAction.setDefaultWidget(checkBox);


        menu = self.menuBar().addMenu("Menu")
        menu.addAction(action1)
        menu.addAction(action2)
        menu.addAction(widgetAction)
        menu.addAction(action3)


if __name__ == "__main__":

    app = QApplication(sys.argv)

    window = MainWindow()
    window.show()

    sys.exit(app.exec_())

How to get a menu item with custom background color?

The QWidgetAction item should have the same behavior and style like all others QAction items. Only the background color is different.

How to do that?

Thanks


1:1 Coaching & Tutoring for your Python GUIs project
Martin Fitzpatrick Python GUIs Coaching & Training
60 mins ($195) Book Now

1:1 Python GUIs Coaching & Training

Comprehensive code reviewBugfixes & improvements • Maintainability advice and architecture improvements • Design and usability assessment • Suggestions and tips to expand your knowledgePackaging and distribution help for Windows, Mac & Linux • Find out more.

Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak
Martin Fitzpatrick

Custom style for menu items was written by Martin Fitzpatrick .

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt. Martin founded PythonGUIs to provide easy to follow GUI programming tutorials to the Python community. He has written a number of popular Python books on the subject.