qml使用c++端的类,作为组件在qml端使用
这个类必须继承QObject
这个类必须继承QObject
#ifndef COLLISIONALARM_H
#define COLLISIONALARM_H#include <QObject>class CollisionAlarm : public QObject
{Q_OBJECT//这个宏就叫做反射机制,让qml端直接使用该变量//qt5.14版本以后,鼠标光标放在变量处,按下alt+enter,快捷生成set get notifyQ_PROPERTY(QPointF endPoint READ getEndPoint WRITE setEndPoint NOTIFY ycnEndPointChanged)public:explicit CollisionAlarm(QObject *parent = nullptr);QPointF getStartPoint() const;void setStartPoint(const QPointF &value);QPointF getEndPoint() const;void setEndPoint(const QPointF &value);void onTimeout();signals:void ycnEndPointChanged();private:QPointF endPoint;
};#endif // COLLISIONALARM_H
#include "collisionalarm.h"
#include<QTimer>#include<QDebug>
CollisionAlarm::CollisionAlarm(QObject *parent) : QObject(parent)
{QTimer *timer = new QTimer(this);connect(timer, &QTimer::timeout, this, &CollisionAlarm::onTimeout);timer->start(1000);endPoint.setX(30.6600465788062);endPoint.setY(104.06294724255133);}
void CollisionAlarm::onTimeout()
{//一定要把这个信号发出去,qml端才能时刻获得endPoint的值emit ycnEndPointChanged();qDebug()<<endPoint;
}QPointF CollisionAlarm::getStartPoint() const
{return startPoint;
}void CollisionAlarm::setStartPoint(const QPointF &value)
{startPoint = value;
}QPointF CollisionAlarm::getEndPoint() const
{return endPoint;
}void CollisionAlarm::setEndPoint(const QPointF &value)
{endPoint = value;
}
找个地方写这段代码,把这个类注册到qml系统反射机制,qml才能识别
qmlRegisterType<CollisionAlarm>("CollisionAlarm", 1, 0, "CollisionAlarm");
来到qml这端
先导入这c++这端的组件(就上面那个类)
import CollisionAlarm 1.0//直接使用上面这个类
CollisionAlarm{id:collisionWarnproperty var fendPoint: endPoint;//这个槽可以监测属性变化onEndPointChanged: {console.log("lat","lon",fendPoint.x,fendPoint.y)// collision_line.append({"lat_collision":fendPoint.x,"lon_collision":fendPoint.y});// collision_line.addCoordinate(QtPositioning.coordinate(fendPoint.x,fendPoint.y));// control.helicopter_.appendpoint("quhi",QtPositioning.coordinate(fendPoint.x,fendPoint.y),3500)}
}