Evgenii Legotckoi
Nov. 9, 2017, 1:22 p.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.

  1. #include <QObject>
  2.  
  3. class TestClass : public QObject
  4. {
  5. Q_OBJECT
  6. public:
  7. explicit TestClass(QObject *parent = nullptr);
  8.  
  9. signals:
  10. void testSignal(int arg1);
  11. void testSignal(int arg1, int arg2);
  12. };

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.


  1. #include <QWidget>
  2. #include "testclass.h"
  3.  
  4. namespace Ui {
  5. class Widget;
  6. }
  7.  
  8. class Widget : public QWidget
  9. {
  10. Q_OBJECT
  11.  
  12. public:
  13. explicit Widget(QWidget *parent = 0);
  14. ~Widget();
  15.  
  16. private slots:
  17. void onTestSlot(int arg1);
  18. void onTestSlot(int arg1, int arg2);
  19.  
  20. private:
  21. Ui::Widget *ui;
  22. TestClass* m_testClass;
  23. };

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.

  1. connect(m_testClass, SIGNAL(testSignal(int,int)), this, SLOT(onTestSlot(int,int)));
  2. 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.

  1. connect(m_testClass, static_cast<void(TestClass::*)(int)>(&TestClass::testSignal),
  2. this, static_cast<void(Widget::*)(int)>(&Widget::onTestSlot));
  3. connect(m_testClass, static_cast<void(TestClass::*)(int, int)>(&TestClass::testSignal),
  4. 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.

  1. connect(m_testClass, static_cast<void(TestClass::*)(int, int)>(&TestClass::testSignal),
  2. 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?

Do you like it? Share on social networks!

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html