Evgenii Legotckoi
April 26, 2018, 4:39 p.m.

Qt/C++ Tutorial 078. Do not mix the old syntax of signals and slots on SIGNAL SLOT macros with new syntax on pointers

We all know that in Qt there are two syntaxes of signals and slots:

But also, as it is not necessary to interfere with beer with vodka, with the same success it is not necessary to mix two syntaxes within the framework of one project.

Of course, there are projects that write a lot of code and make a complete refactoring on changing the whole syntax is quite an overhead job, but if you, gradually completing the project, switch to a new syntax, try to update all the code places with the given one connection to a new syntax.

The fact is that for both cases ( SINGAL SLOT macros and syntax on pointers ) other contents of moc files are formed, which leads to the fact that mixed usage of connect and disconnect methods does not work as expected. And to be precise, the disconnect method will not work if connect was called using macros, and disconnect was called using pointers.


Example

We will create a trial project in which there will be a window and one button. Add a slot in the window. And in the window class designer, let's check the four combinations of connecting the button signal to the window slot:

  1. connect SIGNAL SLOT - disconnect SIGNAL SLOT
  2. connect SIGNAL SLOT - disconnect on pointers
  3. connect on pointers - disconnect on pointers
  4. connect on pointers - disconnect SIGNAL SLOT

widget.h

  1. #ifndef WIDGET_H
  2. #define WIDGET_H
  3.  
  4. #include <QWidget>
  5.  
  6. namespace Ui {
  7. class Widget;
  8. }
  9.  
  10. class Widget : public QWidget
  11. {
  12. Q_OBJECT
  13.  
  14. public:
  15. explicit Widget(QWidget *parent = 0);
  16. ~Widget();
  17.  
  18. public slots:
  19. void checkSlot() {} // Slot for checking
  20.  
  21. private:
  22. Ui::Widget *ui;
  23. };
  24.  
  25. #endif // WIDGET_H

widget.cpp

  1. #include "widget.h"
  2. #include "ui_widget.h"
  3.  
  4. #include <QDebug>
  5.  
  6. Widget::Widget(QWidget *parent) :
  7. QWidget(parent),
  8. ui(new Ui::Widget)
  9. {
  10. ui->setupUi(this);
  11.  
  12. qDebug() << "First test";
  13. qDebug() << connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(checkSlot()));
  14. qDebug() << disconnect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(checkSlot()));
  15.  
  16. qDebug() << "Second test";
  17. qDebug() << connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(checkSlot()));
  18. qDebug() << disconnect(ui->pushButton, &QPushButton::clicked, this, &Widget::checkSlot);
  19.  
  20. qDebug() << "Third test";
  21. qDebug() << connect(ui->pushButton,&QPushButton::clicked, this, &Widget::checkSlot);
  22. qDebug() << disconnect(ui->pushButton, &QPushButton::clicked, this, &Widget::checkSlot);
  23.  
  24. qDebug() << "Fourth test";
  25. qDebug() << connect(ui->pushButton,&QPushButton::clicked, this, &Widget::checkSlot);
  26. qDebug() << disconnect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(checkSlot()));
  27. }
  28.  
  29. Widget::~Widget()
  30. {
  31. delete ui;
  32. }

Output

  1. First test
  2. true
  3. true
  4. Second test
  5. true
  6. false
  7. Third test
  8. true
  9. true
  10. Fourth test
  11. true
  12. true

Thus, it turns out that the pair connect SINGAL SLOT - disconnect on the pointers gives the wrong result that was expected. And in fact the slot remains connected.

Therefore, beginners recommend that I pay close attention to this nuance of working with signals and slots in Qt.

Do you like it? Share on social networks!

c
  • May 3, 2018, 5:13 a.m.

Who hasn’t mixed beer with vodka! 🤢🤮

Evgenii Legotckoi
  • May 3, 2018, 1:38 p.m.

vodka + beer = strong coctail, but it is bad ))

Юрий
  • June 4, 2018, 10:41 p.m.

disconnect - обязательно делать, во всех случаях?

Evgenii Legotckoi
  • June 5, 2018, 2:03 a.m.

Если удаляете объект, то все коннекты отключаются автоматически, здесь следить не требуется.

В остальных случаях disconnect нужно делать тогда, когда Вам нужно отключить сигнал-слотовое соединение в соответствии с логикой вашей программы, то есть на ваше усмотрение.

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