Get current application QStyle
-
Suppose I have a custom application style:
class MyStyle: public QProxyStyle { public: MyStyle(QStyle* style); ~MyStyle(); 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 thestatic
method and not the instance (qApp->style()
) one?http://doc.qt.io/qt-5/qapplication.html#style
QStyle *QApplication::style() [static]
-
@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 afterqApp->setStyle(myStyle);
.So probably the only way to solve my case is storing the pointer.
-
@Sixshaman said in Get current application QStyle:
const MyStyle* myStyle = dynamic_cast<const MyStyle*>(style); //Returns nullptr
Does
MyStyle* myStyle = qobject_cast<MyStyle*>(style);
also return null ? -
@Sixshaman
Thats odd as if i modify the
NorwegianWoodStyle example likevoid WidgetGallery::changeStyle(const QString &styleName) //! [5] //! [6] { if (styleName == "NorwegianWood") { QApplication::setStyle(new NorwegianWoodStyle); NorwegianWoodStyle *mine = qobject_cast<NorwegianWoodStyle *>(QApplication::style()); } else { QApplication::setStyle(QStyleFactory::create(styleName)); } changePalette(); }
It does report the expected type and cast do not fail.