Advanced search
Sept. 1, 2019, 10:09 a.m.

QtКак обращаться к объектам QGraphicsItem созданным в QGraphicsView

Добрый день.
С помощью такого класса создаю эллементы в QGraphicsView

class MoveItem : public QObject, public QGraphicsItem
    explicit MoveItem(QObject *parent = 0);
    int id;
    int width, height;

    QRectF boundingRect() const;
July 20, 2019, 8:52 a.m.

QtКак добавлять на QGraphicsScene элементы в виде картинок

Добрый день.
Взял код из этой статьи.
Кочу добавлять эллементы QGraphicsItem не в виде прямоугольника, а в виде картинки.
Попробовал сделать так, но картинка не добавляется.
Скажите пожалуйста, как сделать правильно?

void MoveItem::paint(QPainter *painter, cons…
May 8, 2018, 7:44 a.m.

C++Нарисовать дугу в QGraphicsItem

Необходимо уметь рисовать направленный граф.
В примерах QT нашел проект elasticnodes . Его переделал под свою задачу.
Получилось реализовать создание вершин/стрелок и их выделение/удаление/перемещение. Вот только не получается сделать дугу на самого себя и его область выделения. …

QtQt / C ++ - Tutorial 072. An example of a vector editor on Qt

Quite often there are questions in one way or another related to the work of the graphic scene, with custom figures, drawing lines on the graphic scene, and even all sorts of broken lines. And then I remembered about one project that I did as a test task.

Namely, it was a vector editor that can:

  • Create rectangles
  • Change the size of these rectangles
  • Twist the rectangles around the center
  • Fill rectangles
  • Fill rectangles with a gradient
  • Change the width of the outline of a rectangle
  • Set the color of the outline of a rectangle
  • Create lines
  • Specify the width and color of the created line
  • Make broken lines from lines by double clicking by adding points on the line
  • Select all graphic objects and drag them with a handful
  • Save the resulting image to an SVG file, and restore all graphic objects from this file

On the implementation of this project in its time (1.5 years ago), I spent about 36 hours of working time ... now it would take less time.

May 7, 2017, 6:41 a.m.

PyQt5Не приходят mousePressEvent от дочерних item'ов а

На QGraphicsScene размещен переопределенный QGraphicsRectItem, в который добавлены с помощью addItem несколько дочерних QGraphicsRectItem. Фильтр событий для child'ов включен (setFiltersChildEvents(True)). По идее, любой клик на child, должен вызывать mousePressEvent у родительского QGraphicsR…

Jan. 17, 2017, 5:17 a.m.

QtСмена цвета объекта при клике мышью

Вот проект. При нажатии на квадрат он меняет цвет. Хотелось бы, чтобы он цвет менял, но не двигался. Мне зафиксировать сцену нужно или что сделать? Может кто-нибудь изменить код, чтобы квадрат не двигался, а лишь изменял цвет.

QtQt/C++ - Lesson 033. Working with QGraphicsObject instead of QGraphicsItem

My attention was drawn to the fact that for working with signals and slots instead of a class inherited from QGraphicsItem and from QObject , you can use a class inherited from QGraphicsObject . Indeed, if a little rummage in the source QGraphicsObject , we find that it is a class inherited from QGraphicsItem and from QObject . That is also used multiple inheritance, but in this case all the bikes have written to us. Therefore, we try to work with this class as an example of the game mechanics.

Specifically, I propose to write a program in which we will move the hero mouse click on the graphic scene, as in any RPG like Diablo.

Project structure for work with QGraphicsObject

  • - the profile of the project;
  • main.cpp - the main source file;
  • widget.h - header file of the application window;
  • widget.cpp - file source code of the application window;
  • customscene.h - customized header graphic scene;
  • customscene.cpp - file source customized graphic scene ;
  • triangle.h - header file of hero class;
  • triangle.cpp - source file triangle class.

QtQt/C++ - Lesson 027. Polymorphism in Qt by the example of geometric shapes in QGraphicsScene

Polymorphism is one of the paradigms of OOP (Object Oriented Programming). Polymorphism implements the ability to provide base-class properties and methods, the implementation of which is not known for future classes that inherit from this class. That is the base class in this case, has all the necessary methods for the realization of tasks, but the specific implementation of certain methods is assigned to the descendants of the classes. And, as a rule, it is an abstract base class, then there are no objects on it.

For example, it is necessary to implement the program in which it is possible to draw a few geometric shapes with the mouse on the graphic scene , choosing the current figures with the buttons in the application. To do this, you can create several classes, each of which will implement all the necessary functionality, and actually duplicated in each class most of the code, making it more difficult and confusing design. Alternatively, you can create one base class, eg, Figure , which is inherited from QGraphicsItem , and implement all the basic functionality in this class, and then create three classes that will inherit from this class, but to implement them only a method of drawing the figure itself: Romb , Square , Triangle .

In the following figure shows the inheritance logic for the base class Figure. Applied as multiple inheritance class Figure for the implementation work with signals and slots .

QtQt/C++ - Lesson 023. Moving QGraphicsItem on QGraphicsScene with mouse help

Let's say that you make an application that will be displayed the elements of the network infrastructure on the graphic scene . The question is how to make the movement of these elements with the mouse, you have to implement drag and drop elements. In other words, take the item with the mouse and exercise his moving to another place graphic scene.

Project Structure

To illustrate an example of creating a new project and add the new class, inherited from QGraphicsItem .

  • - the profile of the project;
  • main.cpp - launch files;
  • widget.h - header of the main window;
  • widget.cpp - file source of the main window;
  • moveitem.h - header graphic element;
  • moveitem.cpp - file source graphic;
  • widget.ui - form the main window.

QtHow to make game using Qt - Lesson 4. Enemy – meaning in the survival

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
How to become an author?

Contribute to the evolution of the EVILEG community.

Learn how to become a site author.

Learn it

Good day, Dear Users!!!

I am Evgenii Legotckoi, developer of EVILEG. And it is my hobby project, which helps to learn programming another programmers and developers

If the site helped you, and you want also support the development of the site, than you can donate by following ways


Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting Timeweb
May 25, 2020, 11:33 a.m.
Mitja Nagibin

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

  • Result:50points,
  • Rating points-4
May 25, 2020, 5:05 a.m.

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

  • Result:66points,
  • Rating points-1
May 25, 2020, 3:30 a.m.
just maks

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

  • Result:80points,
  • Rating points4
Last comments
May 26, 2020, 6:51 a.m.
Evgenij Legotskoj

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

У вас база данных не открылась Исправьте путь к базе данных на свой корректный в следующих методах void DataBase::connectToDataBase() bool DataBase::openDataBase()
May 26, 2020, 6:22 a.m.
Tima 1

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

полностью повторил структору проекта. В форму дабавил tableView. Но при запуске получаю форму только с пустым tableView. Можете подсказать в чем пробелма?
May 26, 2020, 6:02 a.m.
Evgenij Legotskoj

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

Потому что это файл который нужно создать, а не библиотека. В статье есть содержание этого файла. Добавляйте в проект. Копируйте содержимое из статьи.
May 26, 2020, 6 a.m.
Tima 1

Qt/C++ - Lesson 004. QSqlTableModel – How to present the table from database?

не удается подключиить библеотеку include "database.h" выдает ошибку. Можете помочь?
Now discuss on the forum
May 26, 2020, 8:26 a.m.
Vladislav Melenchuk

Templatetags из GenericForeign

Всем привет, не подскажете как сделать templatetags на вывод последних комментариев в сайдбаре для постов? Именно для постов. @register.simple_tag()def get_last_comments(): return Commen…
May 26, 2020, 5:16 a.m.

Отсутствие драйвера SQLite в пакете Qt 4 на Linux

Вот честно непонимаю почему до сих пор используют qt4, там же столько всего отсутствует, много фишек и возможностей нету там. То есть используя такое старье приходится много писать самому а не и…
May 26, 2020, 2:24 a.m.
Dzhon Kofi

Disable autoscroll

такие естественные решения все перепробовал. Получилось вчера так: const int maximumScroll = ui->_samples->verticalScrollBar()->maximum();const int sliderPos = ui->_samp…
May 26, 2020, 12:43 a.m.
Ruslan Polupan

Посоветуйте новичку (базы данных и Qt, что учить)

Без БД сейчас практически никуда. Поэтому SQL надо знать. SQLite самы простой вариант, но имхо лучще начать с бд клиент-сервер. Настроить сервер. Подключаться клиентом. Просто это помогает понят…
May 25, 2020, 2:42 p.m.
Esteban José María

Компиляция пустого проекта Qt Android

qt 5.12.8 BUILD SUCCESSFUL in 42s 28 actionable tasks: 28 executed Android package built successfully in 68.251 ms. Ну, буду разбираться по-тихоньку. :)
© EVILEG 2015-2020
Recommend hosting TIMEWEB