如何使用样式表为 Qt Widget 而不是其子级设置样式?
我有一个:
class Box : public QWidget
它有
this->setLayout(new QGridLayout(this));
我试过了:
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).
如何让样式表影响 Box 小部件,而不是其子小部件?
How do I get the stylesheet to affect the Box widget, not its children?
推荐答案
更准确地说,我可以使用:
To be more precise I could have used:
QWidget#idName {
border: 1px solid grey;
}
或
Box {
border: 1px solid grey;
}
在我看来,后者更容易,因为它不需要使用 id 名称.
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);
}
这取自:自定义小部件的 Qt 样式表
相关文章