Rotate QPixmap on a QgraphicsScene around a point
-
Hey Guys!
This is my first post here. :) So my problem is the following:
I have a QGraphicsScene, there is a QPixmap on it. I would like to rotate that pixmap around a center point, would work like a clock actually.I've tried these:
@
QPixmap pointer_pixmap("/home/peter/desktop/myimg2.png");
QTransform transform;QGraphicsPixmapItem *pointer = new QGraphicsPixmapItem(pointer_pixmap); pointer->setOffset(174,190); pointer->setTransformOriginPoint(QPoint(174-pointer_pixmap.width(), 190-pointer_pixmap.height())); transform.translate((174-pointer_pixmap.width())/2,(190-pointer_pixmap.height())/2); transform.rotate(60); transform.translate(-((174-pointer_pixmap.width())/2),-((190-pointer_pixmap.height())/2)); pointer_pixmap = pointer_pixmap.transformed(transform); item->addItem(pointer); pointer->setPixmap(pointer_pixmap);
@
It looks like the translation doesn't have any effect on my pixmap. Why's that?
-
Hi,
I think you're complicating this too much.
@
QPixmap p("/home/peter/desktop/myimg2.png");
auto item = new QGraphicsPixmapItem(p);
item->setTransformOriginPoint(p.rect().center());
item->setRotation(60);scene->addItem(item);
@ -
Thank you Chris!
It seems great!
However if I put this into a loop and try to rotate my image like a clock pointer, somehow it doesn't change only at first time.
@
QPixmap pointer_pixmap("/home/peter/desktop/myimg2.png");
QTransform transform;
int i = 0;QGraphicsPixmapItem* Pixmapitem = new QGraphicsPixmapItem(pointer_pixmap); Pixmapitem->setPos(200,200); item->addItem(Pixmapitem); while(i<180) { Pixmapitem->setTransformOriginPoint(pointer_pixmap.rect().center()); Pixmapitem->setRotation(i); i++; scene->update }
@
How should I achieve that?
-
You do your animation in one go without intervals so all you see is the last frame of it.
You need to update the rotation in intervals and let your code go back to the event loop in between so the painting and other event can be handled.
As a simple example this would rotate your item in 20 degree steps every 1/10th second until it makes a full circle:
@
void animate(QGraphicsPixmapItem* item, int rotation = 0) {
item->setRotation(rotation);
if(rotation < 360)
QTimer::singleShot(100, [=]{animate(item, rotation+20);});
}//then use it:
auto item =...
animate(item);
@Oh, and you don't need to call scene update. When you modify an item the scene will update itself.
-
/home/cmis/AR_demo/combiThread.cpp:7: error: no matching function for call to 'QTimer::singleShot(int, animate(QGraphicsPixmapItem*, int)::__lambda0)'
QTimer::singleShot(100, [=]{animate(item, rotation+20);});I got this error.
^ -
It uses c++11. Add
@
CONFIG += c++11
@
in your .pro file.