Qt Snippet: use stylesheet in a QWidget derived class


If you derive your class directly from QWidget object and want to apply some stylesheet tags for customize interface you'll find that your stylesheet settings will not work.



Just only a simply stylesheet tag for set background color as follow will not have any effect:

myDerivedWidget.setStyleSheet("background-color: red;");

This because basic QWidget object doesn't automatically manage stylesheet tags. Fortunately add this feature is very easy. What you need to do is to overwrite paint event in your derived class and add the following code:

void myDerivedClass::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    QStyleOption StyleOpt;

    StyleOpt.initFrom(this);
    style()->drawPrimitive(QStyle::PE_Widget, &StyleOpt, &painter, this);
}

This will allow the first example stylesheet tag to work as expected.

Comments

Popular posts from this blog

Access GPIO from Linux user space

Android: adb push and read-only file system error

Tree in SQL database: The Nested Set Model