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


Create GUI Applications with Python & Qt5 by Martin Fitzpatrick — (PyQt5 Edition) The hands-on guide to making apps with Python — Over 10,000 copies sold!

More info Get the book

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

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.