1. What are signals and slots?
One object sends a signal out, and another object triggers the corresponding slot function after receiving the signal
Second, the syntax of signals and slots
connect (sender of the signal, SIGNAL (signal name), receiver of the signal, SLOT (slot function));
1. Writing method:
How to write QT 4
connect(sender,SIGNAL(valueChanged(QString,QString)),receiver,SLOT(updateValue(QString)));
How to write QT 5
connect(sender,&Sender::valueChanged,receiver,&Receiver::updateValue);
2. Definition
The control generates a signal definition:
1. Declare the slot function in the class that needs to receive the signal
//声明槽函数
public slots:
void set_label();
②. Implement the slot function in xxx.cpp
void MainWindow::set_label()
{
ui->label->setText("设置标签成功!!!666");}
③. Associate signals and slots
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(set_label()));
User-defined signal:
①. Declare the signal in the sender class of the signal
signals:
void mysig();
②, associated signal and slot
connect(this,SIGNAL(mysig()),this,SLOT(set_label()));
③, send signal
emit mysig();
3. Parameter transfer of signals and slots
①. Define a signal with parameters
signals:
//定义一个带参的信号
void mysig(int a);
②, define a slot with parameters
public slots:
void get_sig(int a);
③. Associate signals and slots
connect(this,SIGNAL(mysig(QString)),this,SLOT(get_sig(QString )));
④. Send a signal with parameters
emit mysig("HELLO QT");
Notes on parameter passing:
- 1. The parameter types of signals and slots must match
- 2. The number of parameters of the sender must be greater than or equal to the number of parameters of the receiver
Signal and slot disassociation
grammar:
disconnect(信号的发送者,SIGNAL(发送的信号),信号的接收者,SLOT(接收的信号));
-----------------------------------------------------------------------
例子:
disconnect(this,SIGNAL(mysig()),this,SLOT(get_sig()));