Qt中信号带参传值

发布于:2025-03-31 ⋅ 阅读:(26) ⋅ 点赞:(0)

在我们的Qt信号中是可以进行参数的传递的,不过格式上与写普通函数不同。

这是头文件中定义一个含参信号和一个含参槽函数

我们再来看它们两个的绑定 。第一行的clicked()和on_btn_clicked()就是普通无参信号和槽的绑定;第二行就是上图中两个带参信号和槽函数的绑定,要注意的是,我们只要写出参数类型,而不需要写对象。但定义的时候是要写出具体的形参对象的。

我们还可以写成新版信号与槽的连接形式

// 格式:connect(sender, &SenderClass::signalName, receiver, &ReceiverClass::slotName);
connect(this, &Widget::sendMessage, this, &Widget::receiveMessage);

实例:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QPushButton>
#include <QLineEdit>
#include <QLabel>
#include <QVBoxLayout>

#include "smainwidget.h"

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);
    ~Widget();

private:
    QPushButton *btn;
    QLineEdit *edit;
    QLabel *lab;

    QVBoxLayout *layout;

signals:
    void sendMessage(QString text);

public slots:
    void receiveMessage(QString text);
    void on_btn_clicked();
};

#endif // WIDGET_H

widget.cpp

#include "widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    this->btn=new QPushButton();
    this->btn->setText("按钮");
    this->edit=new QLineEdit();
    this->lab=new QLabel();

    this->layout=new QVBoxLayout();
    this->layout->addWidget(this->btn);
    this->layout->addWidget(this->edit);
    this->layout->addWidget(this->lab);

    this->setLayout(this->layout);

    connect(this->btn,SIGNAL(clicked()),this,SLOT(on_btn_clicked()));
    connect(this,SIGNAL(sendMessage(QString)),this,SLOT(receiveMessage(QString)));
}

Widget::~Widget()
{

}

void Widget::receiveMessage(QString text)
{
    this->lab->setText(text);
}

void Widget::on_btn_clicked()
{
    emit sendMessage(this->edit->text());
}

结果: