信号,带参数,可以传递参数给连接的槽函数。信号、槽函数类型要一致。

新建项目,QWidget,不勾选ui

5、信号,带参数

/*mywidget.h代码*/
#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <QWidget>
#include <QPushButton> //按钮
#include <QDebug> //打印

class MyWidget : public QWidget
{
    Q_OBJECT

public:
    MyWidget(QWidget *parent = 0);
    ~MyWidget();
    void sendSignal(); //自定义的函数,发送信号
    void MySlot(int a,QString str); //接收信号的槽函数
signals:
    void MySignal(int a,QString str);//信号与槽相对,信号传参给槽函数

private:
    QPushButton b; //按钮
};

#endif // MYWIDGET_H
/*mywidget.cpp代码*/
#include "mywidget.h"

MyWidget::MyWidget(QWidget *parent)
    : QWidget(parent)
{
    b.setText("打印参数");
    b.setParent(this); //按钮放在本窗体上
    connect(&b,&QPushButton::pressed,this,&MyWidget::sendSignal);
    connect(this,&MyWidget::MySignal,this,&MyWidget::MySlot);
}
void MyWidget::sendSignal()
{
    emit MySignal(520,"这不是节日!");//发送信号,传参给槽函数
}
void MyWidget::MySlot(int a,QString str)
{
    qDebug()<<a<<str.toUtf8().data();//注意字符串的输出方式,qDebug()类似cout
}

MyWidget::~MyWidget()
{

}

 

相关文章:

  • 2022-01-31
  • 2022-12-23
  • 2021-04-30
  • 2022-12-23
  • 2021-08-22
  • 2021-12-08
  • 2022-02-27
  • 2021-12-18
猜你喜欢
  • 2021-07-18
  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
  • 2022-12-23
  • 2022-02-02
相关资源
相似解决方案