Search code examples
c++qtsignalssignals-slotsslots

How to connect two different objects


I have two objects, one will hold the graph, and the other a few buttons. How to use (connect) so that when you press button 1, the inscription is displayed in debag or the schedule is filled with a new one?

For example, I press the button created by the class BtnBox and my graph is displayed. How to use connect()?

main.cpp

#include "mainwindow.h"
#include <QApplication>
#include <QThread>
#include "btnbox.h"
#include "plot.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    BtnBox *panel = new BtnBox(&a);
    Plot *plot = new Plot();

    QObject::connect(panel, SIGNAL(clickedBtn1()), plot, SLOT(slotPrinter()));
//    panel->show();

    QHBoxLayout *mainLayout = new QHBoxLayout;
    mainLayout->addWidget(plot);
    mainLayout->addWidget(panel);

    QWidget window;

    window.setLayout(mainLayout);
    window.show();

    return a.exec();
}

Solution

  • Maybe you can use the QPushButton::clicked signal and write something like this:

    connect(ui->pushButtonObj, &QPushButton::clicked, plot, &Plot::slotPrinter);
    

    But if you want a custom behavior with your class BtnBox you can create on header file of BtnBox a signal.

    signals:
        void clickedBtn1();
    

    And use: emit clickedBtn1(); whenever you want to emit it, your connect should work.

    There is no need for implementation of the signal, you just have to emit it.

    The emit keyword is not really necessary, if you want you can simply use clickedBtn();