4
import sys
import os
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')

        path = os.path.join(os.path.dirname(sys.modules[__name__].__file__), 'icon_1.png')
        self.setWindowIcon(QIcon(path))

        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

I also use a relative path like self.setWindowIcon(QIcon('icon_1.png')) I am sure icon_1.png is at the directory.But the result is always like that:

with no icon in the window and Dock

So where did I make some wrong? I am a newbie in both PyQt and StackOverflow and English... Hope the post is valid.

Thank you in advance.

2
  • Do you get any error message?
    – lrnzcig
    Mar 8, 2016 at 10:05
  • @Irnzcig no, I use eclipse+pydev, the program runs without any error or warning (the console is quite blank)
    – ljy
    Mar 8, 2016 at 10:10

2 Answers 2

15

setWindowIcon is a method for QApplication, not for QWidget and friends

Here is a working version of your test script:

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

class Example(QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(300,300,300,220)
        self.setWindowTitle('Icon')
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    path = os.path.join(os.path.dirname(sys.modules[__name__].__file__), 'icon_1.png')
    app.setWindowIcon(QIcon(path))
    ex = Example()
    sys.exit(app.exec_())
2
  • For the icon display on desktop for example, there is a platform dependant technique explained here.
    – reno-
    Mar 8, 2016 at 10:58
  • Thank you! You are right and the problem is settled. I follow a tutorial but seems that it also has some mistakes, I should also read the document.
    – ljy
    Mar 8, 2016 at 11:25
1

Try using QPixmap('myLogo.png') inside the QIcon() call. Have just tried this on Mac and is working for me =].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.