//for starf study
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QDebug>
#include<QMetaType>
#include <QString>
#include <QVariant>
//QMetaType类管理元对象系统中的命名类型。
//该类用作QVariant、排队信号和插槽连接中marshall类型的助手
//使用 Q_DECLARE_METATYPE()声明新类型,使它们可用于QVariant和其他基于模板的函数。
//qRegisterMetaType()使类型可用于非基于模板的函数,例如排队信号和插槽连接。
/*
enum QMetaType::Type{
QMetaType::Void,
QMetaType::Bool,
QMetaType::Int,
QMetaType::UInt,
...
QMetaType::QString,
QMetaType::QByteArray,
...
QMetaType::QObjectStar,
QMetaType::QVariant,
...
QMetaType::QPen,
...
QMetaType::QPixmap,
...
QMetaType::User,
QMetaType::UnknownType
}
*/
//QMetaType 默认管理这个枚举类型,里面有默认的类型
//typedef struct MyCustomStructStruct{
// QString name;
// int age;
//}MyCustomStruct;
Q_DECLARE_METATYPE(MyCustomStruct) //将自定义数据结构注册到QMetaType
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
MyCustomStruct cs;
cs.age = 24;
cs.name = "starf";
QVariant v;
v.setValue(cs); // 可以让QVariant 识别自定义类型
// 也可以是自定义calss 或者自定义 namespace
MyCustomStruct cp = v.value<MyCustomStruct>();
qDebug()<< cp.name; //"starf"
qRegisterMetaType<MyCustomStruct>("MyCustomStruct"); //注册类型
connect(this,SIGNAL(send_test_signal(MyCustomStruct)), this, SLOT(get_test_signal(MyCustomStruct)), Qt::QueuedConnection);
//需要在槽函数中使用自定义类型或者类 首先需要使用Q_DECLARE_METATYPE 注册类型
// 如果需要跨线程传递自定义类型或者类 就还需要使用qRegisterMetaType 注册
//如果只是在本线程中使用,那么可以不用 qRegisterMetaType
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::get_test_signal(MyCustomStruct s)
{
qDebug()<<s.name<<s.age;
}
void MainWindow::on_pushButton_clicked()
{
MyCustomStruct cs;
cs.name = "fox";
cs.age = 23;
emit send_test_signal(cs);
}
Q_DECLARE_METATYPE()和qRegisterMetaType基本使用方法(5.12)
最新推荐文章于 2024-06-26 19:30:57 发布