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

查看:446
本文介绍了如何使用样式表设置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;
}

在我看来,后者更容易,因为它不需要

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天全站免登陆