Please nominate your Qt Champions for 2021!

Get current application QStyle

  • Suppose I have a custom application style:

    class MyStyle: public QProxyStyle
        MyStyle(QStyle* style);
        void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const Q_DECL_OVERRIDE;

    Now I set the style for the whole application:

    qApp->setStyle(new MyStyle());

    I need a way to get it back. Unfortunately, QApplication::style() doesn't return the style I created, meaning the returned copy is not an instance of MyStyle:

    const QStyle* style = qApp->style();
    const MyStyle* myStyle = dynamic_cast<const MyStyle*>(style); //Returns nullptr

    I've tried using QStyle::proxy, but it didn't work either. It seems the only way to get current application QStyle is storing a pointer somewhere. But probably I'm missing something. Is there a way to do it without dirty hacks?

  • @Sixshaman
    Not sure, but do you have to use the static method and not the instance (qApp->style()) one?
    QStyle *QApplication::style() [static]

  • @JonB
    The method is static anyway, but I use the qApp->style() form.

  • @Sixshaman
    OK, I'm not a C++-er. Can't do that in "nice" languages :) OOI, what does qDebug() << QApplication::style()->metaObject()->className(); give you?

  • @JonB
    Oh. It outputs QStyleSheetStyle.

    You see, we use both stylesheets and QStyle's. Stylesheets are nessessary if you need a bigger palette for elements, but it's impossible to change the entire appearance of complex controls using stylesheets.

    It seems that QStyleSheetStyle always overrides QProxyStyle and it doesn't matter if I call qApp->setStyleSheet(styleSheet); before or after qApp->setStyle(myStyle);.

    So probably the only way to solve my case is storing the pointer.

  • Lifetime Qt Champion

    @Sixshaman said in Get current application QStyle:

    const MyStyle* myStyle = dynamic_cast<const MyStyle*>(style); //Returns nullptr


    MyStyle* myStyle = qobject_cast<MyStyle*>(style);
    also return null ?

  • @mrjj

  • Lifetime Qt Champion

    Thats odd as if i modify the
    NorwegianWoodStyle example like

    void WidgetGallery::changeStyle(const QString &styleName)
    //! [5] //! [6]
        if (styleName == "NorwegianWood") {
            QApplication::setStyle(new NorwegianWoodStyle);
            NorwegianWoodStyle *mine = qobject_cast<NorwegianWoodStyle *>(QApplication::style());        
        } else {

    It does report the expected type and cast do not fail.

Log in to reply