//1.定义结构体
struct Student
{int m_id;int m_age;QString m_name;
};//2.注册元对象
Q_DECLARE_METATYPE(Student)class MainWindow : public QMainWindow
{Q_OBJECTpublic:explicit MainWindow(QWidget *parent = 0);~MainWindow();
private slots:void onSigSendStruct( const QVariant varValue);signals:void sigSendStruct( const QVariant varValue);
}
2.连接信号槽
connect(this, &MainWindow::sigSendStruct,this, &MainWindow::onSigSendStruct);
3.使用QVariant打包数据并发送
Student iStudent;iStudent.m_id = 1;iStudent.m_age = 22;iStudent.m_name = "Allen";QVariant varValue = QVariant::fromValue(iStudent);emit sigSendStruct(varValue);
4.在槽函数中解包并打印
void MainWindow::onSigSendStruct(const QVariant varValue)
{if (varValue.canConvert<Student>()){Student student = varValue.value<Student>();qDebug()<<"ID : "<<student.m_id;qDebug()<<"Age : "<<student.m_age;qDebug()<<"Name : "<<student.m_name;}}
5.运行结果: