qt的信号与槽, 允许一个信号与一个或多个槽连接, 也允许多个信号与一个槽连接
还允许信号与信号连接… 进行信号与槽的连接, 槽方法允许比信号的参数列表少
或参数列表相同(参数必须匹配)
比如: 信号: void hello(QString& str)
槽: void hi1();
或者void hi2(QString& str)
void hi(QString&str, int i) //不行
// 头文件中加入自定义的信号
signals:
void hello(QString& str);
托三个按钮, 添加槽方法, 当点击按钮时发送一个hello的信号
void Dialog::on_pushButton_clicked()
{
QString str = "早上好";
emit hello(str);
}
void Dialog::on_pushButton_2_clicked()
{
QString str = "中午好";
emit hello(str);
}
void Dialog::on_pushButton_3_clicked()
{
QString str = "晚上好";
emit hello(str);
}
信号与槽进行连接, 调用connect.对hello信号与hi槽方法进行连接
类必须继承自QObject, 在我们的类内声明 Q_OBJECT宏
下面俩种连接方法, 看自己的习惯
connect(this, SIGNAL(hello(QString&)),this,SLOT(hi(QString&)));
//connect(this, &Dialog::hello, this, &Dialog::hi);
点击对应的按钮, 发出hello信号, hello信号又与hi槽方法连接, 调用槽方法, 打印数据(或者其他操作), 说明一个信号(hello)可以与一个槽方法(hi)进行连接
// 添加 nihao槽函数
void Dialog::nihao(QString& str)
{
qDebug() << "你好";
}
// 对hello信号与nihao槽方法进行连接
connect(this, &Dialog::hello, this, &Dialog::nihao);
说明一个槽方法可以与多个信号连接
//在早上好按钮中添加 emit hello1(str)
void Dialog::on_pushButton_clicked()
{
QString str = "早上好";
emit hello(str);
emit hello1(str); //添加
}
//对信号hello1信号与nihao槽方法连接
connect(this, &Dialog::hello1, this, &Dialog::nihao);
说明多个信号可以响应一个槽, hello和hello1信号分别响应nihao槽方法
.h文件
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
QT_BEGIN_NAMESPACE
namespace Ui { class Dialog; }
QT_END_NAMESPACE
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = nullptr);
~Dialog();
signals:
void hello(QString& str);
void hello1(QString& str);
void hello2();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
//响应hello信号的槽方法(hi)
void hi(QString str);
void nihao(QString& str);
void dajiahao();
private:
Ui::Dialog *ui;
};
#endif // DIALOG_H
#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::Dialog)
{
ui->setupUi(this);
// 信号与槽的连接
// connect(this, SIGNAL(hello(QString&)),this,SLOT(hi(QString&)));
//1. 一个信号与一个槽
//1.2 一个信号与俩个(多个)槽
//2.3 俩个(多个)信号与一个槽
//4 信号与信号的连接 5给hello2信号添加槽连接, 就是第1条
connect(this, &Dialog::hello, this, &Dialog::hi); // 1
connect(this, &Dialog::hello, this, &Dialog::nihao);// 2
connect(this, &Dialog::hello1, this, &Dialog::nihao); // 3
connect(this, &Dialog::hello,this,&Dialog::hello2); // 4
connect(this, &Dialog::hello2, this,&Dialog::dajiahao);// 5
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_pushButton_clicked()
{
QString str = "早上好";
emit hello(str);
emit hello1(str);
}
void Dialog::on_pushButton_2_clicked()
{
QString str = "中午好";
emit hello(str);
}
void Dialog::on_pushButton_3_clicked()
{
QString str = "晚上好";
emit hello(str);
}
void Dialog::hi(QString str)
{
qDebug() << str;
}
void Dialog::nihao(QString &str)
{
qDebug() << "你好";
}
void Dialog::dajiahao()
{
qDebug() << "大家好";
}
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}
ui界面