2
votes

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.

2

2 Answers

8
votes

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);
}
0
votes

Try to to trigger paintText after the widgets construction when the event loop finished. I imagine the style should be available then.

You can accomplish this but putting QTimer::singleshot(0, this, SLOT(paintText())); in the widgets constructor.

Make sure paintText() is a SLOT.