08黑马QT笔记之Lambda表达式
前提:使用前需要在项目文件加上"CONFIG +=C++11 "。
1 Lambda表达式: C++11的新特性,实质是匿名函数对象,可以减少槽函数的书写。
2 Lambda表达式的说明:
1)[]用于传参。
2)()与普通函数一样里面可以带参数, 例如clicked信号带有一个默认值的参数checked=false,在Lambda表达式接收并显示,即通过信号传参。
3[]里面的使用:
1)"=":将外部的局部变量、类中的所有成员都以值传递(拷贝)方式传进 (最常用)。
2)“this” :类中所有成员以值传递方式传进。
3)"&":引用符号,把外部所有局部变量以引用传进,当出现malloc、new空间时,容易导致内存问题。例如a=1传进,输出变a=未知(最好别用)。
4)也可以传单个变量。例如b1{}。
5)以上传进的所有变量都是只读方式,要想改变需要在括号与花括号中间加上"mutable"。
4 例子: 按下按钮,按钮内容变成Hello,通过信号传参并打印该参数。
5 代码实现:
1)项目文件:
#-------------------------------------------------
#
# Project created by QtCreator 2020-04-22T20:41:16
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = 02_Lambda
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += main.cpp\
mywidget.cpp
HEADERS += mywidget.h
CONFIG +=C++11 #lambda表达式
2)头文件:
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
class MyWidget : public QWidget
{
Q_OBJECT
public:
MyWidget(QWidget *parent = 0);
~MyWidget();
};
#endif // MYWIDGET_H
3).cpp文件:
#include "mywidget.h"
#include<QPushButton>
#include<QDebug>
MyWidget::MyWidget(QWidget *parent)
: QWidget(parent)
{
QPushButton *b1=new QPushButton(this);
b1->setText("Lambda");
b1->move(250,250);
resize(500,500);
int a=10,b=20;
connect(b1,&QPushButton::clicked,
/*1Lambda表达式:C++11的新特性 实质是匿名函数对象 可以减少槽函数的书写
*2Lambda表达式的说明:
* 1)[]用于传参
* 2)()与普通函数一样里面可以带参数 例如clicked信号带有一个默认值的参数checked=false 在Lambda表达式接收并显示 即通过信号传参
*3[]里面的使用:
* 1)"=":将外部的局部变量、类中的所有成员都以值传递(拷贝)方式传进 (最常用)
* 2)"this" :类中所有成员以值传递方式传进
* 3)"&":引用符号 把外部所有局部变量以引用传进 当出现malloc、new空间时 容易导致内存问题例如a=1 输出变成a=12345(最好别用)
* 4)也可以传单个变量 例如[b1](){}
* 5)以上传进的所有变量都是只读方式 要想改变需要在括号与花括号中间加上"mutable"
*/
[=](bool isChecked) //mutable
{
b1->setText("Hello");
qDebug()<<a<<b;
qDebug()<<isChecked;
//qDebug()<<a<<b; 用于测引用符号&
//a=100; 用于测是否只读
}
);
}
MyWidget::~MyWidget()
{
}
4)主函数:
#include "mywidget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyWidget w;
w.show();
return a.exec();
}