connect(信号发送者,发送的信号,信号接收者,信号的处理);
信号函数和槽函数的参数必须是一样的,但信号的参数可以多余槽函数的参数(前面的参数类型必须一致)
是控件和控件间的信号传递,这两个之间没有关联,松散耦合
两个连接意义相同,用父类的(发送的信号,或信号的处理(要地址))或自己类名都可以
//自定义类MyButton 继承QPushButton
MyButton *but=new MyButton;
but->setText("hhh");
but->setParent(this);
connect(but,&MyButton::clicked,this,&MainWindow::close);
connect(but,&QPushButton::clicked,this,&QMainWindow::close);
自定义信号和槽
自定义信号://不用在.cpp里实现faSingnals();
.h
class fasong : public QObject
{
Q_OBJECT
public:
explicit fasong(QObject *parent = nullptr);
signals:
//自定义信号
//没有返回值的只需要声明不需要实现,可以有参数可以重载
//信号函数
void faSingnals();
void faSingnals(QString string);
};
自定义槽:
.h
class jieshou : public QObject
{
Q_OBJECT
public:
explicit jieshou(QObject *parent = nullptr);
signals:
public slots:
//槽函数
//返回void 需要声明和实现,可以有参数可以重载
//槽函数
void shouSlots();
void shouSlots(QString string);
};
//需要在.cpp里实现shouSlots()函数;
#include "jieshou.h"
#include <QtDebug>
jieshou::jieshou(QObject *parent) : QObject(parent)
{
}
void jieshou::shouSlots()
{
qDebug()<<"你好";
}
void jieshou::shouSlots(QString string)
{
//先toUtf8()转成ByteArray在.data()转成char*()
//输出的字符串不带引号
qDebug()<<string.toUtf8().data();
}
可以理解为这里的主函数:调用信号和槽
.h
#include"fasong.h"
#include"jieshou.h"
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
///触发信号
void chuFa();
///信号对象
fasong *fa;
///槽对象
jieshou *shou;
};
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPushButton>
#include "MyButton.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//发送者对象
this->fa=new fasong(this);
//接收者对象
this->shou=new jieshou(this);
//连接信号与槽
//connect(fa,&fasong::faSingnals,shou,&jieshou::shouSlots);
//信号与槽有重载时的连接方法
//函数指针指向函数地址
void(fasong:: *faSongDiZhi)(QString)=&fasong::faSingnals;
void(jieshou:: *jieshouDiZhi)(QString)=&jieshou::shouSlots;
//连接信号与槽(有参)
connect(fa,faSongDiZhi,shou,jieshouDiZhi);
//实现点击按钮触发 触发信号
QPushButton *button=new QPushButton;
button->setParent(this);
button->setText("Button1");
//绑定按钮点击触发触发信号
connect(button,&QPushButton::clicked,this,&MainWindow::chuFa);
void(fasong:: *faSongDiZhi1)(void)=&fasong::faSingnals;
void(jieshou:: *jieshouDiZhi1)(void)=&jieshou::shouSlots;
//信号连接信号
connect(button,&QPushButton::clicked,fa,faSongDiZhi1);
//发送和接收连接(无参)信号和槽连接
connect(fa,faSongDiZhi1,shou,jieshouDiZhi1);
//断开信号,怎么连接就怎么断开
disconnect(button,&QPushButton::clicked,fa,faSongDiZhi1);
chuFa();
}
///触发信号
void MainWindow::chuFa()
{
//emit触发关键字,faSingnals为信号函数
//emit fa->faSingnals();
emit fa->faSingnals("哈哈哈");
}
MainWindow::~MainWindow()
{
delete ui;
}
输出:
//有参 connect(fa,SIGNAL(faSingnals(QString)),shou,SLOT(shouSlots(QString)));//无参 connect(fa,SIGNAL(faSingnals()),shou,SLOT(shouSlots()));不建议使用