Evgenij LegotskojNov. 9, 2017, 2:22 a.m.

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

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?

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

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


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

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

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

  • Result:60points,
  • Rating points-1

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

  • Result:60points,
  • Rating points-1

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

  • Result:90points,
  • Rating points8
Last comments

Python: How to Test Internet Speed

There may be no animus franchise that opens with as dull-witted and satiating a ritual as Scream. As the shaping followers’s logo appears on wall, we rather enter upon hearing the ringing of a l…
  • Andrew
  • Jan. 12, 2022, 11:41 a.m.

Qt/C++ - Lesson 038. Switching between windows in the Qt

Здравствуйте, а как сделать чтобы второе и третье окно не сохраняли свои параметры а создавались заного? Только начинаю изучать прогграмирование и пишу протенькую игру сделал 2 окна, одно с меню…
  • juvf
  • Dec. 28, 2021, 11:56 p.m.

Deploying Qt and QML Applications on Linux and Windows

написал приложение, холоворд на qt виджетах, без qml. Из визарда QtCreator. Собрал кросскомпилятором. Нужно перенести на таргет. juvf@juvf-VirtualBox:~/qtWs/test/imx6/release$ ~/CQtDeploye…

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

А есть возможность передавать координаты классу, что-бы он рисвал, допустим линию?

Django - Tutorial 036. How to add authentication through social networks. VKontakte

Добавь в setting.py строку: SOCIAL_AUTH_VK_OAUTH2_API_VERSION = '5.81'
Now discuss on the forum

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 …

Как получить ссылку на обьект присылающий сигнал через сигнал/слот?

Вот и ответ: Спасибо Александру за подсказку. void Core::onLogin(QString m_login) { Worker *m_worker = qobject_cast (sender()); hashLogin.insert(m_login, m_wor…

подтвердить значение в SpinBox

Мне необходимо подтвердить значение в SpinBox нажатием клавиши Enter и перевести фокус на другое поле. self.doubleSpinBox.returnPressed.co nnect(self.pressedKeys) def pressedKeys(sel…

Сортировка по дате и времени QSortFilterProxyModel QSqlRelationalTableModel

Добрый день. Наследуйте модель сортировки от QSortFilterProxyModel и переопределите метод QSortFilterProxyModel::lessThan таким образом, чтобы вы забирали через индексы дату и в…

Как создать класс вызывающий функции по входному числу 0-255?

Вы в любом случае упрётесь в маршрутизацию сообщения от этих цифр 0-255 до вызова конкретных методов и функций. А все эти пляски метасистемой Qt в данном случае лишь усложнение кода. Если …
© EVILEG 2015-2021
Recommend hosting TIMEWEB