Why Can't I change background-color in QWidget using CSS?
-
Hello,
I have 3 classes:
myWid
newWid
widLabIn newWid and widLab I only create QGridLayouts and setLayouts(), nothing more:
newWid::newWid(QWidget *parent):QWidget(parent) { grid = new QGridLayout; setLayout(grid); }
widLab::widLab(QWidget *parent):QWidget(parent) { grid = new QGridLayout; setLayout(grid); }
In class myWid In constructor I have:
myWid::myWid(QWidget *parent): QWidget(parent) { grid = new QGridLayout; nw = new newWid; wl = new widLab; setLayout(grid); grid->addWidget(nw,0,0,1,1); grid->addWidget(wl,0,1,1,1); setStyleSheet("QWidget {background-color:red}"); nw->setStyleSheet("QWidget {background-color:red}"); wl->setStyleSheet("QWidget {background-color:red}"); }
And that 3 classes don't have any other methods. Only constructors.
Next in mainWindow constructor ( which doesn't have other methods ) I have:
mw = new myWid; grid = new QGridLayout; centralWidget()->setLayout(grid); grid->addWidget(mw);
Classes myWid, newWid, widLab inherits QWidget.
And there is no color red. I try use that setStyleSheet in constructors too, but with the same result ( no result ).
Of course when I add to grids in newWid and widLab widgets I see them, but no on the red background.
-
A subclassed QWidget need to either call
setAttribute(Qt::WA_StyledBackground);
or reimplement paintEvent as stated in the doc:
void CustomWidget::paintEvent(QPaintEvent *) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); }
-
I guess that when you assign
grid->addWidget(mw);
your child widgets inherit the QSS from parent and thus loose your custom stylesheet. Setup your UI first, then set QSS. -
@sierdzio
In mainWindow constructor I add ( after grid->addWidget(mw) )QTimer::singleShot(100,this, SLOT(x()));
and the x() slot looks like:
void MainWindow::x() { mw->setStyleSheet("QWidget {background-color:red}"); }
but still doesn't get the red color.
-
A subclassed QWidget need to either call
setAttribute(Qt::WA_StyledBackground);
or reimplement paintEvent as stated in the doc:
void CustomWidget::paintEvent(QPaintEvent *) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); }
-
@Bonnie Yes, now it works! Thank you. But when I tested something like:
in MainWindow
someObjectWhichInheritsQWidget = new someClass; someObjectWhichInheritsQWidget -> setStyleSheet("QWidget {background-color:red}"); grid = new QGridLayout; centralWidget()->setLayout(grid); grid->addWidget(someObjectWhichInheritsQWidget);
and in this someObjectWhichInheritsQWidget didn't had any other grids / widgets ( like in myWid ) everything was ok.
So when I have to add
setAttribute(Qt::WA_StyledBackground);
?