QML与C++之间结构体输出

1.定义带有结构体的头文件TrackClass.h

#ifndef TRACKCLASS_H
#define TRACKCLASS_H

#include <QGuiApplication>
#include "QObject"
#include <QVector>

struct TrackPoint {
    Q_GADGET
    Q_PROPERTY(qreal lat MEMBER lat)
    Q_PROPERTY(qreal lon MEMBER lon)
    Q_PROPERTY(qreal elevation MEMBER elevation)
    Q_PROPERTY(int age MEMBER age)
public:
    qreal lat;
    qreal lon;
    qreal elevation;
    int   age;

};

class TrackClass: public QObject
{
    Q_OBJECT
    Q_PROPERTY(QVariantList trackpoints READ gpx)


public:
    TrackClass(QObject *parent=nullptr):QObject(parent){


        trackPoints << TrackPoint{10.0, 10, 10, 88} << TrackPoint{11.1, 11, 11, 99};
    }

    QVariantList gpx() const{

        QVariantList l;
        for(const TrackPoint & p: trackPoints){
            l << QVariant::fromValue(p);

        }
        return  l;


        /*
        QVariantList itemsList;

        for(const TrackPoint &p : trackPoints)
        {
            QVariantMap itemMap;
            itemMap.insert("lat", p.lat);
            itemMap.insert("lon", p.lon);
            itemMap.insert("elevation", p.elevation);
            itemMap.insert("age",p.age);
            itemsList.append(itemMap);
        }

        return itemsList;
        */
    }



private:
    QVector<TrackPoint> trackPoints;
};

#endif // TRACKCLASS_H

2.main.cpp 中注册

#include "TrackClass.h"


TrackClass track;   
engine.rootContext()->setContextProperty("track", &track);

3.main.qml中访问结构体

import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Label{

        id:result
        width:300

    }

    Button{
        id:button1
        text: "GetInfo"
        anchors.top: result.bottom

        onClicked: {

            for( var i in track.trackpoints){
                var p = track.trackpoints[i];
                result.text += "lat: "+ p.lat+ " lon: "+ p.lon+ " elevation: "+ p.elevation +" age: "+p.age

            }

        }
    }



}

4.运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值