简体   繁体   中英

PyQt5 customize style of QAction in menuBar

I found very similar questions but no reasonable solution for this issue. I would like to change the style/appearance of QActions which are displayed in menus of a QMainWindow menuBar (eg change the background color). The purpose is to highlight the currently selected action when navigating through the menu again.

Example:

from PyQt5 import QtWidgets, QtCore

class Window(QtWidgets.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)

        action1 = QtWidgets.QAction("action1", self)
        action2 = QtWidgets.QAction("action2", self)
        action1.triggered.connect(self.print_stuff)
        action2.triggered.connect(self.print_stuff)

        mainMenu = self.menuBar()
        mainMenu.setNativeMenuBar(False)
        fileMenu = mainMenu.addMenu('Menu1')
        fileMenu.addAction(action1)
        fileMenu.addAction(action2)

    def print_stuff(self):
        print('whatever')

def run():
    app = QtWidgets.QApplication([])
    application = Window()

    application.show()
    app.exec_()

run()

One could change the StyleSheet of individual menus in the menuBar but I can't change the StyleSheet of QActions since those are not widgets. However, it seems possible to modify the background, since the QActions are eg highlighted when they are hovered with the mouse - just like the menus in the menubar. Any ideas?

use QWidgetAction :

from PyQt5 import QtWidgets, QtCore, QtGui

class Window(QtWidgets.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)

        mainMenu = self.menuBar()
        mainMenu.setNativeMenuBar(False)
        fileMenu = mainMenu.addMenu('Menu1')
        action1 = QtWidgets.QAction("action1", self)
        action2 = QtWidgets.QAction("action2", self)

        action3 = QtWidgets.QWidgetAction(fileMenu)
        l = QtWidgets.QLabel("action3")
        l.setStyleSheet("QLabel { background-color : red; padding: 4 4 4 4px;}")
        action3.setDefaultWidget(l)

        fileMenu.addAction(action1)
        fileMenu.addAction(action2)
        fileMenu.addAction(action3)

        action1.triggered.connect(self.print_stuff)
        action2.triggered.connect(self.print_stuff)
        action3.triggered.connect(self.print_stuff)

    def print_stuff(self):
        print('whatever')

def run():
    app = QtWidgets.QApplication([])
    application = Window()

    application.show()
    app.exec_()

run()

Result:

结果

Try it:

from PyQt5 import QtWidgets, QtCore, QtGui

class Window(QtWidgets.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)

        mainMenu = self.menuBar()
        mainMenu.setNativeMenuBar(False)
        self.fileMenu = mainMenu.addMenu('Menu1')

        action1     = QtWidgets.QWidgetAction(self)             
        self.label1 = QtWidgets.QLabel("action1")
        action1.setDefaultWidget(self.label1);
        action1.setText('action1')

        action2      = QtWidgets.QWidgetAction(self)             
        self.label2  = QtWidgets.QLabel("action2")
        action2.setDefaultWidget(self.label2);
        action2.setText('action2')

        action3      = QtWidgets.QWidgetAction(self)             
        self.label3  = QtWidgets.QLabel("action3")
        action3.setDefaultWidget(self.label3);
        action3.setText('action3')

        self.fileMenu.addAction(action1)
        self.fileMenu.addAction(action2)
        self.fileMenu.addAction(action3)

        self.fileMenu.triggered.connect(self.print_stuff)        # +++

    def print_stuff(self, q):
        print('whatever->', q.text() )
        self.label1.setStyleSheet("""
            QLabel { background-color : #ABABAB; padding: 10px 12px 10px 12px;}
            QLabel:hover { background-color: #654321;}
            """)
        self.label2.setStyleSheet("""
            QLabel { background-color : #ABABAB; padding: 10px 12px 10px 12px;}
            QLabel:hover { background-color: #654321;}
            """)
        self.label3.setStyleSheet("""
            QLabel { background-color : #ABABAB; padding: 10px 12px 10px 12px;}
            QLabel:hover { background-color: #654321;}
            """)

        if q.text() == 'action1':
            self.label1.setStyleSheet("""
                QLabel { background-color : red; padding: 10px 12px 10px 12px;}
                QLabel:hover { background-color: #C10000;}
                """)
        elif q.text() == 'action2':
            self.label2.setStyleSheet("""
                QLabel { background-color : red; padding: 10px 12px 10px 12px;}
                QLabel:hover { background-color: #C10000;}
                """)
        elif q.text() == 'action3':
            self.label3.setStyleSheet("""
                QLabel { background-color : red; padding: 10px 12px 10px 12px;}
                QLabel:hover { background-color: #C10000;}
                """)


qss = """
QMenuBar {
    background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                      stop:0 lightgray, stop:1 darkgray);
}
QMenuBar::item {
    spacing: 3px;           
    padding: 2px 10px;
    background-color: rgb(210,105,30);
    color: rgb(255,255,255);  
    border-radius: 5px;
}
QMenuBar::item:selected {    
    background-color: rgb(244,164,96);
}
QMenuBar::item:pressed {
    background: rgb(128,0,0);
}

QLabel { 
    background-color: #ABABAB;
    color: rgb(255,255,255);
    font: 12px;
    padding: 10px 12px 10px 12px;
} 
QLabel:hover { 
    background-color: #654321;
} 
"""

def run():
    app = QtWidgets.QApplication([])
    app.setStyleSheet(qss)                                   # <---   
    application = Window()
    application.show()
    app.exec_()

run()

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM