(1)自定义结构体使用信号槽在qwidget中传递:
typedef struct tagPoint
{
tPos tIn;
QHash<unsigned char, tPos> tad;
unsigned char flag;
}tPoint;
Q_DECLARE_METATYPE(tPos)
Q_DECLARE_METATYPE(tPoint)
在使用信号槽的地方
qRegisterMetaType<tPoint>("tPoint");
QObject::connect(this, SIGNAL(sendSignal(tPoint)), app, SLOT(receive(tPoint)));
(2)自定义结构体从c++到qml中传递
(2.1)将结构体变成QVariantList形式
// 获取城市列表
Q_INVOKABLE QVariantList getCityNameList(void);
// 获取城市列表
QVariantList MixCppDemo::getCityNameList(void)
{
QVariantList varList;
varList.clear();
for (int i=0; i<m_CityNameList.count(); ++i)
{
varList.push_back(m_CityNameList.at(i));
}
return varList;
}
(2.2)将结构体变成QVariantMap形式(注意:QVariantHash是不可行的,自己试不行)
#include <QObject>
#include <QVariant>
#include <QVariantMap>
#include <QVariantList>
class MixCppDemo : public QObject
{
Q_OBJECT
public:
struct WeatherInfo
{
float tmp; // 温度
int day_code; // 白天天气代码
QString day_text; // 白天天气情况
int night_code; // 夜间天气代码
QString night_text; // 夜间天气情况
};
public:
MixCppDemo(QObject *parent = nullptr);
~MixCppDemo();
// 获取天气信息
Q_INVOKABLE QVariantMap getCurrentWeatherInfo(void);
private:
// 天气信息
WeatherInfo m_WeatherInfo;
};
// 获取天气信息
QVariantMap MixCppDemo::getCurrentWeatherInfo(void)
{
QVariantMap map;
map.clear();
map.insert("tmp", m_WeatherInfo.tmp);
map.insert("day_code", m_WeatherInfo.day_code);
map.insert("day_text", m_WeatherInfo.day_text);
map.insert("night_code", m_WeatherInfo.night_code);
map.insert("night_text", m_WeatherInfo.night_text);
return map;
}
(2.3)将结构体变成QJsonObject的形式(直接对应与js的对象形式)
void Hash::updateInUI(tInfo info)
{
QJsonObject Obj;
Obj.insert("Type", info.Type);
Obj.insert("ID", ID);
Obj.insert("Length", info.Length);
Obj.insert("Width", info.Width);
emit updateSignal(Obj);
}
(2.4)如果将结构体通过QVariant形式传递给qml不可行。
说明:如果向结构体通过QVariant temp1 = QVariant::fromValue(info);形式转成QVariant,然后将QVariant传递给qml也不可行,因为qml没有带有对应的结构体的格式不能解析该字段。
(2.5)扩展:如果在本地的结构是一个带有key,value是一个自定义的结构体的hash或者map,可以通过如下方式:
每次对hash或者map进行add或者remove操作的时候,将字段进行封装成QJsonObject或QVariantMap或者QVariantList,然后发信号。
博客内容部分转自: