Evgenii Legotckoi
Evgenii LegotckoiSept. 14, 2015, 10: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.

mainwindow.ui

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.

mainwindow.h

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

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

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

#include <mypoint.h>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    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

mainwindow.cpp

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) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    /* 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 */
    ui->graphicsView->setScene(scene);
    scene->addItem(point);  // And add to the scene point
}

MainWindow::~MainWindow()
{
    delete ui;
}

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

mypoint.h

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
{
    Q_OBJECT
public:
    explicit MyPoint(QObject *parent = 0);
    ~MyPoint();

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

protected:
    void mousePressEvent(QGraphicsSceneMouseEvent *event);

private:
    /* 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

mypoint.cpp

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()
{

}

MyPoint::~MyPoint()
{

}

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->setBrush(Qt::black);
    painter->drawEllipse(QRectF(0, 0, 100, 100));
        Q_UNUSED(option);
        Q_UNUSED(widget);
}

/* 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
    QGraphicsItem::mousePressEvent(event);
}

Result

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.

Video

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.

Do you like it? Share on social networks!

E
  • April 11, 2019, 6:15 p.m.

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

Evgenii Legotckoi
  • April 11, 2019, 6:29 p.m.

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

E
  • April 11, 2019, 6:49 p.m.

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
S

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

  • Result:53points,
  • Rating points-4
S

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

  • Result:57points,
  • Rating points-2
g

C++ - Test 005. Structures and Classes

  • Result:100points,
  • Rating points10
Last comments
J
JonnyJoMay 25, 2023, 2:24 p.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю!
Evgenii Legotckoi
Evgenii LegotckoiMay 25, 2023, 4:49 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Код на строчка 184-198 вызывает перерисовку области на каждый 4-й такт счётчика. По той логике не нужно перерисовывать объект постоянно, достаточно реже, чем выполняется игровой слот. А слот вып…
J
JonnyJoMay 21, 2023, 10:49 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, благодарю! Всё равно не совсем понимаю :( Если муха двигает ножками только при нажатии клавиш перемещение, то что, собственно, делает код со строк 184-198 в triangle.cpp? В этих строчка…
Evgenii Legotckoi
Evgenii LegotckoiMay 21, 2023, 5:57 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Добрый день. slotGameTimer срабатывает по таймеру и при каждой сработке countForSteps увеличивается на 1, это не зависит от нажатия клавиш, нажатая клавиша лишь определяет положение ножек, котор…
J
JonnyJoMay 20, 2023, 11:27 a.m.
How to make game using Qt - Lesson 2. Animation game hero (2D) Евгений, здравствуйте! Подскажите, а почему при нажатии одной клавиши переменная countForSteps увеличивается не на 1, на 4, ведь одно действие даёт увеличение этой переменной только на единицу? …
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiApril 16, 2023, 4:07 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Да, это возможно. Но подобные вещи лучше запускать через celery. То есть drf принимает команду, и после этого регистрирует задачу в celery, котроый уже асинхронно всё это выполняет. В противном …
АБ
Алексей БобровDec. 14, 2021, 7:03 p.m.
Sorting the added QML elements in the ListModel I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …
Evgenii Legotckoi
Evgenii LegotckoiMarch 29, 2023, 4:11 a.m.
Замена поля ManyToMany Картинки точно нужно хранить в медиа директории на сервере, а для обращения использовать ImageField. Который будет хранить только путь к изображению на сервере. Хранить изображения в базе данных…
Evgenii Legotckoi
Evgenii LegotckoiApril 24, 2023, 3:22 a.m.
Пакеты данных между сервером и клиентами Привет. Если классы имеют что-то общее в полях, а также общую идеологию и их можно вписать в иерархию наследования, то в первую очередь переписать так, чтобы один базовый класс объединял в…

Follow us in social networks