PDA

View Full Version : Custom QGraphicsItem paint function problem



andzero
12th October 2011, 16:06
Hello!

I have a class that inherits QGraphicsItem and QObject:

class Foo: public QObject, public QGraphicsItem
{
Q_OBJECT
...
};
I have set up a QTimer, and connects its timeout signal with QGraphicsScene's advance.

I want to display 2 constantly shifting QPixmap on a Foo instance when it is shown:

void Foo::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->drawPixmap(bodyRect, animate?pic1:pic2); // animate is a boolean variable.
if(animate) animate = false;
else animate = true;
}
e.g., imagine a character walking animation with left foot pixmap and right foot pixmap.

My problem is, the result shown is not as what i have expected.
it looks like pic1 is drawn above pic2 or vice versa.
( pic1 and pic2 is a .png file, supports transparent background. does that have any effect :? )

is it impossible to make this, via paint function re-implementation?
(i'm doing this for learning purposes)

Thanks for your help and attention! :)

stampede
12th October 2011, 18:35
The pixmap will be switched each time the paint method is called, this is probably not what you want.
Connect the timer to a slot, where you will switch the pixmap and update the item:


/*slot*/
void Foo::timeout(){
if( this->_pixmap == pixmap1 ){
this->_pixmap = pixmap2;
} else{
this->_pixmap = pixmap1;
}
update();
}

void Foo::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
painter->drawPixmap(bodyRect, this->_pixmap);
}


Now on each timeout the pixmap will be switched, and item updated, no matter how often its rendered.
Btw. If you are using Qt >= 4.6, take a look at the QGraphicsObject (http://doc.qt.nokia.com/latest/qgraphicsobject.html) class.