Search code examples
c++qtqwidget

Changing background color of QWidget inside another Widget


I have a widget that I am placing inside another widget that I wish to make black. I am doing with the following code.

Here is my inner widget constructor:

innerwidget.cpp

#include "innerwidget.h"
#include <QStyle>

InnerWidget::InnerWidget(QWidget *parent) : QWidget(parent)
{
    setMinimumSize(1280,70);
    this->setStyleSheet("background-color: black");
    style()->unpolish(this);
    style()->polish(this);
    update();
}

And here is my outer widget constructor:

outerwidget.cpp

#include "outerwidget.h"
#include <QGridLayout>

OuterWidget::OuterWidget(QWidget *parent)
    : QWidget(parent)
{
    setMinimumSize(1280, 800);
    setMaximumSize(1280,800);
    innerWidget = new InnerWidget(this);
    QGridLayout *layout = new QGridLayout;
    layout->addWidget(innerWidget, 0, 0, 0, 4, Qt::AlignTop);
    this->setLayout(layout);
    this->setWindowState(Qt::WindowFullScreen);
}

OuterWidget::~OuterWidget()
{

}

My main is the very simple default code:

main.cpp

#include "outerwidget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    OuterWidget w;
    w.show();

    return a.exec();
}

My header files are nothing special:

innerwidget.h

#ifndef INNERWIDGET_H
#define INNERWIDGET_H

#include <QWidget>

class InnerWidget : public QWidget
{
    Q_OBJECT
public:
    explicit InnerWidget(QWidget *parent = nullptr);

signals:

public slots:
};

#endif // INNERWIDGET_H

outerwidget.h

#ifndef OUTERWIDGET_H
#define OUTERWIDGET_H

#include <QWidget>
#include <innerwidget.h>

class OuterWidget : public QWidget
{
    Q_OBJECT

public:
    OuterWidget(QWidget *parent = 0);
    ~OuterWidget();

private:
    InnerWidget *innerWidget;
};

#endif // OUTERWIDGET_H

I've noticed that if I add controls to the inner panel, such as a QLabel, the background color of those controls will be changed, but I'd like to change the background color of the whole widget (which, in my example, would be a bar across the top of the screen).

Where am I going wrong? Does it have something to do with the Grid Layout I am using to add my inner widget to outer widget?


Solution

  • After much experiementing I found an answer to this problem.

    It seems overriding the paitnEvent() method is required to use style sheets with custom widgets, as described here

    Note: If you subclass a custom widget from QWidget, then in order to use the StyleSheets you need to provide a paintEvent to the custom widget :

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