码迷,mamicode.com
首页 > 其他好文 > 详细

4.自定义信号槽

时间:2018-07-17 23:19:32      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:exec   public   turn   .exe   color   pos   col   ade   bean   

具体实现一个自定义newspaper,reader的信号槽
//!!! Qt5
#include <QObject>
 
////////// newspaper.h
class Newspaper : public QObject
{
    Q_OBJECT
public:
    Newspaper(const QString & name) :
        m_name(name)
    {
    }
 
    void send()
    {
        emit newPaper(m_name);
    }
 
signals:
    void newPaper(const QString &name);
 
private:
    QString m_name;
};
 
////////// reader.h
#include <QObject>
#include <QDebug>
 
class Reader : public QObject
{
    Q_OBJECT
public:
    Reader() {}
 
    void receiveNewspaper(const QString & name)
    {
        qDebug() << "Receives Newspaper: " << name;
    }
};
 
////////// main.cpp
#include <QCoreApplication>
 
#include "newspaper.h"
#include "reader.h"
 
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
 
    Newspaper newspaper("Newspaper A");
    Reader reader;
    QObject::connect(&newspaper, &Newspaper::newPaper,
                     &reader,    &Reader::receiveNewspaper);
    newspaper.send();
 
    return app.exec();
}
1
//!!! Qt5
2
#include <QObject>
3
 
4
////////// newspaper.h
5
class Newspaper : public QObject
6
{
7
    Q_OBJECT
8
public:
9
    Newspaper(const QString & name) :
10
        m_name(name)
11
    {
12
    }
13
 
14
    void send()
15
    {
16
        emit newPaper(m_name);
17
    }
18
 
19
signals:
20
    void newPaper(const QString &name);
21
 
22
private:
23
    QString m_name;
24
};
25
 
26
////////// reader.h
27
#include <QObject>
28
#include <QDebug>
29
 
30
class Reader : public QObject
31
{
32
    Q_OBJECT
33
public:
34
    Reader() {}
35
 
36
    void receiveNewspaper(const QString & name)
37
    {
38
        qDebug() << "Receives Newspaper: " << name;
39
    }
40
};
41
 
42
////////// main.cpp
43
#include <QCoreApplication>
44
 
45
#include "newspaper.h"
46
#include "reader.h"
47
 
48
int main(int argc, char *argv[])
49
{
50
    QCoreApplication app(argc, argv);
51
 
52
    Newspaper newspaper("Newspaper A");
53
    Reader reader;
54
    QObject::connect(&newspaper, &Newspaper::newPaper,
55
                     &reader,    &Reader::receiveNewspaper);
56
    newspaper.send();
57
 
58
    return app.exec();
59
}
技术分享图片

自定义信号槽需要注意的事项:

  • 发送者和接收者都需要是QObject的子类(当然,槽函数是全局函数、Lambda 表达式等无需接收者的时候除外);
  • 使用 signals 标记信号函数,信号是一个函数声明,返回 void,不需要实现函数代码;
  • 槽函数是普通的成员函数,作为成员函数,会受到 public、private、protected 的影响;
  • 使用 emit 在恰当的位置发送信号;
  • 使用QObject::connect()函数连接信号和槽。


 

4.自定义信号槽

标签:exec   public   turn   .exe   color   pos   col   ade   bean   

原文地址:https://www.cnblogs.com/LyndonMario/p/9326246.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!