Qt setStyleSheet it not working
-
I have a class called
MyWidget
and I'm trying to load a global style using this code on mymain.cpp
:QFile file(":/style.qss"); file.open(QFile::ReadOnly); QString stylesheet = file.readAll(); application.setStyleSheet(stylesheet);
And it's working, the problem now is that I want to change in that file the background color of my
MyWidget
. I tried to use thesetObjectName('MyWidget')
and do something like:QWidget#MyWidget { background-color: yellow; }
But it doesn't work. What to do?
-
@yugosonegi
If MyWidget is a subclass of QWidget did you see the docs related to this..."QWidget
Supports only the background, background-clip and background-origin properties.
If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget as below:void CustomWidget::paintEvent(QPaintEvent *)
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}The above code is a no-operation if there is no stylesheet set.
Warning: Make sure you define the Q_OBJECT macro for your custom widget."Other than that it should work.
-
With your answer it means that I can't chance the background the way I'm doing? I can't understand your answer right.
-
Hi
mr @kenchan saysIf you MyWidget is a class you made yourself. ( versus one of Qts just named MyClass)
you need to do as he shows in your class
paintEvent for a stylesheet to have any effect.So is MyWidget your own class ?
as in
class MyWidget : QWidget {} -
Yes, it's a subclass of
QWidget
. -
@yugosonegi
Ok, for such a custom widget , you must use the code shown in paintEvent for it to use
stylesheet at all. ( you can have extra code for own drawing but QStyleOption and drawPrimitive
should be used also/first)