qt - 在 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 }
}
}
}
}
解决方案
推荐阅读
- ocaml - 中缀运算符的合法名称是什么?
- nativescript - 如何:将用户文件上传到 iCloud + 从 iCloud 检索文件?(本机脚本)
- python - 使用 numpy 离散接近高斯分布
- firebase - 将 Firebase Firestore Listview 数据显示为列表 Flutter
- jenkins - 使用 jenkins 在融合中显示 sh 脚本输出
- r - 如何用 x 值替换 ggplot2 中的图例?
- java - 更新:根据文件扩展名将文件从一个文件夹移动到另一个文件夹
- c - 有人可以解释指向我的指针吗
- c++ - c ++ - 使用方法或通用函数两个文件的友谊实现
- ios - SCNCamera 以编程方式制作的位置不正确