Problems with Open-Source Downloads read https://www.qt.io/blog/problem-with-open-source-downloads and https://forum.qt.io/post/638946

connect signal from subclass to father's slot



  • Hi,

    I have a method in MainWindow called debug. MainWindow contains an object called inputline and into inputLine, there is a QPushbutton called sendButton.
    The question is, can I write the connection between sendButton (in the inputLine subclass) and the debug slot in MainWindow from the inputLine constructor?
    How should I write the connection?

    //in inputline subclass
    inputLine::inputLine(QWidget *parent) : QWidget(parent)
    {
        QHBoxLayout *layOut = new QHBoxLayout(this);
        sendButton.setText("Text");
        connect(&sendButton, &QPushButton::clicked,
                 parent,          //<- don't work
                ui::debug);   //<- don't work
    }
    
    //in MainWindow
    
    #include "inputline.h"
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent), ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        inputLine *iL = new inputLine(this);
    
    /*    connect(&iL->sendButton, &QPushButton::clicked,
                this, &MainWindow::debug); */ //This worked, but it's outside from object
    }
    
    
    void MainWindow::debug()
    {
       qDebug() << "Debugeando: " << iL->readInfo() << endl;
    }
    
    

    please anybody so kind to help me?

    Thanks in advance



  • @Josz Hi,

    You can redirect the signal from the button to a signal of inputLine (by the way, usually class name starts with uppercase. That's not mandatory but it's a common practice. Better to name your class InputLine):

    //in inputline.h
    class InputLine : public QWidget{ //I guess it inherits from QWidget
    ...
    signals: //replicate signal of QPushButton
        void clicked();
    ...
    }
    
    //in mainwindow.cpp
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent), ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        InputLine *iL = new InputLine(this);
    
        connect(&iL, &InputLine::clicked, this, &MainWindow::debug);
    }
    


  • @Gojir4 Thank you very much for all tips.

    Then I assume that connect inside the object is not possible, but your solution, allows me make private the variables.

    I wil try ;-)


  • Lifetime Qt Champion

    Hi,

    In addition to what @Gojir4 wrote, doing what you originally planned would quickly become a nightmare to maintain because as soon you change the "father" class, you'd have to either ensure that it contains the slot or modify the your InputLine class to match the new "father" class. Doing so you break encapsulation. For all it does InputLine shouldn't care about where the signal goes, that's not its responsibility.


Log in to reply