Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Qt example 1: moving a sprite over a background in 2D

 

This Qt example shows an image moving over a background image, like this screenshot (png).

 

Operating system: Ubuntu

IDE: Qt Creator 2.0.0

Project type: Qt4 GUI Application

Selected required modules: QtCore, QtGui

Compiler: G++ 4.4.1

Libraries used:

 

 

 

 

 

Qt project file

 

#-------------------------------------------------
#
# Project created by QtCreator 2010-07-19T14:59:00
#
#-------------------------------------------------
QT += core gui
TARGET = QtExample1
TEMPLATE = app
SOURCES += main.cpp

 

 

 

 

 

Source code

 

#include <string>
#include <boost/shared_ptr.hpp>
#include <QtGui/QApplication>
#include <QBitmap>
#include <QGraphicsPathItem>
#include <QGraphicsPixmapItem>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QTimer>

struct Background : public QGraphicsPixmapItem
{
  Background(const std::string& filename)
  {
    QPixmap m(filename.c_str());
    this->setPixmap(m);
  }
};

struct TransparentSprite : public QGraphicsPixmapItem
{
  TransparentSprite(
    const std::string& filename,
    const QColor& transparency_color = QColor(0,255,0)) //Lime green
    : dx(1), dy(1), maxx(320), maxy(200)
  {
    QPixmap pixmap(filename.c_str());
    const QBitmap mask = pixmap.createMaskFromColor(transparency_color);
    pixmap.setMask(mask);
    this->setPixmap(pixmap);
  }
  void advance(int)
  {
    int new_x = this->x();
    int new_y = this->y();
    new_x+=dx;
    new_y+=dy;
    if (new_x<0 || new_x>maxx) dx= -dx;
    if (new_y<0 || new_y>maxy) dy= -dy;
    this->setX(new_x);
    this->setY(new_y);
  }
  void setRect(const int width, const int height)
  {
    maxx = width  - this->pixmap().width();
    maxy = height - this->pixmap().height();
  }
  private:
  int dx;
  int dy;
  int maxx;
  int maxy;
};

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  QGraphicsScene s;
  QGraphicsView v(&s);

  Background background("Background.bmp");
  s.addItem(&background);

  TransparentSprite sprite("Butterfly.bmp");
  sprite.setRect(background.pixmap().width(),background.pixmap().height());

  s.addItem(&sprite);

  v.show();

  boost::shared_ptr<QTimer> timer(new QTimer(&s));
  timer->connect(timer.get(), SIGNAL(timeout()), &s, SLOT(advance()));
  timer->start(10);

  return a.exec();
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict