I need to develop a dynamic theme changing in PyQt application, I have different components, and depending on the theme I need to change styles. I need to change the theme from some specific component and all components should change their styles. I do not use global styles, I need to write styles for each component separately in its class.
At the moment I came up with such an implementation:
I grab GlobalObject class from this article - https://stackoverflow.com/a/55554690/15709458.
And for each component, I put a listener for the "themeChanged" event. And by dispatching this event, I notify all components which listen to this event that the theme of the application has changed.
Dispatching event example:
def set_dark_theme(app: QApplication):
app.setProperty("theme", "dark")
GlobalObject().dispatchEvent("themeChanged")
Component example:
class CheckBox(QCheckBox):
def __init__(self, parent=None):
super().__init__(parent)
self.update_stylesheet()
GlobalObject().addEventListener("themeChanged", self.update_stylesheet)
def update_stylesheet(self):
theme = QApplication.instance().property("theme")
if theme == "dark":
text_color = __colors__["gray"][200]
else:
text_color = __colors__["gray"][700]
self.setStyleSheet(
f"QCheckBox {{ spacing: 8px; font-size: 14px; font-weight: 500; color: {text_color}; }}"
)
Will such an implementation adversely affect performance due to the fact that all components in the application of which there can be a lot will be subscribed to the event? Is it possible to somehow improve this solution, for example using some built-in methods?