1
votes

I'm trying to learn PyQt. While going over a tutorial to get the basics I've encountered a problem with QIcon.

The following code is supposed to create a simple window with an icon from an image called 'web.png':

import os
import sys

import PyQt5

dirname = os.path.dirname(PyQt5.__file__)
plugin_path = os.path.join(dirname, 'plugins', 'platforms')
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path

from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()


    def initUI(self):

        self.setGeometry(300, 300, 300, 220)
        self.setWindowTitle('Icon')
        self.setWindowIcon(QIcon('web.png'))        

        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

However, the resulting window contains a standard icon and not the wanted image: Wrong Icon!

The image web.png is contained within the current working directory. I use Python 3.5.1 and PyQt 5 with Qt 5.6.2.

Any help would be appreciated.

2
While tinkering about with this, I found that if I try to use an file with an .ico extension, it does work.Ne_Plus_Ultra
However, the ico quality is rather bad, and I would still like to know if there's a reason to make python read the original files and display them as icons in the top-left corner of the program. ThanksNe_Plus_Ultra
Check your imageformats plugins. Seems like you miss them.ilotXXI

2 Answers

1
votes

You should use absolute path instead:

self.setWindowIcon(QIcon('c:/root_to_your_application/web.png'))

or:

import pathlib
current_directory = str(pathlib.Path(__file__).parent.absolute())
path = current_directory + '/web.png'
self.setWindowIcon(QIcon(path))
0
votes

You are trying to change the icon in the wrong place. I've run into this problem, here is the solution.

You gotta change the icon of the "subWindow", just look up the solution above.