3

I'm trying to create PyQt-application that contains directory with images. Problem is that if I'm trying to load image using it's relative path it's result will depends on current directory from which application will be started.

E.g I've project with the following structure:

qttest/
├── gui.py
└── icon.png

gui.py source:

import sys

from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel

app = QApplication(sys.argv)

main = QMainWindow()
lbl = QLabel()
lbl.setPixmap(QPixmap("icon.png"))
main.setCentralWidget(lbl)
main.show()

sys.exit(app.exec_())

Now if I'll try to launch it from project directory with python3 gui.py it will succesfully load image and display it but if I'll launch it from parent directory with python3 qttest/gui.py it won't work.

Is there are any way to bind image to source file where it's used without hardcoding full image path?

anlar
  • 477
  • 1
  • 11
  • 26
  • 1
    You can [get the path of the py source file](http://stackoverflow.com/a/7162404/1771479). – agold Oct 31 '15 at 17:52
  • You could use the [Qt Resource Sysytem](http://stackoverflow.com/a/11852147/984421). That would allow you to do, e.g. `QPixmap("qrc:/icon.png")`. – ekhumoro Oct 31 '15 at 18:02

1 Answers1

4
import os

path = os.path.dirname(os.path.abspath(__file__))
lbl.setPixmap(QPixmap(os.path.join(path, 'icon.png')))
anlar
  • 477
  • 1
  • 11
  • 26