Search code examples
c++cssqtqwidget

Can't set style sheet for a derived class from QWidget in qt


I have a derived class from QWidget, let's call it DerivedWidget. And I set the DerivedWidget in MainWindow class as central widget. I want to change the background color for the DerivedWidget, I tried many ways, it just will not work.

DerivedWidget::DerivedWidget(QWidget *parent) : QWidget(parent)
{
    mBtn = new QPushButton(this); //if I have some other widgets on this, like a QPushButton
    mBtn->setStyleSheet("QPushButton { background-color: red; }"); //it works for the QPushButton on this widget

    //tried three ways below to set the widget bgcolor, none of them works
    //first
    this->setStyleSheet("QWidget { background-color: yellow; }"); //it is not working

    //second
    this->setObjectName("#DerivedWidget");
    this->setStyleSheet("QWidget#DerivedWidget { background-color: yellow; }"); //still not working

    //third
    this->setStyleSheet("DerivedWidget { background-color: yellow; }"); //not working either
}

So as you can see, I can change the style sheet for the widgets on the DerivedWidget, but just can not change its background color.
I've also tried to change the DerivedWidget bgcolor in MainWindow class. Of course, I tried more than those three ways I provied, but the results are still the same. None of those methods worked. If I just create a QWidget and set it as central widget in MainWindow class, I can easily set bgcolor for that. But why can't I set bgcolor for the derived class?

Why would this happen and how can I solve this problem?


Solution

  • Ok, I solved this problem by re-implementing the paintEvent(QPaintEvent *) function` like:

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

    More details are here: Qt Doc and a helpful answer.