我使用QGraphicsPixmapItem在显示器上显示图像。现在,我希望能够即时更新此图像,但我似乎遇到了一些问题。Qt更新QGraphicsPixmapItem的Pixmap
这是头文件:
class Enemy_View : public QGraphicsPixmapItem
{
public:
Enemy_View(QGraphicsScene &myScene);
void defeat();
private:
QGraphicsScene &scene;
QPixmap image;
}
这里是CPP文件
Enemy_View::Enemy_View(QGraphicsScene &myScene):
image{":/images/alive.png"}, scene(myScene)
{
QGraphicsPixmapItem *enemyImage = scene.addPixmap(image.scaledToWidth(20));
enemyImage->setPos(20, 20);
this->defeat();
}
void Enemy_View::defeat(void)
{
image.load(":/images/dead.png");
this->setPixmap(image);
this->update();
}
这样的想法是,我希望能够在调用defeat
方法我的对象,然后编辑一些属性,最终改变图像。但是,我现在正在做的事情不起作用。 alive.png
图像确实显示,但没有更新到dead.png
之一。
更新1
如马立克基R提及我似乎复制了大量的内置功能。我试图清理这个,但现在再也没有任何东西出现在场景中。
.H文件
class Enemy_View : public QGraphicsPixmapItem
{
public:
Enemy_View(QGraphicsScene &myScene);
void defeat();
private:
QGraphicsScene &scene;
/* Extra vars */
};
的.cpp文件
Enemy_View::Enemy_View(QGraphicsScene &myScene):
scene(myScene)
{
/* This part would seem ideal but doesn't work */
this->setPixmap(QPixmap(":/images/alive.png").scaledToWidth(10));
this->setPos(10, 10);
scene.addItem(this);
/* This part does render the images */
auto *thisEl = scene.addPixmap(QPixmap(":/images/Jackskellington.png").scaledToWidth(10));
thisEl->setPos(10, 10);
scene.addItem(this);
this->defeat();
}
void Enemy_View::defeat(void)
{
this->setPixmap(QPixmap(":/images/dead.png"));
}
所以我删除了QPixmap
,但我不知道我是否可以删除QGraphicsScene
。在我的cpp
-文件中,您可以看到我现在有两个版本的构造函数。第一部分,使用this
似乎是一个理想的解决方案,但不会在屏幕上显示图像(即使它的编译没有错误)。与thisEl
的第二个版本确实呈现它。我在做什么错误的第一个版本?
为什么FGS你继承'QGraphicsPixmapItem'? 'QGraphicsPixmapItem'具有您需要的所有功能。那些你添加的新字段什么都不做,他们只是尝试已经存在的复制功能(但是在这个实现中它什么都不做)。 – 2014-11-23 08:31:37
如何将你的'Enemy_View'添加到场景中? – thuga 2014-11-24 07:25:19
@thuga:这应该在我猜的构造函数中完成,还是应该在调用构造函数的类中完成? – jdepypere 2014-11-24 09:23:15