[Python] How can I set app icon with Qt Design Studio project?

Discussão em 'Python' iniciado por Stack, Abril 16, 2025.

  1. Stack

    Stack Membro Participativo

    How can I modify the icon in the upper left corner of my software and the icon displayed in the taskbar? The software was designed by Qt Design Studio, and the project was generated in 2 ways, one is CMake, and the other is qrc.

    I can run the code normally in both ways. CMake uses C++ driver. Qrc is converted by python using pyside6-rcc. Python can also run, but I can't set the icon of my software. Can anyone help me solve it? The QT version used is 6.8, and the Qt Design Studio version is 4.7.0.

    Below is my python code:

    import sys
    import os
    import sys
    import PySide6.QtCore
    import PySide6.QtQuick
    from PySide6.QtQml import QQmlApplicationEngine
    from PySide6.QtWidgets import QApplication, QMessageBox
    from PySide6.QtCore import QObject, Slot
    from PySide6.QtGui import QIcon
    from PySide6.QtGui import QGuiApplication
    import UpgradeTools_rc
    import serial
    import serial.tools.list_ports
    import ctypes

    class QuickWidget(QObject):
    def __init__(self):
    super().__init__()
    self.engine = QQmlApplicationEngine()
    self.engine.rootContext().setContextProperty("backend", self)
    self.engine.addImportPath(u":/qml")
    self.engine.addImportPath(u":/")

    self.engine.load(u":/UpgradeToolsContent/App.qml")
    if not self.engine.rootObjects():
    QMessageBox.critical(None, "Error", "Failed to load QML file.")
    sys.exit(-1)

    root_objects = self.engine.rootObjects()
    if root_objects:
    window = root_objects[0]
    if hasattr(window, "setIcon"):
    window.setIcon(QIcon(":/images/iconImage.ico"))
    else:
    print("this root window not support setIcon")
    else:
    print("not found root window")

    @Slot()
    def onTestButtonClicked(self):
    QMessageBox.information(None, "Clicked", "You clicked the large button!")
    ports = serial.tools.list_ports.comports()
    for port in ports:
    print(port)


    if __name__ == '__main__':
    app = QGuiApplication([])
    iconTemp = QIcon(":/images/iconImage.ico")
    if iconTemp is None:
    print("Icon not found")
    else:
    print("Icon found")
    # app.setWindowIcon(iconTemp)
    quick_widget = QuickWidget()

    # root_objs = quick_widget.engine.rootObjects()
    # if root_objs:
    # window = root_objs[0]
    # if hasattr(window, "setIcon"):
    # window.setIcon(iconTemp)
    # print("Window icon set via root object")
    # else:
    # print("Window object does not support setIcon")
    # else:
    # print("No root window found")
    app.exec()


    No matter if I use app.setWindowIcon(iconTemp) or root_objs, it doesn't work, and iconTemp is prompted to load normally.

    Continue reading...

Compartilhe esta Página