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");
运行结果:
求解:为什么会出现这种情况?