c++ - QGraphicsPixmapItem的Qt更新像素图

标签 c++ qt

我正在使用 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);

关于c++ - QGraphicsPixmapItem的Qt更新像素图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27085166/

相关文章:

java - Android JNI RegisterNatives : Call once with everything, 或每个函数一次

c++ - OpenGL 是否仅针对 vSync fps 更新屏幕?

c++ - 如何在C++中获取自动变量的类型

java - 如何在 Cmake for Android 中导入共享库

c++ - 我如何知道正在调用 QGraphicsItem::paint() 进行打印?

c++ - Qt(5) : Render same video on 2 different surfaces using QtMultimedia

c++ - C++ 中的 java "package private"是什么?

c++ - SFML loadFromFile 不起作用,奇怪的错误

python - QThread.isFinished 在连接到 finished() 信号的插槽中返回 False

c++ - 最佳实践 : how to interpret/process QDataStream?