Go back to Richel Bilderbeek's homepage.

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






(C++) QtExample1


QtQt CreatorLubuntuUbuntu


Qt example 1: moving a sprite over a background in 2D is a Qt example that shows an image moving over a background image, like this screenshot (png).


Technical facts


Application type(s)

Operating system(s) or programming environment(s)


Project type:

C++ standard:


Libraries used:






Qt project file: ./CppQtExample1/CppQtExample1.pro


exists (../../ConsoleApplication.pri) {
!exists (../../ConsoleApplication.pri) {
  QT += core
  QT += gui
  greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
  CONFIG   += console
  CONFIG   -= app_bundle
  TEMPLATE = app
  CONFIG(release, debug|release) {
  QMAKE_CXXFLAGS += -std=c++11 -Wall -Wextra -Weffc++
  unix {
    QMAKE_CXXFLAGS += -Werror

exists(../../Libraries/Boost.pri) {
!exists(../../Libraries/Boost.pri) {
  win32 {

RESOURCES += CppQtExample1.qrc

SOURCES += main.cpp








#include <string>

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#include <boost/shared_ptr.hpp>

#include <QApplication>
#include <QBitmap>
#include <QGraphicsPathItem>
#include <QGraphicsPixmapItem>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QTimer>
#pragma GCC diagnostic pop

struct Background : public QGraphicsPixmapItem
  explicit Background(const std::string& filename)
    QPixmap m(filename.c_str());

struct TransparentSprite : public QGraphicsPixmapItem
  explicit 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);
  void advance(int)
    int new_x = this->x();
    int new_y = this->y();
    if (new_x<0 || new_x>maxx) dx= -dx;
    if (new_y<0 || new_y>maxy) dy= -dy;
  void setRect(const int width, const int height)
    maxx = width  - this->pixmap().width();
    maxy = height - this->pixmap().height();
  int dx;
  int dy;
  int maxx;
  int maxy;

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

  //Original image from http://commons.wikimedia.org/wiki/File:Bubblegum_2.png
  //by Marendo Mueller 10.05.2013, resized to 15%
  Background background(":/images/Bubblegum_2.png");

  //Image from http://commons.wikimedia.org/wiki/File:Bloem.png
  //by DD21
  TransparentSprite sprite(":/images/Bloem.png");



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

  return a.exec();






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

Go back to Richel Bilderbeek's homepage.


Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml