How do I style a Qt Widget not its children with stylesheets?(如何使用样式表为 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 样式表
这篇关于如何使用样式表为 Qt Widget 而不是其子级设置样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用样式表为 Qt Widget 而不是其子级设置样式?


基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01