自定义信号和槽

//signals_slots.h

#ifndef _SIGNALS_SLOTS_
#define _SIGNALS_SLOTS_
#include <QObject>


class Sender : public QObject
{
public:
void dosend();
Q_OBJECT
signals:
void send(int);

};

class Mediator : public QObject
{
Q_OBJECT
signals:
void mediate(int);

};

class Receiver : public QObject
{
Q_OBJECT

public slots:
void recv(int);
};


#endif

//signals_slots.cpp

#include <QtDebug>
#include <QtCore>


#include "signals_slots.h"

void Sender :: dosend()
{
emit send(40);
}

void Receiver :: recv(int n)
{
qDebug()<<"recv number: "<<n<<endl;
}

int main(int argc, char* argv[])
{
QCoreApplication app(argc, argv);
Sender s;
Receiver r;
Mediator m;

QObject::connect(&s,SIGNAL(send(int)),&r,SLOT(recv(int)));
QObject::connect(&s,SIGNAL(send(int)),&m,SIGNAL(mediate(int)));
QObject::connect(&m,SIGNAL(mediate(int)),&r,SLOT(recv(int)));

s.dosend();

return 0;
}

Leave a Reply

Your email address will not be published.