使用 QIcon 不显示图像

2023-12-24

我正在尝试学习 PyQt。在阅读教程以了解基础知识时,我遇到了 QIcon 的问题。

以下代码应该创建一个简单的窗口,其中包含名为“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!

图像 web.png 包含在当前工作目录中。我使用 Python 3.5.1 和 PyQt 5 以及 Qt 5.6.2。

任何帮助,将不胜感激。


您应该使用绝对路径:

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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 QIcon 不显示图像 的相关文章

随机推荐