2014-11-23 706 views
4

我使用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的第二个版本确实呈现它。我在做什么错误的第一个版本?

+0

为什么FGS你继承'QGraphicsPixmapItem'? 'QGraphicsPixmapItem'具有您需要的所有功能。那些你添加的新字段什么都不做,他们只是尝试已经存在的复制功能(但是在这个实现中它什么都不做)。 – 2014-11-23 08:31:37

+0

如何将你的'Enemy_View'添加到场景中? – thuga 2014-11-24 07:25:19

+0

@thuga:这应该在我猜的构造函数中完成,还是应该在调用构造函数的类中完成? – jdepypere 2014-11-24 09:23:15

回答

4

为什么选择FGS进行分类QGraphicsPixmapItemQGraphicsPixmapItem拥有您所需的全部功能。那些你添加的新字段什么都不做,他们只是尝试已经存在的复制功能(但是在这个实现中它什么都不做)。

这个假设是类似的东西:

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); 
+0

我使用的是一个子类,因为我需要更新模型,但是我留下了该代码。我不太确定如何在不复制大量图像的情况下将图像显示在“QGraphicsScene”上的某个位置。我已经更新了我的答案,以反映我改变了什么。 – jdepypere 2014-11-23 11:04:12