How To Set Your Windows Taskbar Application Icon with pyQT/pySide

If you are writing a Windows-only or cross-platform application using pyQT or pySide (version 6, as of this time of writing), you may discover that you need to change your application's icon, as it appears in the taskbar. By default, it is a boring, generic "window" icon, and, naturally, you will want to change it!

But the instructions for doing so aren't very clear. This StackOverflow post gets us started, but the given (and accepted) solutions seem to advise the unnecessary extra step of saving a copy of the icon as a Python variable itself!

There is a simpler way, and it involves just a few lines of code. Inside the __init__() function of your QT window's code, add the following:

from pathlib import Path
from PySide6.QtGui import QPixmap, QIcon #substitute the equivalent pyQT line if you're using pyQT

# load window icon
path_to_icon = 'res/icon.png' #the path to your icon file, relative to the project root
pixmap = QPixmap()
pixmap.loadFromData( Path( path_to_icon ).read_bytes() )
appIcon = QIcon(pixmap)

And voilà! You now have a pretty icon in the taskbar for your program.

sui generis.

Lyjia's Blog

See posts by category: