Qt笔记:信号和槽(二)

这篇博客是上篇信号和槽的补充,想了解信号和槽概念的同学可以看看信号和槽(一)

信号和槽连接方式

一对一


一对一主要有两种方式:一个信号连接一个槽,一个信号连接一个信号
在这里插入图片描述
修改窗口标题1
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

一对多

一个信号连接多个槽

在这里插入图片描述
在这里插入图片描述
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/e7cc31e8ea704819a941f990d3ecc085.png

多对一

多个信号连接一个槽

在这里插入图片描述

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->pushButton->resize(200,100);

    connect(ui->pushButton, &QPushButton::clicked, this, &Widget::Slot_1);
    connect(ui->pushButton, &QPushButton::clicked, this, &Widget::Slot_2);
    connect(ui->pushButton, &QPushButton::clicked, this, &Widget::on_pushButton_clicked);
}

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

void Widget::Slot_1()
{
    qDebug() << "Slot_1";
}

void Widget::Slot_2()
{
    qDebug() << "slot_2";
}

void Widget::on_pushButton_clicked()
{
    this->close();
}

使用Lambda表达式定义槽

lambda语法是C++11中引入的。Qt5及其更高版本,默认就是C++11来编译的.
如果使用Qt4或者更早的版本,就需要手动在.pro文件中加上C++11的编译选项 CONFIG += C++11
在这里插入图片描述

#include "widget.h"
#include "ui_widget.h"

#include <QPushButton>

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

    QPushButton* but = new QPushButton("关闭", this);

    connect(but, &QPushButton::clicked, this, [=](){this->close();});
}

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

当 “connect” 函数第三个参数为 “this” 时,第四个参数使⽤ Lambda表达式时,可以省略掉"this"

connect(but, &QPushButton::clicked, [=](){this->close();});

断开连接

使用disconnect即可断开
用法和connect一致,一般使用disconnect断开连接是为了重新连接

在这里插入图片描述
在这里插入图片描述

小结


信号和槽的优缺点
优点:低耦合。信号的发送者不需要知道发送的信号被哪个对象的槽函数接收。槽函数也不需要知道谁发送的信号
缺点:效率低。与回调函数相比,因为信号和槽提供了更高灵活性,信号和槽效率会比直接调用效率低些

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值