Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting

Qt/C++ - Tutorial 073. Signals and slots. Connecting Slots to Overloaded Signals in the Qt5 Syntax

Signal, Slot, Qt, Qt5

Quite a frequent problem when working with signals with slots in Qt5, according to my observations on the forum, is the connection of slots in the syntax on the pointers to signals having an overload of the signature. The same applies to slots that have an overload.

Let's take a test class that has overloaded signals.

#include <QObject>

class TestClass : public QObject
    explicit TestClass(QObject *parent = nullptr);

    void testSignal(int arg1);
    void testSignal(int arg1, int arg2);

Here there is a signal, with an overload of the signature. Connect this signal will also be to the slots that are declared in the Widget class, and which also have an overload of the signature.

#include <QWidget>
#include "testclass.h"

namespace Ui {
class Widget;

class Widget : public QWidget

    explicit Widget(QWidget *parent = 0);

private slots:
    void onTestSlot(int arg1);
    void onTestSlot(int arg1, int arg2);

    Ui::Widget *ui;
    TestClass* m_testClass;

How it was in Qt4

Within Qt4, everything was solved quite simply by specifying the signature of the signal and the slot in the SIGNAL and SLOT macros.

connect(m_testClass, SIGNAL(testSignal(int,int)), this, SLOT(onTestSlot(int,int)));
connect(m_testClass, SIGNAL(testSignal(int)), this, SLOT(onTestSlot(int)));

How it became in Qt5

But in Qt5, when writing in the new syntax of signals and slots, there are some problems. Because you need to make the static_cast of the method signature.

    connect(m_testClass, static_cast<void(TestClass::*)(int)>(&TestClass::testSignal),
            this, static_cast<void(Widget::*)(int)>(&Widget::onTestSlot));
    connect(m_testClass, static_cast<void(TestClass::*)(int, int)>(&TestClass::testSignal),
            this, static_cast<void(Widget::*)(int, int)>(&Widget::onTestSlot));

By the way, the new syntax also allows you to connect signals to slots with a smaller signature, as it was in Qt4.

connect(m_testClass, static_cast<void(TestClass::*)(int, int)>(&TestClass::testSignal),
        this, static_cast<void(Widget::*)(int)>(&Widget::onTestSlot));

Advantages of the new syntax

And now a stumbling block. Why use the new syntax of signals and slots? I still hear this question from time to time. Especially when people see such terrible castes of signatures.

  1. Therefore, I will list potential advantages:The ability to track errors in the connection of signals and slots at the compilation stage, rather than in the runtime
  2. Reducing compilation time by excluding macros from the code
  3. The ability to connect lambda functions, it's quite an important bun
  4. We protect ourselves from errors when we try to connect from the outside to a private slot. Yes!! Yes!! The SIGNAL and SLOT macros ignore the access levels of methods, violating OOP.

In general, for me this is enough, but for you?


Отличная необходимая статья.


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