connect in qt using two different classes



  • I want to connect a signal and a slot from two different classes in which one is using the other like this example:

    form.hpp

    class Form : public QDialog
    {
        Q_OBJECT
    
    public:
        explicit Form();
    public slots:
         void onPushButton(void);    
    
    };
    

    form.cpp

    Form::Form() :
        QDialog(parent),
        ui(new Ui::Form)
    {
        ui->setupUi(this);
        connect(..., SIGNAL(clicked()),..., SLOT(onPushButton()));
    
    }
    
    void Form::onPushButton(void)
    {
        ui->pushButton->setText(QString("clicked"));
    }
    

    mainwindow.hpp

    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit MainWindow(QWidget *parent = 0);
        
    private:
        Ui::MainWindow *ui;
        Form f;
    };
    

    mainwindow.cpp

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    }
    

    I know it easy to solve but I don't know how to do it. What the syntax of connect in Form::Form()?
    If it was the way around I would do it like that:

    connect(&f, SIGNAL(clicked()),this, SLOT(onPushButton()));


  • @jaouad100

    You would make life a bit easier when you are introducing a bool in the parameter list of onPushButton.

    form.hpp

    class Form : public QDialog
    {
        Q_OBJECT
    
    public:
        explicit Form();
    public slots:
         void onPushButton(bool);    
    
    };
    

    form.cpp

    Form::Form() :
        QDialog(parent),
        ui(new Ui::Form)
    {
        ui->setupUi(this);
        connect(ui->PushButton, SIGNAL(clicked( bool ) ), this, SLOT(onPushButton ( bool )));  // assumes name of QPushButton is PushButton
      // connect(ui->PushButton, &QPushButton::clicked, this, &Form::onPushButton );
    }
    

    The alternative connect requires exact the same parameter lists. It give you already a compile error.

    The first version would allow to have different parameter lists, but for starting it ios easier to understand when you keep them the same.


Log in to reply