How do I style a Qt Widget not its children with stylesheets?

落花浮王杯 提交于 2021-01-29 11:27:52

问题


I have a:

class Box : public QWidget

and it has

this->setLayout(new QGridLayout(this));

I tried doing:

this->setStyleSheet( "border-radius: 5px; "
                     "border: 1px solid black;"
                     "border: 2px groove gray;"
                     "background-color:blue;");

this->setStyleSheet( "QGridLayout{"
                         "background-color:blue;"
                         "border-radius: 5px; "
                         "border: 1px solid black;"
                         "border: 2px groove gray;"
                     "}"
                   );

this->setObjectName(QString("Box"));
this->setStyleSheet( "QWidget#Box {"
                         "background-color:blue;"
                         "border-radius: 5px; "
                         "border: 1px solid black;"
                         "border: 2px groove gray;"
                     "}"
                   );

but the first affects only the items that are added, the other two do nothing. I want the box itself to have rounded corners and a border (bonus for how to do lines between rows).

How do I get the stylesheet to affect the Box widget, not its children?


回答1:


To be more precise I could have used:

QWidget#idName {
    border: 1px solid grey;
}

or

Box {
    border: 1px solid grey;
}

The latter is easier, in my opinion, as it doesn't require the use of id names.

The main problem with why these weren't working though is because this is considered a custom widget and therefore needs a custom paint event:

 void Box::paintEvent(QPaintEvent *) {
     QStyleOption opt;
     opt.init(this);
     QPainter p(this);
     style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
 }

This was taken from: Qt Stylesheet for custom widget




回答2:


You need to identify the object class and instance, like in regular CSS.

QWidget#BoxName
{
    border-radius: 5px;
    border: 1px solid black;
    border: 2px groove gray;
}

This is the same answer as here: Get variable name of Qt Widget (for use in Stylesheet)?

box->setStyleSheet(QString::fromUtf8("QWidget#box\n"
"{\n"
"    border-radius: 5px;\n"
"    border: 1px solid black;\n"
"    border: 2px groove gray;\n"
"}\n"
""));


来源:https://stackoverflow.com/questions/56661822/background-image-overrides-background-color-of-pushbutton

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!