How to apply stylesheets to menu of QPushButton

Viewed 297

How do I apply css style sheet to a menu of QPushButton. I have made numerous attempts but Nothing seems to work. I found a similar discussion here

Here is my attempt:

from PyQt5 import QtWidgets
import sys


_style = """
    
    #ButtonMenu > QPushButton{
        
        background-color: blue;
        
    }
    
  /*  #ButtonMenu > QPushButton::menu{
        
        background-color: blue;
        
    }*/
    
    QMenu{
    
        background-color: red;
        
    }
    
   /* #ButtonMenu > QMenu{    
        background-color: red;
    }
    */
"""


class ButtonMenu(QtWidgets.QWidget):

    def __init__(self, *args, **kwargs):
        super(ButtonMenu, self).__init__(*args, **kwargs)

        self.setObjectName("ButtonMenu")

        layout = QtWidgets.QVBoxLayout()

        button = QtWidgets.QPushButton()
        menu = QtWidgets.QMenu()

        menu.addAction("hello")
        menu.addAction("world")

        button.setMenu(menu)

        layout.addWidget(button)
        self.setLayout(layout)


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    win = ButtonMenu()
    win.setStyleSheet(_style)

    win.show()

    sys.exit(app.exec_())

1 Answers

Try it:

import sys
from PyQt5 import QtWidgets, QtGui


class ButtonMenu(QtWidgets.QWidget):
    def __init__(self, *args, **kwargs):
        super(ButtonMenu, self).__init__(*args, **kwargs)
        self.setObjectName("ButtonMenu")

        button = QtWidgets.QPushButton()
        menu = QtWidgets.QMenu()
        menu.addAction("hello")
        menu.addAction("world")
        button.setMenu(menu)

        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(button)


_style = """
    #ButtonMenu {
        background-color: blue;
    }
    QPushButton {
        background-color: #f0f;
    }
    
    QMenu {
        background: #ff0;
        border: 2px solid red;
        border-radius: 2px;
    }
    QMenu::item {
        color: green;
        font-size: 22px;
    }
    QMenu::item:selected {
        background: #0ff;
        color: red;
    }
"""


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    
    app.setStyleSheet(_style)                              # +
    
    win = ButtonMenu()
#    win.setStyleSheet(_style)
    win.show()
    sys.exit(app.exec_())

enter image description here

Related