简体   繁体   中英

How to send data through signal and slot?

Could someone please help how to connect signal and slot?

I've got function1 which receive in realtime data ( one value)

void function1(int,double)
{
   if(condition)
     {
     //some code
     numb3 = 100;// double numb3 received new data
     emit mySignal(numb3);
     }
}

then in other function I've got variable which should receive captured value

   void function2(int,double)
    {

     double parameter2 = numb3;
    }

I tried combinations like

Q_SIGNAL double mySignal(double newValue=0){return newValue;};
Q_SLOT double slot1(double param=0) {emit mySignal(param); };

and then in function2{
connect(customPlot,SIGNAL(mySignal()), qApp, SLOT(slot1()));
double parameter2 = slot1();}

but they are not working as I would like to.

Thanks in advance!

Define your custom signal in the header of the class that emits the signal:

signals:
       void   signalName(paramType1,paramType2...);

Define your slot to receive the signal in the class that will receive it:

public slots:
      void   slotName(paramType1,paramType2...) ; // Should be THE SAME parameter types

Now connect inside the cpp where you want to start connecting both:

connect(classObjectWhereTheSignalIs, SIGNAL(signalName(paramType1,paramType2)),classObjectWhereTheSlotIs,SLOT(slotName(paramType1,paramType2)));

And now you emit a signal like this, whenever you want:

emit (signalName(paramOfTypeParamType1, paramOfTypeParamType2...));

Cheers.

you should define your signal like this in header.

Q_SIGNAL:

void mySignal(int);

your slot will look like below in header file.

Q_SLOT:

void mySlot(int val);

Now in cpp file you can connect signal to slot like below.

connect(signalObject, SIGNAL(mySignal(int)),slotObject,SLOT(mySlot(int)));

You're mixing C++ 'return' and Qt signal/slot. Typically, signals and slots have return type void. Also, signal's body is generated by MOC, so you usually just declare it.

Like this:

#include <QObject>
#include <QDebug>

class CustomPlot: QObject {
    Q_OBJECT

public:
    void bla() {
        emit doSomething(3.1415926535);
    }

signals:
    void doSomething(double value);
};

class EventHandler: QObject {
    Q_OBJECT

public slots:
    void onDoSomething(double value) {
        qDebug() << "we are called with value =" << value;
    }

};

//in main:

CustomPlot plot;
EventHandler handler;

QObject::connect(&plot, &CustomPlot::doSomething, &handler, &EventHandler::onDoSomething);

plot.bla();  // in QtCreator's 'Application Output' panel you'll see:
             //we are called with value = 3.1415926535

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM