简单使用,Teacher有了任务后,分派给Student,Student完成后,通知Teacher。
#ifndef CTEACHER_H
#define CTEACHER_H
#include <QObject>
class CTeacher : public QObject
{
Q_OBJECT
public:
explicit CTeacher(const QString &name,QObject *parent = 0);
void taskFromB(QString task,int idx);
signals:
void dispatchTask(QString &taskName,int ibegin,int icount);
public slots:
void taskCompleted(QString &taskName,QString &whoDid);
private:
QString _myName;
};
#endif // CTEACHER_H
#include "cteacher.h"
#include <QDebug>
CTeacher::CTeacher(const QString &name,QObject *parent) :
_myName(name),
QObject(parent)
{
}
void CTeacher::taskCompleted(QString &taskName, QString &whoDid)
{
qDebug()<<_myName<<" received message - "<<"task:"<<taskName<<" completed by "<<whoDid;
}
void CTeacher::taskFromB(QString task,int idx)
{
emit dispatchTask(task,idx,100);
}
Teacher使用taskFromB得到任务并分派给Student,并在收到Student完成的消息后打印相关信息。
#ifndef CSTUDENT_H
#define CSTUDENT_H
#include <QObject>
class CStudent : public QObject
{
Q_OBJECT
public:
explicit CStudent(const QString& name,QObject *parent = 0);
int SetFavor(int i) { _ifavor = i;return _ifavor;}
void taskDone(){emit taskCompleted(_taskName,_myName);}
signals:
void taskCompleted(QString &taskName,QString &whoDid);
public slots:
void gotTask(QString &taskName,int ibegin, int icount);
private:
QString _myName,_taskName;
int _ifavor;
};
#endif // CSTUDENT_H
#include "cstudent.h"
#include <QDebug>
CStudent::CStudent(const QString &name,QObject *parent) :
QObject(parent),
_myName(name),
_ifavor(0)
{
}
void CStudent::gotTask(QString &taskName, int ibegin, int icount)
{
if(ibegin != _ifavor)
return ;
_taskName = taskName;
qDebug()<<_myName<<" got task("<<_taskName<<" begin:"<<ibegin<<" count:"<<icount<<")";
}
Teacher分派消息后,Student在gotTask中获得任务,再调用taskDone表示任务完成。
#include <QCoreApplication>
#include "cteacher.h"
#include "cstudent.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
CTeacher kakaxi("kakaxi");
CStudent naliduo("naliduo"),sekei("sekei");
naliduo.SetFavor(1);
sekei.SetFavor(2);
QObject::connect(&kakaxi,SIGNAL(dispatchTask(QString&,int,int)),&naliduo,SLOT(gotTask(QString&,int,int)));
QObject::connect(&kakaxi,SIGNAL(dispatchTask(QString&,int,int)),&sekei,SLOT(gotTask(QString&,int,int)));
QObject::connect(&naliduo,SIGNAL(taskCompleted(QString&,QString&)),&kakaxi,SLOT(taskCompleted(QString&,QString&)));
QObject::connect(&sekei,SIGNAL(taskCompleted(QString&,QString&)),&kakaxi,SLOT(taskCompleted(QString&,QString&)));
kakaxi.taskFromB(QString("AAA"),1);
kakaxi.taskFromB(QString("BBB"),2);
sekei.taskDone();
naliduo.taskDone();
return a.exec();
}
创建一个Teacher、两个Student,并联接相应的信号与槽。Teacher的一个信号联接了两个Student,两个Student的信号联接了同一个Teacher。
只是简单演示。