How to make game using Qt - Lesson 1. Control of object

GameDev, getasynckeystate, QGraphicsItem, QGraphicsScene, Qt, WinAPI, написать игру

With this lesson begins a series of articles on how to write a play on Qt. In the previous article it was told about the system of positioning of graphical elements QGraphicsItem in the graphic scene QGraphicsScene . It was painted a triangle and placed in the center of the graphic scenes, the dimensions of which were 500 by 500 pixels. And now it is time to revive this triangle, but rather to begin to control it.

We make technical lesson assignment:

  • A graphic scene is located in the Window with dimensions of 500 by 500 pixels (this is already done in the previous lesson);
  • In the center of the graphic scene is a red triangle (which also has been done in the previous lesson);
  • The triangle should move when you press the Up arrow, Down, Left, Right;
  • Triangle should not go beyond a graphic scene, that is, should be limited by the size of the graphic scene.

Note. This project uses of WinAPI, so the project is suitable for use in the Windows operating system, but only algorithm that is used in this lesson is applicable to Linux and MacOS. So if you want to write a game for these operating systems, you will need to use the library of the OS for asynchronous processing keystrokes.

Project Structure

  • - profile project, created by default, and in this project does not require korrektirovaki;
  • main.cpp - the file from which you start the application, the file is called a widget, which will be located in the graphic scene with a triangle, which we will manage;
  • widget.h - header file, called a widget with a graphic scene;
  • widget.cpp - File widget source code;
  • triangle.h - header file class Triangle, which is inherited from QGraphicsItem;
  • triangle.cpp - class source code file Triangle.


The interface design simply throws QGraphicsView in the widget. Nothing more is required.


This file is only to declare a graphical scene, the triangle object, which will manage, as well as a timer counts on which to test the state of the keyboard keys, we'll manage the triangle on the graphic scene.

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QGraphicsScene>
#include <QShortcut>
#include <QTimer>

#include <triangle.h>

namespace Ui {
class Widget;

class Widget : public QWidget

    explicit Widget(QWidget *parent = 0);

    Ui::Widget      *ui;
    QGraphicsScene  *scene;     /// We declare a graphic scene
    Triangle        *triangle;  /// and triangle
    QTimer          *timer;     /* We declare the game a timer, 
                                 * by which will be changing the position of an object 
                                 * on the stage when exposed to the keyboard keys
                                 * */

#endif // WIDGET_H


This file initializes the graphic scene, and its size, in a graphical scene rendered the field border, where a triangle will move. But the key point is to initialize a timer signal processing of which will be made changes in the state of graphic scenes, and will change the coordinates of the triangle position, tracking the state of the keyboard keys.

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    ui(new Ui::Widget)
    this->resize(600,600);          /// Defining the size of the widget, ie the window
    this->setFixedSize(600,600);    /// Fix a widget sizes

    scene = new QGraphicsScene();   /// Initialize the graphics scene
    triangle = new Triangle();      /// Initialize triangle

    ui->graphicsView->setScene(scene);  /// Set the graphic scene in qgraphicsView
    ui->graphicsView->setRenderHint(QPainter::Antialiasing);    /// Install anti-aliasing
    ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); /// Disable scroll vertically
    ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); /// Disable scroll horizontally

    scene->setSceneRect(-250,-250,500,500); /// Set the graphic scenes

    scene->addLine(-250,0,250,0,QPen(Qt::black));   /// Adding a horizontal line through the center
    scene->addLine(0,-250,0,250,QPen(Qt::black));   /// Add a vertical line through the center 

    /* In addition, we draw a limited area in the graphic scene */
    scene->addLine(-250,-250, 250,-250, QPen(Qt::black));
    scene->addLine(-250, 250, 250, 250, QPen(Qt::black));
    scene->addLine(-250,-250,-250, 250, QPen(Qt::black));
    scene->addLine( 250,-250, 250, 250, QPen(Qt::black));

    scene->addItem(triangle);   /// Adding to the scene triangle
    triangle->setPos(0,0);      /// Set the triangle in the center of the stage

    /* Initialize the timer and call processing slot timer signal from Triangle 20 times per second. 
     * By controlling the speed counts, respectively, 
     * control the speed of change in the state of graphic scenes
     * */
    timer = new QTimer();
    connect(timer, &QTimer::timeout, triangle, &Triangle::slotGameTimer);
    timer->start(1000 / 50);

    delete ui;


And now we proceed to the program code that is responsible for the graphic object, which we will operate. The class inherits from QObject to work with signals and slots , as well as QGraphicsItem .

#ifndef TRIANGLE_H
#define TRIANGLE_H

#include <QObject>
#include <QGraphicsItem>
#include <QPainter>
#include <QGraphicsScene>

/* Connect the library is responsible for the use WinAPI. 
 * This library is required to check the status of asynchronous keys
 * */
#include <windows.h>

class Triangle : public QObject, public QGraphicsItem
    explicit Triangle(QObject *parent = 0);


public slots:
    void slotGameTimer();

    QRectF boundingRect() const;
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);

    qreal angle;    // The angle of rotation of the graphic object


#endif // TRIANGLE_H


Drawing a triangle is taken from the previous lesson on the positioning of graphical elements in the graphic scene, but redrawing in a slot that will handle the signal from the timer, and the initialization of the primary rotation of the object has a new piece of code.

Rotate an object is given in degrees of variable angle and set setRotation() function, which was inherited from QGraphicsItem . Also for monitoring the status of the keyboard keys used by the function of the WinAPI , namely GetAsyncKeyState() , which is the code button determines the state of the button itself. Each signal from QTimer class object is checked keystrokes and changing the position of the triangle depending on their condition.

#include "triangle.h"

Triangle::Triangle(QObject *parent) :
    QObject(parent), QGraphicsItem()
    angle = 0;     



QRectF Triangle::boundingRect() const
    return QRectF(-25,-40,50,80);  

void Triangle::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
        QPolygon polygon;   //
        polygon << QPoint(0,-40) << QPoint(25,40) << QPoint(-25,40);

void Triangle::slotGameTimer()
    /* Alternately checks for key presses
     * using the asynchronous reception state of the keys
     * is provided WinAPI
     * */
        angle -= 10;        // Set turn 10 degrees to the left
        setRotation(angle); // Rotate object
        angle += 10;        // Set turn 10 degrees to the right
        setRotation(angle); // Rotate object
        setPos(mapToParent(0, -5));     /* Move the object 5 pixels forward to retranslate them
                                         * in the coordinate system of the graphic scene
                                         * */
        setPos(mapToParent(0, 5));      /* Move the object 5 pixels backward to retranslate them
                                         * in the coordinate system of the graphic scene
                                         * */

    /* Check output of bounds. If the subject is beyond the set boundaries, then return it back
     * */
    if(this->x() - 10 < -250){
        this->setX(-240);       // left
    if(this->x() + 10 > 250){
        this->setX(240);        // right

    if(this->y() - 10 < -250){
        this->setY(-240);       // top
    if(this->y() + 10 > 250){
        this->setY(240);        // bottom


To ensure that the project is compiled with MSVC build a set, add the following lines to pro project file:

    LIBS += -luser32


As a result of this work we have made first steps to ensure that the write off. Namely learned to control the object, that is, our hero-triangle, with whom we also work in future lessons on writing our first game.

A full list of articles in this series:


We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate

Добрый день,
Подскажите пожалуйста, чем может быть вызвана ошибка
"C:\Android\Qt\Mark\untitled4\triangle.cpp:5: ошибка: undefined reference to `vtable for Triangle'" ?
В конструкторе указывает на наследуемый класс QGraphicsItem и деструктор Triangle.
Я сначала пытался код сам исправить, но ничего не вышло и я просто скопировал Ваш.
Скопировал triangle.h и triangle.cpp.
Что это может быть?

Отвратительная ошибка на самом деле.

В одном случае достаточно прописать Q_OBJECT.
В другом случае достаточно удалить build и пересобрать проект.
Один раз пришлось пересоздавать проект с нуля.
Проблема в том, что какие-то таблицы мок-файлов портятся. До сих пор порой до конца не понимаю, из-за чего такая проблема происходит. Иногда случается из-за добавления новых файлов в проект.

Вы как всегда правы, удалить билд и перезапустить было решением проблемы


Only authorized users can post comments.
Please, Log in or Sign up
June 25, 2019, 2:41 p.m.

C++ - Test 001. The first program and data types

  • Result:40points,
  • Rating points-8
June 25, 2019, 9:16 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:40points,
  • Rating points-8
June 24, 2019, 5:49 p.m.
Serg Zhi

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
Last comments
June 24, 2019, 10:23 a.m.
Евгений Легоцкой

Хорошо, ну будут проблемы помимо того, что касается статей, то не стесняйтесь задавать вопросы на форуме.
June 24, 2019, 10:21 a.m.
Михаил Булатов

Извиняюсь, все работает(из-за невнимательности).
June 24, 2019, 9:52 a.m.
Евгений Легоцкой

Придётся делать ещё сигнал в дочернем qml и пробрасывать через коннекты и обработчики. А вообще нужно смотреть конкретный код и что вы пытаетесь сделать. Так что лучше будет, если вы зад...
June 21, 2019, 8:31 a.m.
Ruslan Polupan

Вот моя строка по которой все отлично сработало %cqtdeployer% -bin c:/CentralMposKeys/CentalMposKeys.exe -qmake c:/Qt/5.12.2/mingw73_64/bin/qmake.exe
June 21, 2019, 8:24 a.m.
Андрей Янкович

Возможно кому то пригодится сqtdeployer для windows работает точно так же как и для Linux разница лишь в команде запуска Linux: cqtdeployer Windows: %cqtdeployer...
Now discuss on the forum
June 25, 2019, 6:16 p.m.
Алексей Внуков

только через webengine, прямого апи у Яндекса нет, вроде что-то есть у гугла, сам только начал интересоваться этим вопросом
June 25, 2019, 5:05 p.m.

Само заработало. Странно.
June 25, 2019, 2:32 p.m.

Похоже глюк вебсокета. К другим вебсокетам подключаюсь.
June 25, 2019, 1:55 p.m.
Андрей Янкович

падало потому что boolStatus был на стеке метода, после завершения метода переменная убивалась, и на обращении к ней было падение.просто сделай вот так: connect(&t, &QTimer::timeou...
June 25, 2019, 10:55 a.m.

По пункту 3 попытался переписать метод setData. В итоге комбобокс перестал работать. bool MySqlTableModel::setData(const QModelIndex& index, const QVariant& value, int /* role */){...
Looking for a Job?
10,000.00 руб. - 15,000.00 руб.
Нужен помощник для создания API.
Moscow, Moscow, Russia
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB