I can't create an animated sprite with Qt C++
Unsolved
General and Desktop
-
Hi, I'm trying to make a little animated sprite, but don't get it. I read something about QPainter but I don't find any example related with the thing I want to do.
These are the three files of the project:
spriter.h:
#ifndef SPRITER_H #define SPRITER_H #include <QObject> #include <QGraphicsPixmapItem> #include <QImage> class spriter: public QObject, public QGraphicsPixmapItem { Q_OBJECT public: spriter(QGraphicsItem * parent=0); QPixmap sprite; QPixmap sheet; public slots: void move(); public slots: void animar(); }; #endif // SPRITER_H
spriter.cpp:
#include "spriter.h" #include <QTimer> #include <QGraphicsScene> #include <stdlib.h> #include <QDebug> #include <QPainter> spriter::spriter(QGraphicsItem *parent) : QObject(), QGraphicsPixmapItem(parent) { setPos(200,200); sheet = QPixmap(":/dragon.png"); sprite = sheet.copy(0, 0, 64, 64); //setPixmap(sprite); //animar(sheet,sprite); QTimer *temporizador = new QTimer(); connect(temporizador,SIGNAL(timeout()),this,SLOT(move())); connect(temporizador,SIGNAL(timeout()),this,SLOT(animar())); temporizador->start(60); } void spriter::animar() { for(int i=0; i<(sheet.width()/sprite.width()); i++){ setPixmap(QPixmap(sheet.copy(i*sprite.width(), 0, 64, 64))); } for(int i=(sheet.width()/sprite.width())-1; i>0; i--){ setPixmap(QPixmap(sheet.copy(i*sprite.width(), 0, 64, 64))); } } void spriter::move() { setPos(x()+5, y()); if(x() >= 1000){ setPos(200, y()); } }
main.cpp:
#include <QApplication> #include <QGraphicsScene> #include <QGraphicsView> #include "spriter.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); // create a scene QGraphicsScene * scene = new QGraphicsScene(); spriter *cosilla = new spriter(); scene->addItem(cosilla); // add a view to visualize the scene QGraphicsView * view = new QGraphicsView(scene); view->show(); view->setFixedSize(800,600); scene->setSceneRect(0,0, 798,580); return a.exec(); }
I will be very grateful if someone helps me to solve this problem.
-
Hi,
The first thing that comes to mind is that you are blocking the event loop with your for loop in move. You should rather use a QTimer to trigger the move a regular interval.
On a side note, you are leaking your view in main.