如何使用样式表为 Qt Widget 而不是其子级设置样式? [英] How do I style a Qt Widget not its children with stylesheets?

查看:37
本文介绍了如何使用样式表为 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 而不是其子级设置样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆