Получение данных GPS из текстового файла и отображение в QT Map - PullRequest
1 голос
/ 24 мая 2019

Я пытаюсь получить данные текстового файла с помощью long и lat, используя соединение UDP Socket, полученные данные будут отображаться на моей карте QT QML. Могу ли я сделать это в QT?

Plugin {
    id: mapPlugin
    name: "osm" 
   }

   MapQuickItem
   {
      id: marker
      anchorPoint.x: marker.width / 4
      anchorPoint.y: marker.height
      coordinate: QtPositioning.coordinate(13.293470, 135.816885)
      Image { source: "qrc:/marker.png"
             }
        Text { text: "Location" ;font.pointSize: 8; font.bold: true }

       }
    }

1 Ответ

0 голосов
/ 24 мая 2019

Вы должны реализовать QObject, который имеет позицию q_property, и экспортировать его в QML, используя setContextProperty (или используя qmlRegisterType), у этого QObject должен быть метод, который считывает каждую строку текста, анализирует его в параметре QGeoCoordinate в качестве позиции.Следующий код является примером:

main.cpp

#include <QFile>
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QTextStream>
#include <QTimer>
#include <QGeoCoordinate>
#include <QRegularExpression>

class MarkerManager: public QObject
{
    Q_OBJECT
    Q_PROPERTY(QGeoCoordinate position READ position NOTIFY positionChanged)
public:
    MarkerManager(QObject *parent=nullptr): QObject(parent){
        connect(&timer, &QTimer::timeout, this, &MarkerManager::readLine);
    }
    bool loadFile(const QString & filename, int interval=100){
        file.setFileName(filename);
        if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
            return false;
        ts.setDevice(&file);
        timer.start(interval);
        return true;
    }
    QGeoCoordinate position() const{
        return m_position;
    }
Q_SIGNALS:
    void positionChanged();
private Q_SLOTS:
    void readLine(){
        if(!ts.atEnd()){
            QString line = ts.readLine();
            QStringList elements = line.split(QRegularExpression("\\s+"));
            if(elements.count() == 2){
                bool ok1, ok2;
                double lat = elements[0].toDouble(&ok1);
                double lng = elements[1].toDouble(&ok2);
                if(ok1 && ok2){
                    m_position = QGeoCoordinate(lat, lng);
                    Q_EMIT positionChanged();
                }
            }
        }
    }
private:
    QFile file;
    QTextStream ts;
    QTimer timer;
    QGeoCoordinate m_position;
};

#include "main.moc"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    MarkerManager manager;
    manager.loadFile("data_gps.txt");
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("manager", &manager);
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

main.qml

import QtQuick 2.12
import QtQuick.Window 2.12

import QtLocation 5.12
import QtPositioning 5.12

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    Plugin {
        id: mapPlugin
        name: "osm"
    }
    Map {
        id: map
        anchors.fill: parent
        plugin: mapPlugin
        center: QtPositioning.coordinate(14.70202102, 121.0957246)
        zoomLevel: 15
        MapQuickItem{
            id: marker
            anchorPoint.x: marker.width / 4
            anchorPoint.y: marker.height
            coordinate: manager.position
            sourceItem:  Image { source: "qrc:/marker.png"
                Text { text: "Location" ; font.pointSize: 8; font.bold: true }
            }
        }
    }
}

Полный пример можно найти здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...