首页 > 解决方案 > 在 Qt 中显示 QML 地图时显示修改后的 txt 文件

问题描述

我在我的 Qt QML 项目中显示地图,我需要在地图中显示的项目是来自文本文件的数据,我在显示时遇到问题,因为 txt 文件每次都被修改。在显示地图时修改文本文件时,我可以在 Qt 中显示一个项目吗?

.h 文件

     class BackEnd: public QObject
 {
  Q_OBJECT
  Q_PROPERTY(QGeoCoordinate position READ position NOTIFY positionChanged)
public:
  BackEnd(QObject *parent=nullptr): QObject(parent){
    connect(&timer, &QTimer::timeout, this, &BackEnd::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;
  };

main.cpp 文件

   QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

   QGuiApplication app(argc, argv);
       BackEnd backend;
       backend.loadFile("message.txt");
       QQmlApplicationEngine engine;
       engine.rootContext()->setContextProperty("backend", &backend);
       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();

qml代码

  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(50.123, 20.329)
    zoomLevel: 15
    MapQuickItem{
        id: marker
        anchorPoint.x: marker.width / 4
        anchorPoint.y: marker.height
        coordinate: backend.position
        sourceItem:  Image { source: "qrc:/marker.png"
            Text { text: "Item" ; font.pointSize: 8; font.bold:  true }
          }
      }
      }
  }

标签: qtqml

解决方案


推荐阅读