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
{
    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.

ADS

#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.
Support the author Donate
AK

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

Comments

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

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting
s

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

  • Result:42points,
  • Rating points-8
e
  • enfant
  • Oct. 14, 2021, 2:59 p.m.

C++ - Test 002. Constants

  • Result:75points,
  • Rating points2
e
  • enfant
  • Oct. 14, 2021, 2:54 p.m.

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

  • Result:93points,
  • Rating points8
Popular publications in the last 90 Days
Last comments
s

Qt/C++ - Lesson 060. Configuring the appearance of the application in runtime

Добрый вечер, на "лету" не работает, только перезапуск
s

Qt/C++ - Lesson 060. Configuring the appearance of the application in runtime

Спасибо, завтра опробую и отпишусь по результату

Django - Tutorial 007. Adding Pagination based on django-bootstrap3

Просто список каких-нибудь объектов передавайте, который дёрнули ищ api стороннего сервера from django.core.paginator import Paginatorobjects = ['john', 'paul', 'george', 'ringo']p = Pagina…
b

PyQt5 - Tutorial 009. Using QThread with MoveToThread

Спасибо большое

PyQt5 - Tutorial 009. Using QThread with MoveToThread

Вызвать либо метод quit() либо эквивалентный его вариант - метод exit(0)
Now discuss on the forum
  • Nomad
  • Oct. 15, 2021, 6:39 a.m.

Вопрос из раздела "как реализовать"

Всем привет. Есть бизнес логика которую надо реализовать на джанге, она состоит в следующем: надо реализовать функционал регистрации/авторизации компаний у которого есть свой дашборд …

Проблема с созданием файлов перевода для составного проекта

Я имею ввиду, если у вас был старые ts файлы, то написать парсер, который составил бы словарь переводов. Например. "Hello world" - "Привет мир" "Hello dev" - "Привет dev" и…
k

QPsql Компиляция драйвера

при компиляции драйвера из окна Qt 5.15.2 (MSVC2019 64 ) надо было запустить C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Auxiliary\Build\vcvars64.bat тогда компиляция вып…
P
  • Pisych
  • Oct. 12, 2021, 10:59 p.m.

Фильтр в Select формы Django

Добрый день! Подскажите, как можно сделать? Есть форма, связанная с моделью. В форме Select, выбор типа документа (Приход, Расход,Списание). Этот Select берет данные из таблицы типов документов.…

Вызов функции Python с Qml

Чтобы onResult в QML подключилось к чему-то в Python, нужно чтобы result было сигналом, а у вас это слот. В качестве сигнала определено takeFunc и в данном случае в QML должно ра…
About
Services
© EVILEG 2015-2021
Recommend hosting TIMEWEB