如何使用样式表设置Qt小部件而不是其子部件的样式?

2024-10-02 00:28:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个:

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;"
                     "}"
                   );

但是第一个只影响添加的项,另外两个什么也不做。我希望框本身有圆角和边框(行与行之间的线的额外功能)。

如何使样式表影响Box小部件,而不是其子部件?


Tags: box部件bluethiscolorblackbackgroundsolid
2条回答

您需要像在常规CSS中那样标识对象类和实例。

QWidget#BoxName
{
    border-radius: 5px;
    border: 1px solid black;
    border: 2px groove gray;
}

这和这里的答案一样:Get variable name of Qt Widget (for use in Stylesheet)?

box->setStyleSheet(QString::fromUtf8("QWidget#box\n"
"{\n"
"    border-radius: 5px;\n"
"    border: 1px solid black;\n"
"    border: 2px groove gray;\n"
"}\n"
""));

更准确地说,我可以用:

QWidget#idName {
    border: 1px solid grey;
}

或者

Box {
    border: 1px solid grey;
}

在我看来,后者更容易,因为它不需要使用id名称。

但是,为什么这些控件不起作用的主要问题是,这被视为自定义小部件,因此需要自定义绘制事件:

 void Box::paintEvent(QPaintEvent *) {
     QStyleOption opt;
     opt.init(this);
     QPainter p(this);
     style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
 }

这是从:Qt Stylesheet for custom widget

相关问题 更多 >

    热门问题