Qt中信号带参传值

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

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

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

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

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

实例:

widget.h

cpp 复制代码
#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

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());
}

结果:

相关推荐
好好学习O(∩_∩)O33 分钟前
[QT] 多线程moveToThread 和易踩的8个坑
开发语言·qt
北i3 小时前
Dubbo 默认超时重试:把下游打雪崩的隐形放大器
开发语言·qt·dubbo
扶尔魔ocy5 小时前
【qt openGL入门笔记】OSG实现显示飞机模型飞行的点迹(二)
qt·opengl·osg
Python图像识别8 小时前
43-【2027毕设】YOLO11暴力检测识别系统 - Python完整源码+PyQt5界面+训练模型+数据集
python·qt·课程设计
bug和崩溃我都要17 小时前
QT 开发的专业截图录屏工具 - macOS版 / Windows版
windows·qt·mac·录屏·截屏
Python图像识别20 小时前
40-【2027毕设】YOLO11面部口罩检测识别系统 - Python完整源码+PyQt5界面+训练模型+数据集
python·qt·课程设计
Python图像识别20 小时前
39-【2027毕设】YOLO11行人摔倒检测系统 - Python完整源码+PyQt5界面+训练模型+数据集
python·qt·课程设计
Quz1 天前
QML PathView:直线路径与曲线路径
qt·动画·qml
扶尔魔ocy1 天前
【qt openGL入门笔记】OSG实现飞机模型在网格图上飞行
qt·opengl·osg