[英]QWidget's background applied to all its QWidget children
我选择使用Qt来管理我正在处理的项目的GUI。
在找到如何在QWidget
底部应用图片之后,我注意到它会对添加到其中的所有组件产生影响。
无论通过setStyleSheet
方法或什至使用QPixmap
应用的样式,这些元素的背景始终是为QWidget
容器定义的图像。
如何避免这种行为?
这是我的代码:
MainMenu::MainMenu(QWidget* Parent, const QPoint& Position, const QSize& Size) : QWidget(Parent) {
QString qwidgetStyle = "QWidget {background-image: url(background.jpg); border: 5px solid rgba(3, 5, 28, 1);}";
QString buttonStyle = "color: rgba(73, 123, 176, 1); font-size:30px; background-color: rgba(73, 123, 176, 1);";
move(Position);
resize(Size);
setStyleSheet(qwidgetStyle);
// Menu title
QLabel *title = new QLabel(this);
title->setText("Menu");
title->setStyleSheet(buttonStyle);
title->setAlignment(Qt::AlignCenter);
// Menu buttons
// Play
buttonPlay = new QPushButton("Play");
(*buttonPlay).setEnabled(true);
(*buttonPlay).setStyleSheet(buttonStyle);
connect(buttonPlay, SIGNAL(clicked()), this, SLOT(handleButton()));
// Option
buttonOptions = new QPushButton("Options", this);
(*buttonOptions).setEnabled(true);
(*buttonOptions).setGeometry(250, 175, 100, 50);
(*buttonOptions).setStyleSheet(buttonStyle);
connect(buttonOptions, SIGNAL(clicked()), this, SLOT(handleButton()));
// Quit
buttonQuit = new QPushButton("Quit", this);
(*buttonQuit).setEnabled(true);
(*buttonQuit).setGeometry(250, 275, 100, 50);
(*buttonQuit).setStyleSheet(buttonStyle);
connect(buttonQuit, SIGNAL(clicked()), this, SLOT(handleButton()));
// Layout
QGridLayout *layout = new QGridLayout;
layout->setMargin(50);
layout->addWidget(title, 0, 0, 1, 5);
layout->addWidget(buttonPlay, 3, 1, 2, 3);
layout->addWidget(buttonOptions, 4, 1, 2, 3);
layout->addWidget(buttonQuit, 5, 1, 2, 3);
setLayout(layout);
show();
}
由于以下几行,因此您遇到的行为是完全正常的:
QString qwidgetStyle = "QWidget {background-image: url(background.jpg); border: 5px solid rgba(3, 5, 28, 1);}";
...
setStyleSheet(qwidgetStyle);
在这里,您只是告诉Qt使用关键字QWidget
将qwidgetstyle
应用于应用程序的每个 QWidget
。 这就是为什么在Qt中,如果要将样式应用于此特定对象,最好为该对象设置一个名称。
在代码中, QLabel
和QPushButton
都继承自QWidget
,因此它们将具有您为QWidget
定义的样式, 除非您为它们命名或为每个样式指定样式 。
如果您要为MainMenu
设置样式表,该样式表直接继承自QWidget
(这是您首先要做的事情),则必须设置一个名称,然后应用样式:
setObjectName("MainMenu");
QString qwidgetStyle = "QWidget#MainMenu {background-image: url(background.jpg); border: 5px solid rgba(3, 5, 28, 1);}";
setStyleSheet(qwidgetStyle); // here, only your MainMenu will have the style "qwidgetstyle"
请注意,例如,您可以为每个QWidget
设置相同的样式表,并且只为MainMenu
添加特定的颜色:
// this is in a CSS, but you can apply it directly from the MainMenu constructor of course
QWidget, QWidget#MainMenu {
background-image: url(background.jpg);
border: 5px solid rgba(3, 5, 28, 1);
} // aplied to all QWidget
QWidget#MainMenu {
color : #9b9b9b; // a nice grey, only applied to MainMenu
}
同样,在使用样式表时要特别说明,否则您的应用程序中到处都会有奇怪的颜色/对齐方式:)。 希望有帮助!
注意:您也可以感谢@PaulRooney,他在评论中给出了很好的链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.