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

2023-12-13 13:47:59

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.运行结果

文章来源:https://blog.csdn.net/huzhifei/article/details/134859723
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。