Qt notebook

Qt5 - 3. 自定义信号&槽

2019-05-25  本文已影响0人  QWERDF007

信号&槽是 Qt 的核心特性之一,Qt 允许我们自定义信号&槽,因此我们可以在 Qt 程序中定义我们自己的信号&槽。要使用信号&槽,必须继承 QObject,并且必须在类定义添加宏 Q_OBJECT,这个宏提供很多操作,具体待查。

使用 Qt 的信号&槽完成观察者模式,实现报纸与订阅者,实现一个 NewspaperSubscriber 类,Subscriber 订阅 Newspaper,当 Newspaper 出现新内容时通知 Subscriber

newspaperandsubscriber.h

#ifndef NEWSPAPERANDSUBSCRIBER_H
#define NEWSPAPERANDSUBSCRIBER_H

#include <QObject>

class Newspaper : public QObject
{
    Q_OBJECT
public:
    explicit Newspaper(const QString &name);
    void send(const QString &content);

signals:
    void NewContent(const QString &content);

public slots:

private:
    QString newspaper_name_;
};

class Subscriber : public QObject
{
    Q_OBJECT
public:
    explicit Subscriber();
    void ReceiveNewspaper(const QString &name);

signals:

public slots:
};

#endif // NEWSPAPERANDSUBSCRIBER_H

newspaperandsubscriber.cpp

#include "newspaperandsubscriber.h"
#include <QDebug>

Newspaper::Newspaper(const QString &name) : newspaper_name_(name)
{

}

void Newspaper::send(const QString &content)
{
    emit NewContent(newspaper_name_ + ": " + content);
}


Subscriber::Subscriber()
{

}

void Subscriber::ReceiveNewspaper(const QString &name)
{
    qDebug() << "Receive newspaper:" << name;
}

main.cpp

#include <QCoreApplication>
#include "newspaperandsubscriber.h"

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

    Newspaper newspaper1("paper1");
    Newspaper newspaper2("paper2");
    Subscriber subscriber;
    QObject::connect(&newspaper1, &Newspaper::NewContent, &subscriber, &Subscriber::ReceiveNewspaper);
    QObject::connect(&newspaper2, &Newspaper::NewContent, &subscriber, &Subscriber::ReceiveNewspaper);
    newspaper1.send("??");
    newspaper2.send("...");
    newspaper1.send("what?");

    return a.exec();
}

效果:

result.png
上一篇下一篇

猜你喜欢

热点阅读