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/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01