Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get stylesheet change event in a QWidget?

Tags:

c++

qt

I'm trying to read a global stylesheet for all widgets and apply it to the QApplication instance.

This styles all widgets correctly, except that I can not query style options, like font and font sizes, in the main window constructor and its children widget's constructors, because at that moment the stylesheet is not applied to it yet.

So I need to :

  • either make global stylesheet available in the mainwindow constructor;
  • catch the event in the widget when style sheet is applied.

Is there a way to achieve one of those?

My code for the main window is below :

int main(int argc, char **argv)
{   
    QWSServer::QWSServer::setBackground(QBrush(QColor(0, 0, 0, 255)));
    QApplication app(argc, argv);

    QFile stylesheet("/usr/bin/app.qss");
    stylesheet.open(QFile::ReadOnly|QFile::Text);
    QTextStream styleSheetStyle(&stylesheet);

    app.setStyleSheet(styleSheetStyle.readAll());

    MainWindow * pWindow = new MainWindow();
    pWindow->setWindowFlags(Qt::FramelessWindowHint);
    pWindow->show();

    return app.exec();  
}

In the widget, where style is needed:

void paintText(QPixmap *target, const QString &text)
{
    QPainter painter(target);
    painter.setPen(QColor(184,188,193,255));
    painter.setFont(property("font").value<QFont>());
    style()->drawItemText(&painter, 
                         target->rect().adjusted(0,0,0,-15), 
                         Qt::AlignHCenter|Qt::AlignBottom, 
                         QPalette(QColor(184,188,193,255)), 
                         true, 
                         text);
    painter.end();
}

If that paint function is called in the widget's constructor, then font is default, if called in the show event, then font is the one specified by the global style sheet.

But that function only needs to be called once, so I don't want to paint it in the show event, even though I can use a flag to make it run only on the first show event.

like image 294
user3528438 Avatar asked Oct 16 '25 14:10

user3528438


1 Answers

Every time a style is changed the QWidget::changeEvent() method is called. Reimplement that method and check for QEvent::StyleChange event type.

void CMyWidget::changeEvent(QEvent* e)
{
    if (e->type() == QEvent::StyleChange)
    {
        // Style has been changed.
    }

    QWidget::changeEvent(e);
}
like image 60
Tomas Avatar answered Oct 18 '25 15:10

Tomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!