猿问

使用 Python 的 QPixmaps 性能

.setPos()我目前正在尝试创建一个游戏对象,只要它在 QGraphicsScene 中移动,它就会更改像素图。由于我对这一切都不熟悉,所以我不确定缓存像素图或更改图像的最高效的方法是什么。


我已经查看QPixmapCache并重新实现了该paint()功能,但我仍然不确定最好的方法是什么。这是我目前的想法:


class Object(QGraphicsPixmapItem):


    def __init__(self):

        super(Object, self).__init__()

        self.state = 0

        self.img = {

            "pix1": QPixmap("pix1.png"),

            "pix2": QPixmap("pix2.png"),

            "pix3": QPixmap("pix3.png")}


    def changePix(self):

        if self.state == 0:

            self.setPixmap(self.img["pix1"])

        elif self.state == 1:

            self.setPixmap(self.img["pix2"])

        elif self.state == 2:

            self.setPixmap(self.img["pix3"])

如果我能得到任何建议或反馈,我将不胜感激。


大话西游666
浏览 90回答 1
1回答

白板的微信

以前我从来不需要使用QPixmapCache对象来避免任何性能问题,但这将取决于你到底在做什么。如果您只是在 5 个左右相对较小的静态/生成图像 ( .png < 20kB) 之间切换,我认为没有必要。但是,如果您要执行诸如具有撤消功能的 2k 绘图缓冲区之类的操作,或者需要在某些绘图事件后重新生成的图形,您将需要某种缓存。我也对您的代码进行了一些重构,以避免对任何内容进行硬编码。class Object(QGraphicsPixmapItem):&nbsp; &nbsp; def __init__(self, *args):&nbsp; &nbsp; &nbsp; &nbsp; super(Object, self).__init__()&nbsp; &nbsp; &nbsp; &nbsp; self.img = [a for a in args if os.path.exists(a)]&nbsp; &nbsp; def load_image(img_path, set_now=False):&nbsp; &nbsp; &nbsp; &nbsp; if img_path not in self.img:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.img.append(img_path)&nbsp; &nbsp; &nbsp; &nbsp; if set_now:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;self.change_state(img_path)&nbsp; &nbsp; def change_state(img_path):&nbsp; &nbsp; &nbsp; &nbsp; if img_name in self.img:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.setPixmap(QPixmap(self.img[self.img.index(img_path)]))
随时随地看视频慕课网APP

相关分类

Python
我要回答