Evgenij LegotskojSept. 14, 2015, 12:36 p.m.

Qt/C++ - Lesson 018. QGraphicsItem – The inheritance and slots

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.


All work with this file is that we throw QGraphicsView widget in the center of the main window and stretch it to the width and height of the window.


File notable only ad graphic scene, our new class MyPoint and a slot for signal processing of MyPoint .


#include <QMainWindow>
#include <QGraphicsScene>
#include <QMessageBox>

#include <mypoint.h>

namespace Ui {
class MainWindow;

class MainWindow : public QMainWindow

    explicit MainWindow(QWidget *parent = 0);

    Ui::MainWindow  *ui;
    /* We declare gaficheskuyu scene and the point at which we will work */
    QGraphicsScene  *scene;
    MyPoint         *point;

private slots:
    /* The slot for the signal processing of the point */
    void slotFromPoint();

#endif // MAINWINDOW\_H


There is already more interesting. In this file, execute the implementation of the slot, and connect it to the object SLOT MyPoint class. And adds the object to the graphic scene.

#include "mainwindow.h"
#include "ui\_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    ui(new Ui::MainWindow)

    /* Initialize the graphic scene to the point at which we will work */
    scene = new QGraphicsScene();
    point = new MyPoint();

    /* Connect the signal from the point to the words in the main class */
    connect(point,SIGNAL(signal1()),this, SLOT(slotFromPoint()));

    /* Set the graphic scene in the widget */
    scene->addItem(point);  // And add to the scene point

    delete ui;

void MainWindow::slotFromPoint()
                             "Зафиксировано нажатие",
                             "Вы нажали на точку!!!"
                             "\n      С Уважением, Ваш КЭП!!!");


The key point in this file is that in the class applied multiple inheritance, namely, that we inherit not only from QGraphicsItem, but also from QObject. The fact is that if you do not inherit from the QObject, the Signals and the slot will not work and the project will not compile if you use the function to connect the connection signal from MyPoint, to slot in MainWindow.

#ifndef MYPOINT\_H
#define MYPOINT\_H

#include <QObject>
#include <QGraphicsItem>
#include <QPainter>

/* To work signals and slots, we inherit from QObject,
 * */
class MyPoint : public QObject, public QGraphicsItem
    explicit MyPoint(QObject *parent = 0);

    /* Signal to be sent in the event that there was a mouse click on the object
     * */
    void signal1();

    void mousePressEvent(QGraphicsSceneMouseEvent *event);

    /* These methods are virtual, so they need to be implemented 
     * in the case of inheritance from QGraphicsItem
     * */
    QRectF boundingRect() const;
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);

#endif // MYPOINT\_H


Most importantly, what I recommend to get attention in class, so it is that we override a method to call the click event on a graphic object right-click. And call the method of signal.

#include "mypoint.h"

MyPoint::MyPoint(QObject *parent)
    : QObject(parent), QGraphicsItem()




QRectF MyPoint::boundingRect() const
    return QRectF(0,0,100,100);

void MyPoint::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
    // Set the brush in QPainter and draw the circle, ie the point
    painter->drawEllipse(QRectF(0, 0, 100, 100));

/* Override method of capturing a mouse click event, add the sending signal from the object
 * */
void MyPoint::mousePressEvent(QGraphicsSceneMouseEvent *event)
    emit signal1();
    // Call the parent function mouse click events


As a result, you should get the following application, which displays a black circle in the window when you click on that pop up dialog box. Also you can find a video tutorial for this article, which shows a demonstration of the application and provides additional explanations to the program code.


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.
Support the author Donate

Здравствуйте. А где описание функции signal1()?

Добрый день. Вы имели ввиду реализацию? Для сигналов в Qt реализация не пишется, это всё генерируется в moc файлах под капотом Qt.


Спасибо за ответ) У меня компоновщик на нее ругался просто. Оказалось, просто забыл Q_OBJECT в начале класса указать.


Only authorized users can post comments.
Please, Log in or Sign up
Card image cap
Pulsum Via

Project for travelers from EVILEG.


Let me recommend you a great European Fornex hosting.

Fornex has proven itself to be a stable host over the years.

For Django projects I recommend VPS hosting

Following the link you will receive a 5% discount on shared hosting services, dedicated servers, VPS and VPN

View Hosting
Share on social networks

The EVILEG project has switched to a non-commercial basis and will develop solely on the enthusiasm of the site creator, the enthusiasm of users, donations and the hosting referral system

Thank you for your support

Available ways to support the project



C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4

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

  • Result:66points,
  • Rating points-1

C++ - Test 002. Constants

  • Result:58points,
  • Rating points-2
Last comments

Qt/C++ - Lesson 061. Adding images to the application using the Drag And Drop method from the file manager

Доброго времени суток. А если нужно и изображение и текст? Что-то потерялся немного.... // Вместо отрисовки иконки и текста будем отрисовывать только одно изображение // с н…

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

error insert into TableExample " Количество параметров не совпадает" Я путь свой прописывала и даже бд удаляла, чтобы заново сделать, не работает. (всё остальное как у вас... Вроде ка…

Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt

cialis powder comprare cialis online

GameDev on Qt - Tutorial 1. Track mouse movement in QGraphicsScene

Вполне возможно, что ты не закинул graphicsView в дизайнере в виджет

GameDev on Qt - Tutorial 1. Track mouse movement in QGraphicsScene

Кому интересно, поворот в slotTarget можно в одну строку организовать this->setRotation(90 + rotation() + qRadiansToDegrees(qAtan2(mapFromScene(point).y(), mapFromScene(point).x())));
Now discuss on the forum

Sorting the added QML elements in the ListModel

buy accutane online forum https://isotretinoinxp.top
  • Nomad
  • July 30, 2022, 5:42 a.m.

Как работать с HTMX?

Приветствую колеги. На днях наткнулся на вот это : https://htmx.org/ На офф сайте написанно вот такая фраза: htmx gives you access to AJAX, CSS Transitions, We…
  • harisr
  • July 25, 2022, 2:56 a.m.

QT - Native App Integration

Привет, у нас уже есть собственное приложение для Android. Можем ли мы интегрировать пользовательское представление QT в приложение со всем приложением QT внутри представления. Если да, ука…

Правильный запуск сервера на vps - Django

О я как то себе дома локальный сервер создавал. Вам же нужно просто сделать ручками конфигурацию системы. Настроить Nginx ну либо Apache (тут кому что нравится). Соответственно БД и всё остально…

Распознание объектов

Я к тому, что, возможно, софт уже есть.
© EVILEG 2015-2022
Recommend hosting TIMEWEB