方法
1)引入头文件:#include
2)添加声明:利用宏 Q_DECLARE_METATYPE
3)注册:利用方法 qRegisterMetaType
实践
1.建结构体作为自己传输的信号(可以多加几个需要的数据。
struct MySignalParam{
QString str;
QString dis;
};
- 添加声明
Q_DECLARE_METATYPE(MySignalParam)
3.注册
qRegisterMetaType();
4.连接信号与槽函数
connect(&worker,SIGNAL(sendMeg(MySignalParam)),this,SLOT(receiveData(MySignalParam)));
【Qt5的写法试了一下,好像报错了,希望知道的小伙伴不吝赐教】
源码
构建一个类来定义信号
myworker.h
#ifndef MYWORKER_H
#define MYWORKER_H
#include <QObject>
struct MySignalParam{
QString str;
QString dis;
};
Q_DECLARE_METATYPE(MySignalParam)
class MyWorker : public QObject
{
Q_OBJECT
public:
explicit MyWorker();//QObject *parent = 0);
signals:
void sendMeg(MySignalParam myparam);
public:
void myrun();
};
#endif // MYWORKER_H
myworker.cpp
#include "myworker.h"
#include <QVariant>
#include <QDebug>
#include <QTime>
#include <QThread>
MyWorker::MyWorker()
{
qRegisterMetaType<MySignalParam>();
}
void MyWorker::myrun()
{
MySignalParam signalParam;
signalParam.str="send time signial : ";
signalParam.dis=QTime::currentTime().toString() ;
QThread::msleep(50);
emit sendMeg(signalParam);
}
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "myworker.h"
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
public slots:
void receiveData(MySignalParam signalParam);
private slots:
void on_pushButton_clicked();
private:
Ui::Widget *ui;
MyWorker *worker;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include <iostream>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
worker= new MyWorker();
connect(worker,SIGNAL(sendMeg(MySignalParam)),this,SLOT(receiveData(MySignalParam)));
}
Widget::~Widget()
{
delete ui;
}
void Widget::receiveData(MySignalParam signalParam)
{
ui->textEdit->append(signalParam.str+signalParam.dis);
}
void Widget::on_pushButton_clicked()
{
worker->myrun();
}
搭载界面
添加一个按钮和一个textEdit框:
效果
每点击一次按钮就会打印一次当前时间
参考:1.https://www.freesion.com/article/885612072/
2. https://www.cnblogs.com/mehome/p/15832052.html
3. https://blog.csdn.net/u013360881/article/details/78878471