Qt信号与槽 如何写2个类,一个发送信号,一个接收并处理

题目:

假设要做2个类,一个类的值提供一个函数SetValue,当这个值发生变化时,假设>10就触发告警调用B的函数;

 

-------------------------------------------

a.h

 

#pragma once
#include <QOBJECT>

class CA:public QObject
{
    Q_OBJECT
public:
    CA() {}
    ~CA() {}

    void DoSetValue(int c)
    {
        //qDebug() << "class a do set value and it will emit class to do b\r\n";
        printf("class a do set value and it will emit class to do b\r\n");
        printf("before emit onvaluechange\r\n");
        emit __OnAlarm(c);
        printf("after emit onvaluechange\r\n");
    }

signals:
    void __OnAlarm(int c);
};

  

b.h

#pragma once
#include <qobject.h>

class CB:public QObject
{
    Q_OBJECT
public:
    CB() {}
    ~CB() {}

    public slots:
    void OnAlarm(int c) 
    {
        printf("on value change on class b %d \r\n", c);
    }

};

  

#include <QtCore/QCoreApplication>


#include "CA.h"
#include "CB.h"
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    CA a;
    CB b;


    QObject::connect(&a, SIGNAL(__OnAlarm(int)), &b, SLOT(OnAlarm(int)));

    a.DoSetValue(100);



    return app.exec();
}

  

 如果对告警的处理有多个处理函数,多个处理类,那么可以做多个B,cb1, cb2,cb3.....然后全部链接再一起即可单个处理。

posted @ 2018-08-13 17:27  吉瓦吴老师  阅读(7955)  评论(0编辑  收藏  举报