Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
Sept. 23, 2015, 3 p.m.


GameDev, QMediaPlayer, QMediaPlaylist, Qt звук, Qt, написать игру

Getting to the fifth and final lesson on writing games on Qt, which will add sound using QMediaPlayer class. I propose to add the three types of sounds: Eating apples, buzzing flies that will be buzzing when moving and heartbreaking cry when Fly will eaten.

The sound in the project structure

The sound in the project structure is placed in a resource file, as shown in the screenshot of the project structure.

To do this, create a resource directory and folder game . Further, in the resources folder, create a resource file, which prescribes the prefix "/" and add audio files that are pre-placed in the game folder.

And then the sound must be connected to the project using QMediaPlayer class.

In this case, the sounds are connected in three places of the code.

Sept. 22, 2015, 4:36 p.m.


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

Continuing the theme of how to write a play on Qt. Once in past articles a fly was created, that eating apples, it is time to create her enemy. And the enemy flies, as is well known, the spider. Creation of game characters, who will participate in the immediate life of your main character - is not only rendering the animation action and movement, as well as the reactions of the logic on the impact of the player, but also artificial intelligence, in accordance with the logic of which will be determined by the behavior of the game character. Thus, we add to the game a new meaning, not only to eat as many apples, but to survive at any cost.

We define the behavior of the spider in this game. What should he do? Yes, the most common of all the action - to hunt a fly just chasing it on the playing field.

Also add to the game button to start the game process, and pause, and the most important thing to add - it's Game Over.

The enemy flies in the project structure

As is the case with the fly in the structure of the project added an additional class, which will be responsible for the object, which is a spider.

  • spider.h - header file of spider
  • spider.cpp - source file of spider
Sept. 21, 2015, 2:44 p.m.


paintEvent, QPainter, QPainter example, QPainter пример, Qt QPainter, Qt рисование

In Qt framework you have gat opportunity to draw on the graphics scene and widgets. For it you can use QPainter class. Drawing objects on the widgets can be made in paintEvent (* event) function that is called when rendering the widget.

In this tutorial you will work with this function. It will create an object of class QPainter , and with it will be drawn circle. At the same time drawing a circle will depend on three QRadioButton object class. Depending on what radiobatton selected will be selected and the color of circle, if none radiobatton is selected, then the circle is drawn in white.

Project structure for QPainter

Project contains the following files:

  • - project profile;
  • widget.h - header file of Widget class, which will works with QPainter;
  • widget.cpp - source file of Widget class, which will works with QPainter;
  • main.cpp - file with main function;
  • widget.ui - application interface
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. 16, 2015, 9:14 a.m.

Data Transmission Technologies

Frame Relay, виртуальный канал

Origin of Frame Relay technology is the end of the 80s. At this time, more and more began to receive the spread of reliable digital channels plesiochronous systems, synchronous digital hierarchy (PDH and SDH). These technologies provide a reliable high-speed channel with low noise and error.

X.25 protocol stack, which existed before the advent of Frame Relay, included a variety of systems error checking and recovery, as used in the low-speed channels with a large noise level. But with the advent of technologies PDH and SDH communication quality has improved significantly and eliminated the need for a complex system of checks, which was present in the X.25. As a result, the change of the protocol stack came Frame Relay technology, which had only the minimum necessary for delivering information from the sender to the recipient. It is also a breakthrough of this technology was that it provided a guaranteed bandwidth, which could provide early technology.

Sept. 15, 2015, 3:44 p.m.


Qt5, пример, example, сигнал, сигналы Qt, сигналы слоты Qt, сигналы слоты Qt5, слот, слоты Qt

Signals and slots are used for communication between objects. The signals and slots mechanism is a central feature of Qt and probably the part that differs most from the features provided by other frameworks. Signals and slots are made possible by Qt's meta-object system .


In GUI programming, when we change one widget, we often want another widget to be notified. More generally, we want objects of any kind to be able to communicate with one another. For example, if a user clicks a Close button, we probably want the window's close() function to be called.

Other toolkits achieve this kind of communication using callbacks. A callback is a pointer to a function, so if you want a processing function to notify you about some event you pass a pointer to another function (the callback) to the processing function. The processing function then calls the callback when appropriate. While successful frameworks using this method do exist, callbacks can be unintuitive and may suffer from problems in ensuring the type-correctness of callback arguments.

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.
April 26, 2019, 2:45 a.m.

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

  • Result:42points,
  • Rating points-8
April 25, 2019, 8:02 p.m.

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

  • Result:60points,
  • Rating points-1
April 24, 2019, 2:30 p.m.

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

  • Result:50points,
  • Rating points-4
Last comments
April 21, 2019, 4:22 p.m.
Евгений Легоцкой

Через метод setIcon table.horizontalHeaderItem(0).setIcon("qrc://path/to/icon.png")
April 21, 2019, 3:48 p.m.
Евгений Легоцкой

Добрый день! Спасибо за комментарий. Там действительно лучше будет сделать с инициализацией по умолчанию.
April 18, 2019, 3:37 p.m.

А как иконку в хедер задать?
April 18, 2019, 2:15 a.m.

доброго времени,большое спасибо за пример для начинающего)при адаптации к своему проекту столкнулся с таким ньансом:в vepolyline.h в 47 строке нужна инициализация по умолчанию: int m_pointF...
April 11, 2019, 12:49 p.m.

Спасибо за ответ) У меня компоновщик на нее ругался просто. Оказалось, просто забыл Q_OBJECT в начале класса указать.
Now discuss on the forum
April 25, 2019, 10:51 a.m.
Ruslan Polupan

Изменил функциютеперь работает. bool ModelTerminals::setData(const QModelIndex &index, const QVariant &value, int role){ Q_UNUSED(role) if(!index.isValid()) {return false;...
April 24, 2019, 6:20 a.m.
Ruslan Polupan

я так понимаю надо инфорация об устройствах.Я бы пробовал так rust@suse:~> lsblk -PNAME="sda" MAJ:MIN="8:0" RM="0" SIZE="111,8G" RO="0" TYPE="disk" MOUNTPOINT=""NAME="sda1" MAJ:MIN="8...
April 21, 2019, 4:16 p.m.
Евгений Легоцкой

Приветствую Нужно сохранять где-то выбранное значение, а потом восстанавливать его. Или использовать QSettings или добавить метод open(), в который передавать начальные значения для того...
April 19, 2019, 9:55 a.m.

мені важко це зараз навіть перевірити, тому що знайшов коміт, це ще було в 2016 році, і цей код не буде працювати коректно зараз, єдине скажу що це були QThread
Join us in social networks

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