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

结果:

相关推荐
用户805533698032 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner2 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz7 天前
QML Hello World 入门示例
qt
xcyxiner10 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner11 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner11 天前
DicomViewer (添加模型类)3
qt
xcyxiner12 天前
DicomViewer (目录调整) 2
qt
xcyxiner12 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
桥田智能14 天前
桥田智能 QT-650S:面向白车身焊装的 800kg 重载快换解决方案
开发语言·qt·系统架构
森G14 天前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt