QT的信号和槽函数的使用(一)

一,信号的使用

语法:

参数解释:

  1. sender:发出信号的对象
  2. signal:发送对象发出的信号
  3. receiver:接收信号的对象
  4. slot:接收对象在接收到信号之后所需要调用的函数(槽函数)
    自带信号的槽函数的使用案例
  //第一个参数是:按键   第二参数是:处理的点击事件,
    //第三个参数接收到事件的处理的人
    //第四个参数处理事件
    connect(ui->pushButton, &QPushButton::clicked, this, &QMainWindow::close);

QT的信号和槽函数的使用(一)_第1张图片

二,自定义的信号处理事件

1. newspaper.h头文件

#ifndef NEWSPAPER_H
#define NEWSPAPER_H

#include 

class NewsPaper : public QObject
{
    Q_OBJECT
public:
    explicit NewsPaper(QObject *parent = 0);

    //发送信令
    void sendSignal3();

signals:
    //信令操作
    void hasNewsPaper();
    void hasNewsPaper(QString name);


public slots:
};

#endif // NEWSPAPER_H

2.newspaper.cpp实现

#include "newspaper.h"

NewsPaper::NewsPaper(QObject *parent) : QObject(parent)
{

}

void NewsPaper::sendSignal3()
{
    //发送自定义信令
    emit hasNewsPaper();
     emit hasNewsPaper("sdlkfj");
}

3.Reader.h头文件

#ifndef READER_H
#define READER_H

#include 

class Reader : public QObject
{
    Q_OBJECT
public:
    explicit Reader(QObject *parent = 0);

    //信令处理函数, 槽函数
    void buyNewsPaper3();
    void buyNewsPaper3(QString name);

signals:

public slots:
};

#endif // READER_H

4.实现

#include "reader.h"
#include <QDebug>
Reader::Reader(QObject *parent) : QObject(parent)
{

}

void Reader::buyNewsPaper3()
{

    qDebug() << "songli" ;
}

void Reader::buyNewsPaper3(QString name)
{

    qDebug() << "songli name :" << name  ;
}

测试:

#include "mywidget.h"
#include "ui_mywidget.h"
#include "newspaper.h"
#include "reader.h"

MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyWidget)
{
    ui->setupUi(this);

    NewsPaper* newsPaper = new NewsPaper(this);

    Reader* reader = new Reader(this);

    connect(ui->pushButton, &QPushButton::clicked, newsPaper, &NewsPaper::sendSignal3);

    void(NewsPaper::*myfunc)(QString) = &NewsPaper::hasNewsPaper;
    void(Reader::*myRead)(QString) = &Reader::buyNewsPaper3;

    connect(newsPaper, myfunc, reader, myRead);


}

MyWidget::~MyWidget()
{
    delete ui;
}

QT的信号和槽函数的使用(一)_第2张图片

三,总结

QT的信令就是IOC控制反转的实现

Created with Raphaël 2.1.0 点击事件的通知 点击事件的通知 处理事件的的人 处理事件的的人 点击事件(是否点击)

你可能感兴趣的:(Qt)