2023-04-25

How to visualise a changed pixmap in QIcon without resetting it on the widget?

Now that dark mode has finally come to Windows with Qt 6.5, I noticed that a lot of my icons don't look too well on a dark background. So I'd like to use different icons for light and dark mode. And, to make things difficult, have the icons change (their appearance) when the user switches mode on his OS.

In order to avoid having to setIcon() on all kinds of widgets all over the place, I thought I'd subclass QIcon and have it change its pixmap on the colorSchemeChanged signal.

class ThemeAwareIcon(QIcon):
    def __init__(self, dark_pixmap, light_pixmap, *args):
        super().__init__(*args)
        self.dark_pm = dark_pixmap
        self.light_pm = light_pixmap
        self.app = QApplication.instance()
        self.app.styleHints().colorSchemeChanged.connect(self.set_appropriate_pixmap)
        self.set_appropriate_pixmap()

    def set_appropriate_pixmap(self):
        current_scheme = self.app.styleHints().colorScheme()
        pm = self.dark_pm if current_scheme == Qt.ColorScheme.Dark else self.light_pm
        self.addPixmap(pm, QIcon.Mode.Normal, QIcon.State.On)

This works almost as intended; pixmaps are changed upon the signal. It's just that the changed pixmap isn't displayed on the widget that the icon is set on. The only way I found to make the change visible is to reset the icon on the widget, and that is what I was trying to avoid in the first place.

So, can my icon class be rescued somehow or is what I want just not possible this way?



No comments:

Post a Comment