Sept. 20, 2015, 4:08 p.m.


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

Once the game has animated fly, which moves under the influence of the keyboard shortcuts, it is time to add meaning to the game. Add goal Fly, for example, it will eat the apples that will be counted. That is, you must configure the Flies interaction with other objects, in this case apples.

For apples, you must create a separate class, which will also be otnasledovan from QGraphicsItem . When creating the apples must have a random color, which will also be initialized in the class constructor using apples qrand() function.

When fly stumbles upon an apple, it is necessary to transmit the information to the core of the game, which is in the widget class. To do this, we analyze the motion flies objects that fall within its field of view, and which is necessary to work out the interaction.

    /* Checks for whether the fly bumped into any graphic element on the stage. 
     * To do this, we define a small area in front of the fly, which will search for items
     * */
    QList<QGraphicsItem *> foundItems = scene()->items(QPolygonF()
                                                           << mapToScene(0, 0)
                                                           << mapToScene(-20, -20)
                                                           << mapToScene(20, -20));
    /* Then we check all the elements. One of them will fly itself - do not do anything with it. 
     * And send signal to the game core with another objects
     * */
    foreach (QGraphicsItem *item, foundItems) {
        if (item == this)
        emit signalCheckItem(item);
Sept. 19, 2015, 3:33 p.m.


GameDev, QPainter, Qt, анимация, написать игру

In the second lesson we'll get to the next aspect of the writing of the game - the hero Animation. In the last lesson it was considered as a control object in the graphic scene, and the main character played a red triangle, but it is not very interesting. So we will turn the triangle into an animate object, namely the Fly, which will crawl under the control of the keyboard and move the legs when moving.

In this lesson, the adjustment made in the code triangle.h, triangle.cpp and just a little in widget.cpp file.

Animation Fly on steps

We describe an algorithm, which should be the rendering Flies:

  1. Initialize variable in the class constructor, which will be responsible for the number of legs position. There will be three positions fly legs.
  2. Initialize variable in the class constructor, which will be useful to consider the timer ticks of the game, then those ticks during which the fly moved. It is necessary to weed out those tics, in which there was no movement Flies Fly otherwise be constantly iterate legs, even if we do not manage Fly .
  3. Draw Fly in the paint method, choosing which of the provisions of the flies legs will be drawn.
  4. The slot that handles the event starting the game timer produces accumulation and reset the counter ticks useful game timer and depending on its value set position Flies legs, namely completely redraw the Fly with the correct position of the legs.
Sept. 18, 2015, 2:54 p.m.


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.

Sept. 17, 2015, 2:22 p.m.


QGraphicsItem, QPainter, QPolygon, Qt, Qt5, Рисование Qt, Рисование Qt5, треугольник

Drawing interfaces, the formation of the database tables, work with the network - it's all good, but sometimes you want to just draw something, such as a triangle. And then of course, revive this place, so that they can be controlled, and subsequently to turn this project into a little game. Well, who does not want to write your own game, even the most simple?

Let us then take the first step toward the unpretentious games, namely deal with drawing objects to Qt, trying to draw a triangle.

Project structure

  • - Project profile, created by default, and in this project does not require the correction;
  • main.cpp - file, which starts with the application, the file is called a widget, which will be located in the graphic scene with a triangle;
  • widget.h - header file of a widget with a graphic scene;
  • widget.cpp - source file of widget;
  • triangle.h - Triangle header file class that inherits from QGraphicsItem;
  • triangle.cpp - source file of Triangle class;
Sept. 14, 2015, 4:36 p.m.


QGraphicsItem, QGraphicsItem example, QGraphicsItem Qt, QGraphicsItem слот, Qt, множественное наследование

Let's talk a little about the inheritance from QGraphicsItem and application of signals and slots system in interaction with graphical objects on the graphic scene QGraphicsScene . The objective of this lesson is to create an application that on the graphic scene to be displayed object class QGraphicsItem , by clicking on which will appear QMessageBox dialog box signaling the event clicking on the graphic.

The project structure to work with QGraphicsItem

The structure of the project include:

  • - profile;
  • mainwindow.h - header file of the main application window;
  • mainwindow.cpp - file source code of the main application window;
  • mypoint.h - header code of the class inherited from QGraphicsItem;
  • mypoint.cpp - respectively, the source code;
  • main.cpp - master file from which you start the application, in the classroom is not considered as created by default;
  • mainwindow.ui - design file of the main window.
Sept. 12, 2015, 4:12 p.m.


QGraphicsScene, QGraphicsScene пример, Qt, QGraphicsScene Qt5, QGraphicsScene example

From this article we begin to explore the Qt graphic libraries, to be exact, QGraphicsScene. This class provides the functionality to manage a large number of 2D objects. QGraphicsScene set to QGraphicsView.

We describe the features that need to be implemented in our application:

  • Adding a graphic scene in QGraphicsView.
  • Rendering the graphics objects on the two stage via lines, namely a rectangle and a square.
  • Dynamic resizing of graphic scenes, depending on changes QGraphicsView sizes.
  • Dynamically changing objects on the graphic scene, depending on the size of the graphic scene.

Project Structure for QGraphicsScene

Project Structure for QGraphicsScene

By the project structure "Default" added another class MyGraphicView .

The fact is that for the convenience of working with QGraphicsScene it was decided to create a class that inherits from QGraphicsView already inside to operate graphical scene and its objects.

Sept. 4, 2015, 3:54 p.m.


qcheckbox, qcheckbox center, Qt, QTableWidget

One of the first problems in working with The QTableWidget , which are trying to solve, start to work with this widget - setting QCheckBox in the middle of the cell. The fact that the standard check box in QTableWidget checkbox attached to the left edge of the cell, while the right side is given for explanatory text. But the text may not be, but the area still remains. But at the same time it allows you to set QTableWidget in his cell widgets, which we use to solve this problem.

This article is an extension of a previous article on working with QTableWidget , therefore, to see the full code of the project I encourage you also to the article. This article provides only the code necessary to solve the problem.

Project Structure for QCheckBox center

Project structure remains the same as in the previous article .


The form for the application window QCheckBox

In the main application will be placed:

  • QTableWidget
  • QLable
Sept. 4, 2015, 3:30 p.m.


Qt, Qt Таблица, QTableWidget, QTableWidget example, QTableWidget пример

Using QTableWidget will be the first in a manner that will advise you to create tables with checkboxes on Qt. So let's look at this option and work with tables in Qt and certainly applicable checkboxes.

So, the lesson to be more close to reality, grabbed some code from lesson QDataWidgetMapper . Namely, take a class to work with the database, so they'd just do a table from the database. After that, make the shape of the main application window and output data from the table with the mapping checkboxes. Naturally, when the application database table is created and populated by several records, which we will display in the widget.

Project Structure for QTableWidget

I suggest to get acquainted with the project structure:

  • - profile;
  • mainwindow.h - header file of the main application window;
  • mainwindow.cpp - source of window;
  • main.cpp - the main source file from which the application starts;
  • mainwindow.ui - form of the main application window;
  • database.h - header file of helper class to be used for information that is placed in a database;
  • database.cpp - source of helper class file to be used for information that is placed in a database;
Sept. 1, 2015, 3 p.m.


QPushButton, Dynamic widget, Динамический виджет, Qt

In complex projects may not be enough to have a static widget in the interface as the incoming information can change every second. Therefore the question on creation of dynamic widgets, such as the layout Qt buttons.

This tutorial describes how to dynamically create QPushButton buttons, receiving signals from these buttons, and the subsequent removal of these buttons from the layout Qt.

Project Structure

Description of the Project:

  • - profile;
  • mainwindow.h - header file of the main application window;
  • mainwindow.cpp - source of window;
  • main.cpp - the main source file from which the application starts;
  • mainwindow.ui - form of the main application window;
  • qdynamicbutton.h - header file of the wrapper class, which simplifies the process of working with dynamic objects in this lesson;
  • qdynamicbutton.cpp - source file wrapper class that simplifies the process of working with dynamic objects in this lesson.
Aug. 31, 2015, 2:39 p.m.


QMenu, QMenu example, QMenu Qt, Qt, контекстное меню, меню

To use the context menu in Qt is used QMenu class. When performing actions that should cause the menu handler is called, which creates the menu and binds handlers to act in this menu.

In this lesson, work with the shortcut menu will be shown in the example code from the tutorial on working with QDataWidgetMapper. In this lesson, the two files from the previous lesson will be modified, but the project will not work if you do not include it as in the previous lesson files that can not be edited.

Project structure for QMenu

Project structure remains the same as in the tutorial, which is based on the lesson. Changes in the code will be subjected to only two files:

  • mainwindow.h
  • mainwindow.cpp
May 19, 2019, 1:49 a.m.

Qt - Test 001. Signals and slots

  • Result:78points,
  • Rating points2
May 17, 2019, 1:14 p.m.

Qt - Test 001. Signals and slots

  • Result:42points,
  • Rating points-8
May 17, 2019, 4:18 a.m.

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

  • Result:57points,
  • Rating points-2
Last comments
May 21, 2019, 8:10 p.m.

Приветствую! Я думаю дойдёт и до этого, но пока изучать его у меня нет желания.
May 20, 2019, 7:20 p.m.
Евгений Легоцкой

Добрый день! Вы не думали разместить репозиторий проекта на GitHub?
May 18, 2019, 2:03 p.m.

Спасибо большое! Вскоре буду разбираться!
May 18, 2019, 9:13 a.m.
Евгений Легоцкой

Добрый день! Отнимать значение общего счётчика можно в деструкторе класса кнопки QDynamicButton::~QDynamicButton(){ ResID--;} При этом я бы ещё переустанавливал значения вс...
May 14, 2019, 10:33 p.m.

Здравствуйте!А не подскажите, как можно при удалении какой либо кнопки, у щётчика отнять значение?Дабы например четвёртой кнопке соответствовал ID 4, а не 5 скажем
Now discuss on the forum
May 22, 2019, 1:40 p.m.
Даниил Тетерин

Есть задание - сделать программу-расписание, где главное окно - календарь, в котором можно нажать на любой день, тогда откроется окно, в котором будут видны уже существующие на этот день зад...
May 22, 2019, 10:05 a.m.

Данный код компилируется только для 32 битной системы, а на 64 битной выдаёт ошибку линковки LNK2019. Возможно ли как-то, используя функцию RegisterHotKey, использовать глобальные горячие клав...
May 22, 2019, 5:08 a.m.

Евгений, доброго времени суток и спасибо! Все получилось.
May 20, 2019, 8:43 a.m.

Кинул библиотеки в папку с проектом и в папку к компилируемым файлам.В файле проекта прописал так, но все равно выдает ту же ошибку QT += core gui networkgreaterThan(QT_MAJOR_VERSI...
May 20, 2019, 1:47 a.m.

Что вы понимаете под статической сборкой приложений? В какой среде?

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

Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB