Qt信号槽传递自定义结构体

1.定义结构体并注册元对象

//1.定义结构体
struct Student
{
    int     m_id;
    int     m_age;
    QString m_name;
};


//2.注册元对象
Q_DECLARE_METATYPE(Student)

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    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 = varValue.value();
         qDebug()<<"ID : "<

5.运行结果:

 

你可能感兴趣的:(qt,Qt信号使用结构体,qt信号自定参数)