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


Over 10,000 developers have bought Create GUI Applications with Python & Qt!
Create GUI Applications with Python & Qt6
Take a look

Downloadable ebook (PDF, ePub) & Complete Source code

Also available from Leanpub and Amazon Paperback

[[ discount.discount_pc ]]% OFF for the next [[ discount.duration ]] [[discount.description ]] with the code [[ discount.coupon_code ]]

Purchasing Power Parity

Developers in [[ country ]] get [[ discount.discount_pc ]]% OFF on all books & courses with code [[ discount.coupon_code ]]
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 https://www.martinfitzpatrick.com/browse/books/ on the subject.