如何更改具有特定id的QMenuBar的子css样式表?

2024-10-08 19:25:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个QMenuBar在我的pyqt5应用程序,我正试图costumize。我只想用id='update'更改一个QAction的颜色,其他QAction保持不变,但它没有按我想要的那样工作。以下是我所拥有的:

self.update_btn = self.menu.addAction('Update')
self.update_btn.setVisible(True)
self.update_btn.setObjectName("update")

self.menu.setStyleSheet(
    """
    QMenuBar > QAction#update) {
            background: red;
    }
    """)

我试过其他几种方法,但都不管用


Tags: selfid应用程序颜色updatepyqt5menubtn
1条回答
网友
1楼 · 发布于 2024-10-08 19:25:18

QAction不支持样式表

您可以使用QWidgetAction

试试看:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore    import *
from PyQt5.QtGui     import *

class MenuDemo(QMainWindow):
    def __init__(self,parent=None, *args):
        super().__init__(parent, *args)        

        bar = self.menuBar()

        file = bar.addMenu('File')
        quit = bar.addMenu('Quit')

        open_action = QAction('Open', self)

        save_action = QWidgetAction(self)             # <            
        label  = QLabel(" \n   New \n")
        save_action.setDefaultWidget(label);
        save_action.setText('New')

        file.addAction(open_action)
        file.addAction(save_action)

        #   - setStyleSheet        -
        self.setStyleSheet("""
            QMenu {
                background-color: #ABABAB;         
                border: 1px solid black;
                margin: 2px;
            }
            QMenu::item {
                background-color: transparent; 
                padding: 20px 25px 20px 20px;
            }
            QMenu::item:selected {
                background-color: blue;
            }

            QLabel { 
                background-color: yellow;
                color: red;
                font: 18px;
            } 
            QLabel:hover { 
                background-color: #654321;
            } 

        """)  

        quit.aboutToShow.connect(exit)      

        file.triggered.connect(self.selected)

        self.setWindowTitle("Demo QWidgetAction")
        self.resize(300, 200)
        self.show()

    def selected(self, q):
        print('\n{} <- selected -> {}'.format(q.text(), q))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    menus = MenuDemo()
    sys.exit(app.exec_())

enter image description here

相关问题 更多 >

    热门问题