QT中对MenuBar使用setStyleSheet设置菜单栏背景颜色导致整个菜单消失

对菜单栏使用setStyleSheet会导致菜单栏整条消失

testwindow.cpp

#include "testwindow.h"
#include <QPushButton>

#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QApplication>

TestWindow::TestWindow(QWidget *parent)
    : QMainWindow(parent)
{
    this->resize(800,600);

    //创建菜单栏
    QMenuBar * pmb = new QMenuBar(this);
    pmb->setGeometry(0,0,this->width(),30);
    this -> setStyleSheet("QMenu::item:selected{background-color:#ff0000;}\
                          QMenuBar{background-color:#ee00ff;}");

    //创建菜单
    QMenu * turn = new QMenu("开关灯",this);
    pmb->addMenu(turn);

    QAction * light = new QAction("Light",this);
    QAction * dark = new QAction("Dark",this);

    turn->addAction(light);
    turn->addAction(dark);

    connect(light,&QAction::triggered,this,&TestWindow::setwindowstyle1);
    connect(dark,&QAction::triggered,this,&TestWindow::setwindowstyle2);
}

TestWindow::~TestWindow()
{
}

void TestWindow::setwindowstyle1()
{
    this->setStyleSheet("background-color:rgb(240,240,240)");
}

void TestWindow::setwindowstyle2()
{
    this->setStyleSheet("background-color:rgb(100,100,100)");
}

main.cpp

#include "testwindow.h"
#include <QApplication>
#include <QStyleFactory>
#include <QApplication>
#include <QDebug>
#include <QObject>


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    TestWindow w;
    w.setWindowTitle("测试窗口");
    w.show();
    return a.exec();
}

以下为该代码的运行结果:
图片说明

当注释掉这行代码后:

 this -> setStyleSheet("QMenu::item:selected{background-color:#ff0000;}\
                          QMenuBar{background-color:#ee00ff;}");

运行结果:
图片说明

显示正常。

接下来对菜单使用setStyleSheet():

 turn->setStyleSheet("background-color:yellow");

运行结果:
图片说明

求解:为什么会出现这种情况?

https://blog.csdn.net/u010002704/article/details/39060131