Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Direct connect a built-in signal from one class to a slot on another class



  • As the subject line says, is it possible to directly connect a built-in signal from one class to a slot on another class? For instance, I created this simple qt program Qt signal and Slot program to show how to indirectly connect a built-in signal from one class to a slot on another class. The program is basically comprised of 3 classes, i.e MainWindow, DialogOne, and DialogTwo classes. In the DialogOne class, I have a comboBox resides in the groupBoxItem and gets filled by the DialogOne::init() method. Then, in both MainWindow and DialogTwo classes, I have methods (slots) to handle the value of currentIndexChanged in the comboBox of DialogOne UI through a public signal in DialogOne called indexChanged. Whenever the value of the currentIndexChanged in comboBox of DialogOne UI changes, the signal indexChanged gets emitted in the DialogOne::on_comboBox_currentIndexChanged(int index) method. This triggers both the connect functions in the MainWindow ctor to pass the index value to both the MainWindow::outputToLineEdit(int index) and DialogTwo::outputToLineEdit(int index) methods to display the result. The program compiles and runs as I expected. AFAICT, the signal indexChanged is acting like the "Man in middle" (a.k.a M-i-M). What I am trying to achieve is to get rid off the M-i-M and have the process done directly from the built-in signal in DialogOne class to the slots in both MainWindow and DialogTwo class. Is this doable and how?



  • @Habibie
    You do not have to do "man-in-the-middle" provided you have somewhere in your code which can see the signalling object+signal and the slot object+slot. This might be in the slot class, or it might be in some other class (e.g. main window) so long as that is allowed to see (via #include) the signals/slots and the instances to connect.

    In your case (I haven't examined the code) if MainWindow can see both DialogOne and DialogTwo instances it can do both connects as required. Or whatever similar solution.

    Sometimes it is true that it is too inconvenient for one place to be able to see both instances, and it turns out (for separation of code) that it is better to do some signalling via "relays". Depends on the case, and how you want to write/separate your code.


  • Lifetime Qt Champion

    Hi

    void DialogOne::on_comboBox_currentIndexChanged(int index)
    {
        emit(indexChanged(index));
    }
    

    This is not needed if you just want to forward the signals.
    You can actually do signal-to-signal connections so
    you don't have to use a slot to forward them. (still need a public signal for it )

    You simply connect internal widget signal to public signal.

    This is a better design than allowing direct access to the inner widgets from another class to
    be able to get signals from the Widgets.



  • @mrjj said in Direct connect a built-in signal from one class to a slot on another class:

    Hi

    void DialogOne::on_comboBox_currentIndexChanged(int index)
    {
        emit(indexChanged(index));
    }
    

    This is not needed if you just want to forward the signals.
    You can actually do signal-to-signal connections so
    you don't have to use a slot to forward them. (still need a public signal for it )

    You simply connect internal widget signal to public signal.

    This is a better design than allowing direct access to the inner widgets from another class to
    be able to get signals from the Widgets.

    Thank you for your quick response. TBH, I have no idea how to do this, i.e. I'm sort of a newbie with qt programming. I was hoping you could provide to show some code here how to implement this.


  • Lifetime Qt Champion

    @Habibie said in Direct connect a built-in signal from one class to a slot on another class:

    I have no idea how to do this

    First read https://doc.qt.io/qt-5/signalsandslots.html
    "I was hoping you could provide to show some code here how to implement this" - it is better to learn things instead of asking others to write the code.
    In the link above you will see how to connect signals and slots, you connect signals with other signals in the same way.


  • Banned

    This post is deleted!


  • @jsulm said in Direct connect a built-in signal from one class to a slot on another class:

    it is better to learn things instead of asking others to write the code.

    Got it!

    In the link above you will see how to connect signals and slots, you connect signals with other signals in the same way.

    Got that too.

    Anyway, I just got sometimes to explore more on this subject and so far it looks like I finally managed to get it working by means of connecting the built-in signal to an external signal (see my code here). All I did was to add another connection in the DialogOne class constructor as shown below:

    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(indexChanged(int)));
    

    Being a newbie in SIGNAL/SLOT, I honestly don't know if this is the correct way. Regardless, if anyone out here knows a better way, I am definitely all ears. Thank you.



  • @Habibie
    This looks reasonable. You are indeed allowed to chain one signal onto another, as you have done.

    If you are a newbie: do yourself a favour, drop your SIGNAL/SLOT macros, change over to New Signal Slot Syntax. That will give you edit-time autocomplete on picking signals/slots, compile-time errors on wrong connections and will allow you to use lambdas in due course for more powerful slots.



  • @JonB said in Direct connect a built-in signal from one class to a slot on another class:

    @Habibie
    This looks reasonable. You are indeed allowed to chain one signal onto another, as you have done.

    Reasonable could mean there can be some improvements, am I right? If so, I sure don't mind to learn more about the improvement if you and/or anyone is willing to help.

    If you are a newbie: do yourself a favour, drop your SIGNAL/SLOT macros, change over to New Signal Slot Syntax. That will give you edit-time autocomplete on picking signals/slots, compile-time errors on wrong connections and will allow you to use lambdas in due course for more powerful slots.

    I am not sure what exactly did you mean. Did you mean the commented SIGNAL/SLOT macros I put in the constructor of src/mainwindow.cpp as shown below?

    // Using string-based QObject::connect syntax.
    //    connect(D1, SIGNAL(indexChanged(int)), this, SLOT(outputToLineEdit(int)));
    //    connect(D1, SIGNAL(indexChanged(int)), D2, SLOT(outputToLineEdit(int)));
    


  • @Habibie said in Direct connect a built-in signal from one class to a slot on another class:

    Reasonable could mean there can be some improvements, am I right?

    No, it means fine.

    I am not sure what exactly did you mean. Did you mean the commented SIGNAL/SLOT macros I put in the constructor of src/mainwindow.cpp as shown below?

    No, it referred to

    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(indexChanged(int)));

    Use new style instead of any SIGNAL or SLOT macros in connect()s.



  • @JonB said in Direct connect a built-in signal from one class to a slot on another class:

    No, it referred to

    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(indexChanged(int)));

    Use new style instead of any SIGNAL or SLOT macros in connect()s.

    I tried the following:

    connect(this, &DialogOne::ui->comboBox->currentIndexChanged, this, &DialogOne::indexChanged);
    

    and got some errors as shown below:

    ../src/dialogone.cpp: In constructor ‘DialogOne::DialogOne(QWidget*)’:
    ../src/dialogone.cpp:12:96: error: no matching function for call to ‘DialogOne::connect(DialogOne*, <unresolved overloaded function type>, DialogOne*, void (DialogOne::*)(int))’
       12 |     connect(this, &DialogOne::ui->comboBox->currentIndexChanged, this, &DialogOne::indexChanged);
    

  • Lifetime Qt Champion

    @Habibie said in Direct connect a built-in signal from one class to a slot on another class:

    and got some errors as shown below:

    And the documentation tells you why and how to circumvent it...



  • @Christian-Ehrlicher said in Direct connect a built-in signal from one class to a slot on another class:

    And the documentation tells you why and how to circumvent it...

    When I tried the suggestion in the above link, I keep getting the following error.

    g++ -c -pipe -g -std=gnu++11 -Wall -Wextra -D_REENTRANT -fPIC -DGIT_VERSION=\"\" -DGIT_HASH=\"febc5d8c3a77a4a9039601f638b0ce220c3b3189\" -DQT_QML_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I../../SignalsAndSlots-01 -I. -I../include -I/usr/include/x86_64-linux-gnu/qt5 -I/usr/include/x86_64-linux-gnu/qt5/QtWidgets -I/usr/include/x86_64-linux-gnu/qt5/QtGui -I/usr/include/x86_64-linux-gnu/qt5/QtCore -I. -I. -I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++ -o dialogone.o ../src/dialogone.cpp
    ../src/dialogone.cpp: In constructor ‘DialogOne::DialogOne(QWidget*)’:
    ../src/dialogone.cpp:13:22: error: expected primary-expression before ‘,’ token
       13 |     connect(QComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [=](int index) {
          |                      ^
    ../src/dialogone.cpp: In lambda function:
    ../src/dialogone.cpp:14:13: error: ‘class Ui::DialogOne’ has no member named ‘lineEdut’
       14 |         ui->lineEdut->setText(QString::number(index));
          |             ^~~~~~~~
    make: *** [Makefile:566: dialogone.o] Error 1
    
    • Here is (the changes in) the constructor of src/mainwindow.cpp:
    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    }
    
    • Here is (the changes in) the constructor of src/dialogone.cpp:
    #include "dialogone.h"
    #include "ui_dialogone.h"
    
    DialogOne::DialogOne(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::DialogOne)
    {
        ui->setupUi(this);
    
        init();
        connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [=](int index) {
            ui->lineEdit->setText(QString::number(index));
        });
    }
    
    
    • And, (the changes in) the constructor of src/dialogtwo.cpp
    #include "dialogtwo.h"
    #include "ui_dialogtwo.h"
    
    DialogTwo::DialogTwo(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::DialogTwo)
    {
        ui->setupUi(this);
        connect(ui->comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &DialogOne::indexChanged);
    }
    

    However, if I do the following (I don't know if this is what you really mean), it works just fine, except I am not able to connect the DialogOne::indexChange(int index) signal to the lineEdit in DialogTwo class using lambda.

    • src/mainwindow.cpp:
    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        D1 = new DialogOne(this);
        D2 = new DialogTwo(this);
    
        // Using functor-based QObject::connect syntax with lambda
        connect(D1, &DialogOne::indexChanged, this, [this](int index) {
            ui->lineEdit->setText(QString::number(index));
        });
    
       // Using functor-based QObject::connect syntax
       connect(D1, &DialogOne::indexChanged, D2, &DialogTwo::outputToLineEdit);
    }
    
    • src/dialogone.cpp:
    #include "dialogone.h"
    #include "ui_dialogone.h"
    
    DialogOne::DialogOne(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::DialogOne)
    {
        ui->setupUi(this);
    
        init();
        connect(ui->comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &DialogOne::indexChanged);
    }
    
    • src/dialogtwo.cpp:
    #include "dialogtwo.h"
    #include "ui_dialogtwo.h"
    
    DialogTwo::DialogTwo(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::DialogTwo)
    {
        ui->setupUi(this);
    }
    

  • Lifetime Qt Champion

    What Qt version/ compiler do you use? I would say an ancient one... then you should also take a look at the Qt version documentation you use. e.g. for Qt5.5: https://doc.qt.io/archives/qt-5.5/qcombobox.html#currentIndexChanged



  • @Christian-Ehrlicher said in Direct connect a built-in signal from one class to a slot on another class:

    What Qt version/ compiler do you use? I would say an ancient one... then you should also take a look at the Qt version documentation you use. e.g. for Qt5.5: https://doc.qt.io/archives/qt-5.5/qcombobox.html#currentIndexChanged

    I'm doing all of these on a 64-bit Dell Inspiron-3252 (a rather old) computer running on an uBuntu 21.04 (Hirsute) OS with Qt-5.15.2 (I think this is pretty up-to-date for Qt-5.x) and gcc-10.3.0.

    ~ qmake --version
    QMake version 3.1
    Using Qt version 5.15.2 in /usr/lib/x86_64-linux-gnu
    ~
    ~ g++ -v
    Using built-in specs.
    COLLECT_GCC=g++
    COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/10/lto-wrapper
    OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa:hsa
    OFFLOAD_TARGET_DEFAULT=1
    Target: x86_64-linux-gnu
    Configured with: ../src/configure -v --with-pkgversion='Ubuntu 10.3.0-1ubuntu1' --with-bugurl=file:///usr/share/doc/gcc-10/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-10 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-10-gDeRY6/gcc-10-10.3.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-10-gDeRY6/gcc-10-10.3.0/debian/tmp-gcn/usr,hsa --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-mutex
    Thread model: posix
    Supported LTO compression algorithms: zlib zstd
    gcc version 10.3.0 (Ubuntu 10.3.0-1ubuntu1)
    

  • Lifetime Qt Champion

    I see that you compiler error does not fit to your pasted code:

    connect(QComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),

    I don't see a variable named QComboBox in your code.



  • @Christian-Ehrlicher said in Direct connect a built-in signal from one class to a slot on another class:

    I see that you compiler error does not fit to your pasted code:

    connect(QComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),

    I don't see a variable named QComboBox in your code.

    You are right and sorry about that.

    Now, I put it exactly like the documentation link you provided and filled the dotted line with ui->lineEdit(QString::number(index)); in the constructor of DialogOne class as shown below.

    #include "dialogone.h"
    #include "ui_dialogone.h"
    
    DialogOne::DialogOne(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::DialogOne)
    {
        ui->setupUi(this);
    
        init();
        connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [=](int index){
            ui->lineEdit(QString::number(index));
        });
    }
    

    The compilation of the above code generates the following error:

    g++ -c -pipe -g -std=gnu++11 -Wall -Wextra -D_REENTRANT -fPIC -DGIT_VERSION=\"\" -DGIT_HASH=\"febc5d8c3a77a4a9039601f638b0ce220c3b3189\" -DQT_QML_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I../../SignalsAndSlots-01 -I. -I../include -I/usr/include/x86_64-linux-gnu/qt5 -I/usr/include/x86_64-linux-gnu/qt5/QtWidgets -I/usr/include/x86_64-linux-gnu/qt5/QtGui -I/usr/include/x86_64-linux-gnu/qt5/QtCore -I. -I. -I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++ -o dialogone.o ../src/dialogone.cpp
    ../src/dialogone.cpp: In constructor ‘DialogOne::DialogOne(QWidget*)’:
    ../src/dialogone.cpp:12:13: error: ‘comboBox’ was not declared in this scope; did you mean ‘QComboBox’?
       12 |     connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [=](int index){
          |             ^~~~~~~~
          |             QComboBox
    ../src/dialogone.cpp: In lambda function:
    ../src/dialogone.cpp:13:13: error: ‘class Ui::DialogOne’ has no member named ‘lineEdit’
       13 |         ui->lineEdit(QString::number(index));
          |             ^~~~~~~~
    make: *** [Makefile:566: dialogone.o] Error 1
    

  • Lifetime Qt Champion

    C++ basics missing - you don't have a member named 'comboBox' on your class - so how do you suppose that this works? I would guess your combobox is somewhere in your ui struct.



  • @Christian-Ehrlicher said in Direct connect a built-in signal from one class to a slot on another class:

    C++ basics missing - you don't have a member named 'comboBox' on your class - so how do you suppose that this works? I would guess your combobox is somewhere in your ui struct.

    Exactly.

    I ONLY have a comboBox in DialogOne class. From there, whenever there is a change in the index (currentIndexChanged), I want it to trigger the external signal indexChanged(int index) (also declared in the header file of DialogOne class). This is done through the old (string) style SIGNAL/SIGNAL connect in the constructor of DialogOne class as shown below and it works just fine.

    #include "dialogone.h"
    #include "ui_dialogone.h"
    
    DialogOne::DialogOne(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::DialogOne)
    {
        ui->setupUi(this);
    
        init();
        connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(indexChanged(int)));
    }
    

    However, since in the constructor of MainWindow, I use the new functional style connect, you suggested in one of your posts above to drop your SIGNAL/SLOT macros, change over to New Signal Slot Syntax. TBH, I was so happy and thrill to see such a suggestion mainly because I wasn't able to do it before and someone like you made such a recommendation giving me a hope, especially after I read the documentation link you suggested to read. So, now it looks like that it's not possible, is it? I am still keeping my fingers crossed to hope the answer is yes.

    The documentation link you suggested to read really gives me an impression that we can just drop the external indexChange(in index) signal (declared in the header file of DialogOne class) and use lambda to connect the built-incurrentIndexChangedsignal from thecomboBoxdirectly to the twolineEditdeclared in bothMainWindowandDialogTwo` classes. If this can be done, I am all ears.



  • @Habibie
    You say this works:

    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(indexChanged(int)));
    

    and it's inside DialogOne::DialogOne().

    Then you say you changed to

    connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [=](int index){
    

    still inside DialogOne::DialogOne().

    The compiler says

    ../src/dialogone.cpp:12:13: error: ‘comboBox’ was not declared in this scope

    Why have you changed from ui->comboBox to comboBox?



  • @JonB said in Direct connect a built-in signal from one class to a slot on another class:

    @Habibie
    You say this works:

    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(indexChanged(int)));
    

    and it's inside DialogOne::DialogOne().

    The above uses the old string SIGNAL/SIGNAL connection style.

    Then you say you changed to

    connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [=](int index){
    

    still inside DialogOne::DialogOne().

    The compiler says

    ../src/dialogone.cpp:12:13: error: ‘comboBox’ was not declared in this scope

    Why have you changed from ui->comboBox to comboBox?

    The above uses a new functional connection with lambda.

    BTW, with an old style string SIGNAL/SIGNAL connection, if I change from this

        connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(indexChanged(int)));
    

    to this

        connect(comboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(indexChanged(int)));
    

    the compilation spits out the following error messages.

    g++ -c -pipe -g -std=gnu++11 -Wall -Wextra -D_REENTRANT -fPIC -DGIT_VERSION=\"\" -DGIT_HASH=\"febc5d8c3a77a4a9039601f638b0ce220c3b3189\" -DQT_QML_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I../../SignalsAndSlots-01 -I. -I../include -I/usr/include/x86_64-linux-gnu/qt5 -I/usr/include/x86_64-linux-gnu/qt5/QtWidgets -I/usr/include/x86_64-linux-gnu/qt5/QtGui -I/usr/include/x86_64-linux-gnu/qt5/QtCore -I. -I. -I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++ -o dialogone.o ../src/dialogone.cpp
    ../src/dialogone.cpp: In constructor ‘DialogOne::DialogOne(QWidget*)’:
    ../src/dialogone.cpp:12:13: error: ‘comboBox’ was not declared in this scope; did you mean ‘QComboBox’?
       12 |     connect(comboBox, SIGNAL(currentIndexChanged(int)), this, SIGNAL(indexChanged(int)));
          |             ^~~~~~~~
          |             QComboBox
    make: *** [Makefile:566: dialogone.o] Error 1
    

  • Lifetime Qt Champion

    Hi,

    That's exactly the point of @JonB, there's no reason to remove the ui-> from your code.



  • @SGaist said in Direct connect a built-in signal from one class to a slot on another class:

    Hi,

    That's exactly the point of @JonB, there's no reason to remove the ui-> from your code.

    Got it and thank you for pointing it out.


Log in to reply