Manage QIcon instances on a application global level

Charles peacech at gmail.com
Thu Jul 6 13:26:32 BST 2023


On Thu, Jul 6, 2023 at 7:17 PM Florian Bruhin <me at the-compiler.org> wrote:

>
> 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
>

I think it would still be possible to get IDE autocompletion by adding
__dir__ in the module

from PyQt5.QtGui import QIcon

ICONS = {'PAUSE': 'media-playback-pause'}

def __getattr__(name):
    return globals().setdefault(name, QIcon.fromTheme(ICONS[name]))

def __dir__():
    return list(ICONS.keys())
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20230706/b90ae5c5/attachment.htm>


More information about the PyQt mailing list