Skip to main content

Command Palette

Search for a command to run...

SetStyleSheet function doesn't work in QWidget

Updated
1 min read
SetStyleSheet function doesn't work in QWidget

1. Preface

we found that the subclasses that inherit from QWidget look fine in Qt Designer when we used the setStyleSheet() function, but when we actually run the application, we find that it doesn't work.

2. Solutions

2.1. solution 1

If you are not going to use signals and slots, you can remove Q_OBJECT from the header file.

2.2. Solution 2

Add the following code.

this->setAttribute(Qt::WA_StyledBackground);

2.3. Solution 3

Override the paintEvent() function.

void MyClass::paintEvent(QPaintEvent *event)
{
    QStyleOption option;
    option.initFrom(this);
    QPainter painter(this);
    style()->drawPrimitive(QStyle::PE_Widget, &option, &painter, this);
}

More from this blog

KangarooLove's blog

11 posts