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

结果:

相关推荐
范特西.i5 天前
QT聊天项目(8)
开发语言·qt
枫叶丹45 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
十五年专注C++开发5 天前
Qt deleteLater作用及源码分析
开发语言·c++·qt·qobject
kangzerun5 天前
SQLiteManager:一个优雅的Qt SQLite数据库操作类
数据库·qt·sqlite
金刚狼885 天前
qt和qt creator的下载安装
开发语言·qt
追烽少年x5 天前
Qt中使用Zint库显示二维码
qt
谁刺我心5 天前
qt源码、qt在线安装器镜像下载
开发语言·qt
金刚狼886 天前
在qt creator中创建helloworld程序并构建
开发语言·qt
扶尔魔ocy6 天前
【转载】QT使用linuxdeployqt打包
开发语言·qt
YxVoyager6 天前
在VS2017中使用Qt的foreach宏,IntelliSense无法正确识别函数定义
c++·qt