Evgenii Legotckoi
Evgenii LegotckoiNov. 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
{
    Q_OBJECT
public:
    explicit TestClass(QObject *parent = nullptr);

signals:
    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
{
    Q_OBJECT

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

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

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

Do you like it? Share on social networks!

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

Comments

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

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

  • Result:50points,
  • Rating points-4
m

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

  • Result:80points,
  • Rating points4
m

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

  • Result:20points,
  • Rating points-10
Last comments
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 2:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 8:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 3:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 6:04 a.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 3:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 9:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks