代码之家  ›  专栏  ›  技术社区  ›  adi

如何设置自定义小部件的背景色和边框宽度?

  •  1
  • adi  · 技术社区  · 6 年前

    我有一个自定义小部件,它的父部件是另一个自定义小部件。我可以使用 QPalette 而且效果很好。但我无法使用这两种方法设置子自定义小部件的边框颜色 stylesheet

    这是我如何设置父自定义小部件的背景色:

    QPalette pal = parentCustomWidget->palette();
    QColor color = {226, 208, 208};
    pal.setColor (QPalette::Background, color);
    parentCustomWidget->setAutoFillBackground (true);
    parentCustomWidget->setPalette (pal);
    parentCustomWidget->show();
    

    childCustomWidget 的颜色:

    方法1:

    QPalette pal = childCustomWidget->palette();
    QColor color = {204, 231, 47};
    pal.setColor (QPalette::Background, color);
    childCustomWidget->setAutoFillBackground (true);
    childCustomWidget->setPalette (pal);
    

    方法2:

    childCustomWidget->setStyleSheet ("*{border-width:" +
        BorderThickness +
        ";border-style:solid;border-color:" +
        hexColorCode + " ;color:white;}");
    

    注: 我已经把那本书注释掉了 paintEvent 虚拟函数。

    How to Change the Background Color of QWidget 并加入了一些变化,如给定,但我无法设置颜色 子自定义小部件 .

    this

    这里橙色是家长的背景颜色,我可以设置。灰色的似乎是子小部件的默认颜色。

    2 回复  |  直到 6 年前
        1
  •  2
  •   scopchanov    6 年前

    解决方案

    为了 方法2 为了工作,即为了使您的自定义小部件尊重样式表 Qt::WA_StyledBackground 属性应设置为 true ,因为:

    例子

    下面是我为您准备的一个最小示例,以演示建议解决方案的可能实现:

    class ParentWidget : public QWidget
    {
        Q_OBJECT
    public:
        explicit ParentWidget(QWidget *parent = nullptr) : QWidget(parent) {}
    };
    
    class ChildWidget : public QWidget
    {
        Q_OBJECT
    public:
        explicit ChildWidget(QWidget *parent = nullptr) : QWidget(parent) {}
    };
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    public:
        explicit MainWindow(QWidget *parent = 0) :
               QMainWindow(parent)
           {
               auto *pWidget = new ParentWidget(this);
               auto *l = new QVBoxLayout(pWidget);
               auto *cWidget = new ChildWidget(pWidget);
               QString BorderThickness("2");
               QString hexColorCode("#FF00FF");
    
               l->addWidget(cWidget);
               l->setContentsMargins(25, 25, 25, 25);
    
               QPalette pal(pWidget->palette());
               QColor color(226, 208, 208);
               pal.setColor (QPalette::Background, color);
               pWidget->setAutoFillBackground (true);
               pWidget->setPalette (pal);
    
               cWidget->setAttribute(Qt::WA_StyledBackground, true);
               cWidget->setStyleSheet("ChildWidget { border: " + BorderThickness + " solid " +
                                      hexColorCode + ";"
                                                     "background-color: rgb(204, 231, 47);"
                                                     "color: white; }");
    
               setCentralWidget(pWidget);
               resize (400, 400);
           }
    };
    

    如前所述,此示例产生以下结果:

    Window showing a colored rectangle with a border on a colored background