问题
I am attempting to load in images I can't figure out how to load the images using pkgutil.get_data()
which I would prefer to use since I don't want to have fixed paths in my code.
Currently, I have something like this, which works only when running out of the same folder.
...
self.imagePixmap = QtGui.QPixmap("img/myImage.png")
...
The issue then is, if you run the script from other folders the path is messed up and you get this error:
QPixmap::scaled: Pixmap is a null pixmap
I would like to use something like: pkutil.get_data("img", "myImage.png")
to load the images however this provides the data from the image file where QPixmap()
wants other kinds of data.
The only "workaround" I can see is to use part of what they specify here: pkgutil.get_data and do something like this:
self.myPath = os.path.dirname(sys.modules[__name__].__file__)
self.imagePixmap = QtGui.QPixmap(os.path.join(self.myPath,"img/myImage.png"))
This just seems to much of a kludge to me. Is there a better way?
回答1:
Here is what I ended up finding out. I should have rtfm a little closer. Anyway, you can use the loadFromData()
method to get data from a QByteArray
and pass it the format of the data therein.
self.imagePixmap = QtGui.QPixmap()
self.imagePixmap.loadFromData(get_data(__name__, "img/myImage.png"), 'png')
Here is a link to the information from here:
bool QPixmap::loadFromData(const QByteArray &data, const char *format = Q_NULLPTR, Qt::ImageConversionFlags flags = Qt::AutoColor)
This is an overloaded function.
Loads a pixmap from the binary data using the specified format and conversion flags.
来源:https://stackoverflow.com/questions/37278073/loading-qicons-using-pkgutil