Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting
TIMEWEB
Sept. 27, 2015, 3:11 p.m.

Qt

mouse, QCursor, Qt, Qt уроки

The task "to customize the cursor in the" confronts a programmer when required by the design of the program, or is being developed game software, and it becomes a matter of design and atmosphere of the game.

Customization cursor in Qt is a trivial task, which includes installing a custom cursor for each visual object that is present in the game or program. When you hover over the object, the cursor changes its appearance according to the image that has been set in the object as the cursor.

In Qt project by default, the window in which it is inherited from QWidget, even no need to connect additional headers. All you need to do - is to create a class object via QCursor QPixmap from a resource file.

As the resource files necessary to create the image with the extension PNG and dimensions of 32x32 pixels. This size is recommended by the documentation for Qt, because it is widely supported.

This example uses three image:

  • cursorTarget.png - the cursor will be used in the field of QGraphicsView;
    cursorArrowRed.png - active cursor would be used in a window as a whole;
    cursorArrowGreen.png - the cursor will be used in the field of the button.

Cursors:

Sept. 24, 2015, 2:56 p.m.

Qt

QGraphicsScene, Qt, Qt урок, Qt5, рисование, рисование QGraphicsScene, Рисование Qt, рисование мышью

In this lesson, let us learn drawing with the mouse in Qt, based on the most primitive analogue Paint using QGraphicsScene . No adjustments or brush size, or palette, or special effects, and a red line, which we will draw the mouse.

Project Structure

Project Structure

The structure of the project consists of the following files:

  • paint.h - widget header file, which will be located a graphic scene to draw;
    paint.cpp - respectively the file source code for this widget;
    paintscene.h - customized header graphic scene, with which we work;
    paintscene.cpp - source file for customized graphic scene.
Sept. 23, 2015, 3 p.m.

Qt

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.

Qt

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. 20, 2015, 4:08 p.m.

Qt

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)
            continue;
        emit signalCheckItem(item);
    }
Sept. 19, 2015, 3:33 p.m.

Qt

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.

Qt

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.

Qt

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

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

Qt

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:

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

Qt

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.

d
April 26, 2019, 2:45 a.m.
djanaibekova_0301@mail.ru

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

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

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

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

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.
Евгений Легоцкой

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

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

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

Спасибо за ответ) У меня компоновщик на нее ругался просто. Оказалось, просто забыл 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(), в который передавать начальные значения для того...
R
April 19, 2019, 9:55 a.m.
RED_Spider

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

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