qt5-信号和槽

信号函数:

connect(btn,&QPushButton::clicked,this,&QWidget::close);
    //参数1  信号发送者;
//参数2 信号;---&发送者的类名::信号名字
//参数3 信号接受者;参数4 槽函数)
//参数4 槽函数 ----&接受的类名::槽函数

自定义类的信号和槽函数: 

例子一:不带参数

例子2---带参数

视频教程:https://www.bilibili.com/video/av66373980/   

signals:
    void xiake(QString str);//自定义一个信号--带传送参数
public slots:
    void huodong(QString str); //声明一个槽函数--带接受参数
void Student::huodong(QString str){  //槽函数实现体
qDebug()<<"学生开始活动了:"<<str;
}
Teacher* th=new Teacher(this);
    Student* sd=new Student(this);
    void(Teacher::*p)(QString)=&Teacher::xiake; //定义函数指针
    void(Student::*p1)(QString)=&Student::huodong;
    connect(th,p,sd,p1);//连接信号与槽函数
    emit th->xiake("做操");//发出信号

如果不是重载函数,也可以:connect(th,&Teacher::xiake,sd,&Student::huodong);

信号和槽函数出现同名重载时,用函数指针来区分

信号连接信号: 

QPushButton* btn=new QPushButton("按钮",this);
    btn->move(10,10);

    Teacher* th=new Teacher(this);
    Student* sd=new Student(this);
    void(Teacher::*p)(void)=&Teacher::xiake; 
    void(Student::*p1)(void)=&Student::huodong;

    connect(btn,&QPushButton::clicked,th,p);//信号连接信号
    //点击按钮就发出th的xiake信号
    connect(th,p,sd,p1);
    //th信号连接sd的槽函数

    //disconnect(th,p,sd,p1);//断开信号与槽函数的连接

注意:一个信号可以连接多个槽函数

多个信号也可以连接一个槽函数

槽函数的参数可以少于信号参数,但是类型必须一一对应

在VS中自定义槽函数:https://blog.csdn.net/qq_36880027/article/details/96627918

原文地址:https://www.cnblogs.com/liming19680104/p/11423891.html