Manage QIcon instances on a application global level

Florian Bruhin me at the-compiler.org
Thu Jul 6 13:17:02 BST 2023


Hey,

> You can simply create qapplication instance in your application
> __init__.py, or make icon.py lazy, e.g.
> 
> from PyQt5.QtGui import QIcon
> 
> ICONS = {'PAUSE': 'media-playback-pause'}
> 
> def __getattr__(name):
>     return globals().setdefault(name, QIcon.fromTheme(ICONS[name]))

Personally, I'd probably do something like this, but a bit more
explicit. I also like using enums for things like this, because then you
get IDE autocompletion and such:

    import enum
    from PyQt5.QtGui import QIcon

    class Icon(enum.Enum):

        PAUSE = "media-playback-pause"
        ...

    def get(icon: Icon) -> QIcon:
        return QIcon.fromTheme(icon.value)

And then when you want an icon:

    icon.get(icon.Icon.PAUSE)

Florian
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20230706/e1ad3f6c/attachment.sig>


More information about the PyQt mailing list