PDA

View Full Version : PNG-based animation



soul_rebel
30th December 2009, 19:48
I'd like to display a busy-animation in my program.

KDE-Themes come with process-working-kde.png and process-working.png, which contain a number of pictures "below" each other (see attachment). What is the easiest way of telling to Qt to make an animation out of this? It must be used in KDE-apps, but I couldn't find the corresponding code…

Thanks for your help!

numbat
31st December 2009, 09:14
Header:


#ifndef ANIM_H
#define ANIM_H
#include <QWidget>
#include <QString>
#include <QTimer>
#include <QLabel>
#include <QList>
#include <QPixmap>

class AnimatedLabel : public QLabel
{
Q_OBJECT

public:
AnimatedLabel(const QString & image, const int imageCount, QWidget* parent = 0);

private slots:
void changeImage();

private:
QList<QPixmap> pixmaps;
int currentPixmap;
QTimer timer;
};

#endif // ANIM_H

and source:


#include "anim.h"
#include <QApplication>
#include <QImage>

AnimatedLabel::AnimatedLabel(const QString &image, const int imageCount, QWidget *parent)
: QLabel(parent), currentPixmap(0)
{
QImage img;
img.load(image);
int subImageHeight = img.height() / imageCount;

for (int i = 0; i < imageCount; i++)
{
QImage subImage = img.copy(0, i * subImageHeight, img.width(), subImageHeight);
pixmaps.push_back(QPixmap::fromImage(subImage));
}

connect(&timer, SIGNAL(timeout()), SLOT(changeImage()));
timer.start(100);
changeImage();
}

void AnimatedLabel::changeImage()
{
if (currentPixmap >= pixmaps.length())
currentPixmap = 0;

setPixmap(pixmaps.at(currentPixmap));

currentPixmap++;
}

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
AnimatedLabel bt("process-working.png", 8);
bt.show();
return a.exec();
}

soul_rebel
31st December 2009, 22:33
Awesome, thanks for the complete code!