更改"child's parent's style sheet"时如何将孩子的样式表重置为 Qt 默认样式表?
How to reset child's style sheet to Qt default style sheet when the "child's parent's style sheet" is changed?
当我更改对象的样式表时,其子对象的样式表也会更改。 如何将孩子的样式表重置为 Qt 默认样式? 为了测试这一点,我使用以下代码:
在头文件中:
#include "ui_QtGuiApplication.h"
#include <QGraphicsView>
#include <QtWidgets/QPushButton>
class QtGuiApplication : public QMainWindow
{
Q_OBJECT
public:
QtGuiApplication(QWidget *parent = Q_NULLPTR);
private:
Ui::QtGuiApplicationClass ui;
QGraphicsView* qGraph;
QGraphicsScene* scene;
};
在源文件中:
#include "QtGuiApplication.h"
QtGuiApplication::QtGuiApplication(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
// Change centralWidget stylesheet
ui.centralWidget->setStyleSheet(
"background:qlineargradient(x1 : 0, y1 : 0, x2 : 0, y2 : 1,
stop : 0 rgb(216, 0, 0), stop : 0.4 rgb(155, 0, 0),
stop : 0.4 rgb(155, 0, 0), stop : 1.0 rgb(216, 0, 0));");
// creat a QGraphicsView an add it to centralWidget
qGraph = new QGraphicsView(ui.centralWidget);
qGraph->setGeometry(QRect(70, 30, 300, 300));
scene = new QGraphicsScene(qGraph);
scene->setSceneRect(0, 0, 300, 300);
qGraph->setScene(scene);
qGraph->show();
// creat a push button and add it in to centralWidget
QPushButton* btn_Ok = new QPushButton(ui.centralWidget);
btn_Ok->setGeometry(QRect(340, 340, 75, 23));
btn_Ok->setText("Ok");
//below code doesn't work
btn_Ok->setStyleSheet("");
btn_Ok->setStyleSheet(styleSheet());
}
我遇到了类似的问题,孩子或ID选择器为我做了这个技巧。
例如,如果你想btn_Ok
哪个是QPushButton
的样式,你可以给它起一个名字
btn_Ok->setObjectName("xxx");
并使用此名称通过
ui.centralWidget->setStyleSheet("QPushButton#xxx{background: red;}");
这样,唯一要设置样式的按钮是btn_Ok
.
如果要设置所有按钮的样式,这些按钮都是中央小部件的直接后代,您可以使用
ui.centralWidget->setStyleSheet("QWidget#centralWidget > QPushButton{background: red;}");