Ay Men
Ay Men

Reputation: 90

how to set background-image in pyqt6 without qrc system

I have a question about the resource system in PyQt6 and PySide6. firstly why PySide6 still supports the qrc system and PyQt6 does not. secondly how to use an image as a background for a widget in PyQt6, I saw the notion of addSearchPath(), and setSearchPath() but I didn't understand how to use it and it didn't work.

 QtCore.QDir.addSearchPath('icons', 'path_to_icons/')
 icon = QtGui.QIcon('icons:myicon.png')       

Upvotes: 2

Views: 2362

Answers (1)

eyllanesc
eyllanesc

Reputation: 244301

  1. Check How can resources be provided in PyQt6 (which has no pyrcc)? for more information.

  2. Most likely, "path_to_icons" is not correct, instead of using a relative path, you must construct the absolute path.

├── icons
│   └── myicon.png
└── main.py
import os
import sys
from pathlib import Path

from PyQt6.QtCore import QDir
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QApplication, QToolButton

CURRENT_DIRECTORY = Path(__file__).resolve().parent


def main():
    app = QApplication(sys.argv)
    QDir.addSearchPath("icons", os.fspath(CURRENT_DIRECTORY / "icons"))

    icon = QIcon("icons:myicon.png")
    assert not icon.isNull()

    button = QToolButton()
    button.setIcon(icon)
    button.resize(100, 40)
    button.show()

    sys.exit(app.exec())


if __name__ == "__main__":
    main()

Upvotes: 3

Related Questions