Quick question about loading images
-
I'm trying to load an image using the path:
image = 'images/world.png'
However it doesn't work, it only works if i use an absolute path. Everything in the right place, folder and image but it doesn't work with a relative path.
Ok thanks world!!
-
@pablomichea said in Quick question about loading images:
However it doesn't work, it only works if i use an absolute path. Everything in the right place, folder and image but it doesn't work with a relative path.
Precisely! What do you expect your path to be relative to?!
It's relative to the current working directory of your application. Which is... what? You don't know, and depends how the user invokes your application.
You simply should never rely on the current working directory being anything specific and hence you should never use relative paths in your code (unless you know what you are doing!). Use absolute paths to access files. And utilise Qt's QStandardPaths Class to build absolute paths from suitable standard locations at run-time. You can alternatively use Qt's resource paths to access resources stored inside the executable if you wish to put them there.
-
Thanks you JonB, i understand what you mean, i just wanted to know why it won't work. I'm currently studying the book "Beginning PyQt" (2nd edition) and well.. they used a relative path but it doesn't work for me, it just work with an absolute path.
Thanks!!
-
Hi,
Where is your script ?
Where is that folder with regards to your script ?
Where are you calling your script from ? -
@SGaist Hi, you can even download their folder from github and it doesn't work, here it is: https://github.com/Apress/Beginning-PyQt--second-edition
chapter 2: labels.py
-
@pablomichea said in Quick question about loading images:
they used a relative path but it doesn't work for me, it just work with an absolute path.
They were naughty! If you ensure your current directory is where that
labels.py
is located thenimages/...
will be found relative to it. That must be what they intend. -
@pablomichea Do you know what a relative path is?
As @JonB told you a relative path is relative to the current working directory of your running application.
If the working directory is not the one where images subfolder is your path will not be found.
Either put your images into ressource files or construct absolute path at runtime.
You can also get the directory where you executable is: https://doc.qt.io/archives/qt-4.8/qcoreapplication.html#applicationDirPath, then add "images/world.png" to it... -
You can also take a look at our QML examples.
They use pathlib to determine the path to the current source file:Path(__file__).resolve().parent / 'view.qml')