Как изменить цвет нажатой кнопки в QMenuBar

Как изменить цвет нажатой кнопки в menubar PyQt5?


Ответы (1 шт):

Автор решения: S. Nick

Попробуйте установить Style Sheet:

QMenuBar::item:pressed {
    background: rgb(128, 0, 0);
}

main.py

import sys
from PyQt5.Qt import *


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        self.layout = QVBoxLayout(central_widget) 
        
        mainMenu = self.menuBar()
        testMenu = mainMenu.addMenu('mainMenu') 

        test1_action = QAction('Test 1', self)
        testMenu.addAction(test1_action)
        
        test2_action = QAction('Test 2', self)
        test2_action.triggered.connect(self.displayImage)
        testMenu.addAction(test2_action)

        test_action = QAction('Exit', self)
        test_action.setShortcut('Ctrl+E')
        test_action.triggered.connect(self.close)
        testMenu.addAction(test_action)         
        
    def displayImage(self):
        pixmap = QPixmap("D:/_Qt/img/pyqt.jpg") 
        label = QLabel(self)
        self.layout.addWidget(label)
        label.setPixmap(pixmap.scaled(400, 400, Qt.KeepAspectRatio))        


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);
}

QMenu {
    background-color: #ABABAB;   
    border: 1px solid black;
    margin: 2px;
}
QMenu::item {
    background-color: transparent;
}
QMenu::item:selected { 
    background-color: #654321;
    color: rgb(255,255,255);
}
"""
         
if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    app.setStyleSheet(qss)       
    
    w = MainWindow()
    w.setWindowTitle('Style Sheet: QMenuBar, QMenu')
    w.setWindowIcon(QIcon('D:/_Qt/img/py-qt.png')) 
    w.resize(420, 440)
    w.show()
    sys.exit(app.exec_())

введите сюда описание изображения

→ Ссылка