使用qt,在mainwindow里采用qquickwidget,将一组二维qvariantlist数据,传递给qml并在qlocation地图上画一段曲线
时间: 2023-12-10 09:05:07 浏览: 186
利用Qt在区域内绘制多条曲线
5星 · 资源好评率100%
好的,可以参考下面的代码实现:
在mainwindow.cpp中,定义一个QVariantList的数据并初始化:
```c++
QVariantList dataList;
dataList << QVariant::fromValue(QGeoCoordinate(39.9042, 116.4074));
dataList << QVariant::fromValue(QGeoCoordinate(31.2304, 121.4737));
dataList << QVariant::fromValue(QGeoCoordinate(22.3964, 114.1095));
```
然后在MainWindow构造函数中,设置QQuickWidget的源码为qml文件,并在QML中绑定数据:
```c++
QQuickWidget *mapWidget = new QQuickWidget(this);
mapWidget->setSource(QUrl(QStringLiteral("qrc:/map.qml")));
QObject *rootObject = mapWidget->rootObject();
rootObject->setProperty("dataList", QVariant::fromValue(dataList));
```
在qml中,需要使用QML Map中的Polyline绘制曲线。在Polyline中绑定数据并设置颜色、宽度等参数:
```qml
import QtLocation 5.6
Map {
id: map
anchors.fill: parent
Polyline {
line.width: 3
line.color: "red"
line.capStyle: Qt.RoundCap
line.joinStyle: Qt.RoundJoin
path: dataList
}
}
```
其中,dataList是在MainWindow中绑定的数据,Polyline的path属性即为绘制的路径。最后在MainWindow中显示QQuickWidget即可:
```c++
mapWidget->setMinimumSize(800, 600);
mapWidget->show();
```
完整的代码如下:
mainwindow.cpp:
```c++
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtQuickWidgets/QQuickWidget>
#include <QVariantList>
#include <QGeoCoordinate>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QVariantList dataList;
dataList << QVariant::fromValue(QGeoCoordinate(39.9042, 116.4074));
dataList << QVariant::fromValue(QGeoCoordinate(31.2304, 121.4737));
dataList << QVariant::fromValue(QGeoCoordinate(22.3964, 114.1095));
QQuickWidget *mapWidget = new QQuickWidget(this);
mapWidget->setSource(QUrl(QStringLiteral("qrc:/map.qml")));
QObject *rootObject = mapWidget->rootObject();
rootObject->setProperty("dataList", QVariant::fromValue(dataList));
mapWidget->setMinimumSize(800, 600);
mapWidget->show();
}
MainWindow::~MainWindow()
{
delete ui;
}
```
map.qml:
```qml
import QtQuick 2.9
import QtPositioning 5.6
import QtLocation 5.6
Item {
width: 800
height: 600
Map {
id: map
anchors.fill: parent
Plugin {
id: mapPlugin
name: "osm"
}
MapItemView {
model: mapPlugin.mappingModel
}
Polyline {
line.width: 3
line.color: "red"
line.capStyle: Qt.RoundCap
line.joinStyle: Qt.RoundJoin
path: dataList
}
}
}
```
阅读全文