本文介绍了使用 pkgutil 加载 QIcons的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试加载图像我不知道如何使用 pkgutil.get_data() 加载图像,我更喜欢使用它,因为我不想有固定路径在我的代码中.

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: 像素图是一个空像素图

我想使用类似:pkutil.get_data("img", "myImage.png") 来加载图像,但是这提供了图像文件中的数据,其中 QPixmap() 想要其他类型的数据.

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.

我能看到的唯一解决方法"是使用他们在此处指定的部分内容:pkgutil.get_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"))

这对我来说似乎很kludge.有没有更好的办法?

This just seems to much of a kludge to me. Is there a better way?

推荐答案

这是我最终发现的.我应该让 rtfm 更接近一点.无论如何,您可以使用 loadFromData() 方法从 QByteArray 获取数据并将其中数据的格式传递给它.

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')

这是来自此处的信息链接:

bool QPixmap::loadFromData(const QByteArray &data, const char *format = Q_NULLPTR, Qt::ImageConversionFlags flags = Qt::AutoColor)

这是一个重载函数.

使用指定的格式和转换标志从二进制数据加载像素图.

Loads a pixmap from the binary data using the specified format and conversion flags.

这篇关于使用 pkgutil 加载 QIcons的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 06:04