Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting

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

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.


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.



Only authorized users can post comments.
Please, Log in or Sign up
Feb. 18, 2019, 3:39 p.m.

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

  • Result:73points,
  • Rating points1
Feb. 15, 2019, 1:03 p.m.
Николай Булахтин

C++ - Test 002. Constants

  • Result:25points,
  • Rating points-10
Last comments
Feb. 14, 2019, 6:41 p.m.

Спасибо огромное! Заработало!
Feb. 12, 2019, 9:26 a.m.

Сам разборался, спасибо.
Feb. 12, 2019, 8:19 a.m.

День добрый! Можешь выложить форму mainwindow.ui от урока? Заранее спасибо
Feb. 11, 2019, 10:51 a.m.
Евгений Легоцкой

Нет, у меня проблема с жёстким диском случилась, занимался восстановлением ПК, ещё пару вечеров придётся этим заниматься, увы.
Now discuss on the forum
Feb. 17, 2019, 5:28 p.m.
Евгений Легоцкой

Добрый день. Очень извиняюсь за долгий ответ Первое, что нашёл, так это необходимость перерисовать чекбокс. void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem ...
Feb. 15, 2019, 3:36 p.m.
Евгений Легоцкой

Ну я тут нашёл одно решение, но сам его не проверял. Вам нужно помещать фамилии скорее всего в ячейки заголовка, и потом просто перерисовывать их QHeaderView * header = m_ui->tableWidget...
Feb. 15, 2019, 7:53 a.m.
Евгений Легоцкой

Добрый день! Не работал с remoteobjects, поэтому глянул документацию, чтобы рассмотреть, что это за зверь. После просмотра документации сложилось стойкой впечатление, что это вполне возм...
Feb. 14, 2019, 6:28 p.m.

Нашел решение на Java. Удалось интегрировать в проект сервиса на Qt, теперь из Qt запускаю Java-код акселерометра.
Join us in social networks

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