Go back to Richel Bilderbeek's homepage.

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






(C++) QtExample3


QtQt CreatorLubuntuUbuntu


Qt example 3: a changing background in 2D is a Qt example that shows a changing background in 2D, 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: ./CppQtExample3/CppQtExample3.pro


exists(../../DesktopApplication.pri) {
!exists(../../DesktopApplication.pri) {
  QT += core gui
  greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
  TEMPLATE = app

  CONFIG(debug, debug|release) {
    message(Debug mode)

  CONFIG(release, debug|release) {
    message(Release mode)

  QMAKE_CXXFLAGS += -std=c++11 -Wall -Wextra

  unix {
    QMAKE_CXXFLAGS += -Werror

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

SOURCES += main.cpp








#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Weffc++"
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#include <boost/shared_ptr.hpp>
#include <QApplication>
#include <QDesktopWidget>
#include <QGraphicsPixmapItem>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QTimer>
#pragma GCC diagnostic pop

struct ChangingBackground : public QGraphicsPixmapItem
  ChangingBackground(const int width, const int height)
    : z(0)
    QPixmap m(width,height);
  void advance(int)
    QImage i = this->pixmap().toImage();
    const int width = i.width();
    const int height = i.height();
    for (int y=0;y!=height;++y)
      for (int x=0;x!=width;++x)
          QPoint(x,y), //Position
          QColor( //Color
  int z;

int main(int argc, char *argv[])
  QApplication a(argc, argv);

  //Create a scene to add the background sprite to
  boost::shared_ptr<QGraphicsScene> scene(new QGraphicsScene);

  //Create a background sprite to add to the scene
  boost::shared_ptr<ChangingBackground> background(
    new ChangingBackground(256,256));

  //Create a view to display the scene
  boost::shared_ptr<QGraphicsView> view(new QGraphicsView);

  //Create a timer to call 'advance' on the scene and its sprite
  boost::shared_ptr<QTimer> timer(new QTimer(scene.get()));
  timer->connect(timer.get(), SIGNAL(timeout()), scene.get(), SLOT(advance()));

  //Display the view

  //Move the view to the screen center
  const QRect screen = QApplication::desktop()->screenGeometry();
  view->move( screen.center() - view->rect().center() );

  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