Qt Update Pixmap of QGraphicsPixmapItem
Qt Update Pixmap of QGraphicsPixmapItem
我正在使用QGraphicsPixmapItem在显示器上显示图像。现在,我希望能够即时更新此图像,但我似乎遇到了一些问题。
这是头文件:
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
正如Marek 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
具有您需要的所有功能。您添加的那些新字段什么都不做,它们只是尝试复制已经存在的功能(但通过此实现,它什么也不做)。
这假设是这样的:
QPixmp image(":/images/alive.png");
QGraphicsPixmapItem *enemyItem = scene.addPixmap(image.scaledToWidth(20));
enemyItem->setPos(20, 20);
// and after something dies
QPixmap dieImage(":/images/dead.png");
enemyItem->setPixmap(dieImage);