Evgenii Legotckoi
Evgenii LegotckoiSept. 18, 2015, 10:54 a.m.

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

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

  • Triangle.pro - 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.

mainwindow.ui

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

widget.h

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
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    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

widget.cpp

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) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    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);
}

Widget::~Widget()
{
    delete ui;
}

triangle.h

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
{
    Q_OBJECT
public:
    explicit Triangle(QObject *parent = 0);
    ~Triangle();

signals:

public slots:
    void slotGameTimer();

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

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

};

#endif // TRIANGLE_H

triangle.cpp

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;     
    setRotation(angle);    
}

Triangle::~Triangle()
{

}

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);
        painter->setBrush(Qt::red);    
        painter->drawPolygon(polygon);  
        Q_UNUSED(option);
        Q_UNUSED(widget);
}

void Triangle::slotGameTimer()
{
    /* Alternately checks for key presses
     * using the asynchronous reception state of the keys
     * is provided WinAPI
     * */
    if(GetAsyncKeyState(VK_LEFT)){
        angle -= 10;        // Set turn 10 degrees to the left
        setRotation(angle); // Rotate object
    }
    if(GetAsyncKeyState(VK_RIGHT)){
        angle += 10;        // Set turn 10 degrees to the right
        setRotation(angle); // Rotate object
    }
    if(GetAsyncKeyState(VK_UP)){
        setPos(mapToParent(0, -5));     /* Move the object 5 pixels forward to retranslate them
                                         * in the coordinate system of the graphic scene
                                         * */
    }
    if(GetAsyncKeyState(VK_DOWN)){
        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:

win32-msvc*{
    LIBS += -luser32
}

Result

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:

Video

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.

Do you like it? Share on social networks!

M
  • Oct. 13, 2017, 6:19 a.m.

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

Evgenii Legotckoi
  • Oct. 13, 2017, 6:50 a.m.

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

В одном случае достаточно прописать Q_OBJECT.
В другом случае достаточно удалить build и пересобрать проект.
Один раз пришлось пересоздавать проект с нуля.
Проблема в том, что какие-то таблицы мок-файлов портятся. До сих пор порой до конца не понимаю, из-за чего такая проблема происходит. Иногда случается из-за добавления новых файлов в проект.
M
  • Oct. 13, 2017, 7:23 a.m.

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

Добрый день.
Проблема следующая:
треугольник при перемещении не отрисовывается полностью, кроме того, на графической сцене остаются его следы, но если, например, свернуть приложение и заново его открыть, то треугольник отрисовывется как положено.

Добрый день. Переопределили boundingRect? и переопределили ли его правильно? выглядит так, что либо boundingRect неправильно расчитывается, либо не вызывается update сцены.

Спасибо, не поставил минус в boundingRect

СГ
  • Nov. 27, 2019, 10:21 a.m.

Евгений здравствуйте!Только начинаю разбираться в QT и работаю в Unreal Engine 4(делаю игры и приложения).Можно ли их сравнивать или они для разных задач.И что не сделать в Unreal,что можно сделать в QT.Оба на с++,у обоих есть дизайнеры для интерфейса.В Unreal правда blueprints,а в QT Qml(я так понимаю это его плюс перед Unreal).На Qml можно писать красивый интерфейс,но в Unreal это делать проще?

Evgenii Legotckoi
  • Nov. 27, 2019, 10:52 a.m.
  • (edited)

Добрый день

Они для разных задач.

  • Unreal Engine 4 - это всё-таки игры. Писать CAD систему или программу для клиентов по работе с базой данных я бы точно не стал, не для того это.
  • Qt - это различные приложения, от десктопных до мобильных, но точно не игры. Вернее игру написать можно на Qt, но я бы не стал писать что-то очень сложное. Для этого нужно брать игровой движок, тот же самый Unreal Engine 4.

В Qt вам для игры придётся написать собственный движок, который будет отвечать за физику и т.д. А в Unreal Engine 4 придётся писать очень много подготовительной логики для моделей данных (таблицы и т.д.). Ну либо использовать Felgo - фреймворк для написания приложений, который написан поверх Qt, они там сделали большую работу для мобильных приложений. В качестве движка используют cocos2d для игр.

Делать вёрстку приложения на QML определённо проще, якоря очень хорошая вещь. Когда я пробовал делать простую вёрстку в UE4 для меню, то мне якорей очень сильно не хватало, которые есть в QML.

blueprints - это конёчно жёсткое псевдопрограммирование )))) работать с ними можно, но я прекрасно понимал, когда пробовал себя в UE4, что логику, которую я писал в blueprints 8-10 блоками , на С++ я мог бы написать в две строки кода, которые были бы предельно понятны. Поэтому сразу начал искать варианты переноса логики в C++.

blueprints хороши для того, что требует 3D представления, но биты и байты ими перебирать - это самовредительство.

В общем сравнивать можно по ощущениям, но точно не по назначению. UE4 - игры, а Qt - это всё остальное.

СГ
  • Nov. 27, 2019, 11:22 a.m.

Евгений, спасибо за развёрнутый ответ!

kesh KD
  • May 13, 2020, 3:28 p.m.

"В дизайнере интерфейсов просто закидываем QGraphicsView в виджет. Больше ничего не требуется."

Для тупеньких, объясните пж (Qt Creator 4.10.2)

Evgenii Legotckoi
  • May 13, 2020, 4:06 p.m.

В Qt Creator двойным кликом открыть ui файл, и перетащить в виджет Graphics View. Потом выделить корневой виджет и нажать кнопку для создания GridLayoyt, чтобы Graphics View нормально позиционировался.

kesh KD
  • May 14, 2020, 3:35 a.m.
  • (edited)

Спасибо, и пока пользуясь случаем. PushButton в основном для чего?

Evgenii Legotckoi
  • May 14, 2020, 3:57 a.m.

Это обычная кнопка, клик по этой кнопке можно привязать к какому угодно функционалу, от применения настроек до открытия диалога. Зависит от логики, которую в неё вкладывают.

Если у вас и дальше будут вопросы, то задавайте их на форуме, каждый в отдельной теме, чтобы они уже были логически структурированы и не было оффтопов.
Я просматриваю все вопросы, которые появляются на форуме и по возможности отвечаю на них. Форум

V
  • Dec. 8, 2020, 9:44 a.m.

Может вы мне подскажете, ибо я не могу понять и найти как эти строчки изменить под linux:

Evgenii Legotckoi
  • Jan. 28, 2021, 9:47 a.m.

Под Linux Не подскажу, там всё несколько сложнее

b
  • April 6, 2022, 2:12 a.m.

Привет, такой вопрос. Пишу игру, где отрисовываю абсолютно всё через QPainter. Спрайты анимации вывожу через DrawImage(). Какой из вариантов (QPainter и QGraphicsView) лучше в плане производительности? По поводу функционала понятно, но интересует именно скорость отрисовки, так как на средних смартфонах бывает падает FPS

Comments

Only authorized users can post comments.
Please, Log in or Sign up
г
  • ги
  • April 24, 2024, 1:51 a.m.

C++ - Test 005. Structures and Classes

  • Result:41points,
  • Rating points-8
l
  • laei
  • April 23, 2024, 7:19 p.m.

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

  • Result:10points,
  • Rating points-10
l
  • laei
  • April 23, 2024, 7:17 p.m.

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

  • Result:50points,
  • Rating points-4
Last comments
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 7:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 8:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 3:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 5:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 4:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 12:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 2:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks