【发布时间】:2019-07-28 07:25:21
【问题描述】:
我有一个小问题让我花了一大半时间。我正在尝试根据 pyQt 使用 Geocoder 传入的本地坐标在 QML 中绘制地图屏幕。我可以画好地图,但是一旦发出信号,它似乎就不会更新。我对 QML 和信号/插槽比较陌生。任何帮助都将不胜感激。
main.py
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot
class Point(QObject):
def __init__(self, lat, lng):
QObject.__init__(self)
self.lat = lat
self.lng = lng
#Signal sending point
#Give the name of the argument through arguments=['lat', 'lng']
#Otherwise, it will not be possible to get it in QML
showCenter = pyqtSignal(float, float, arguments=['lat', 'lng'])
#Slot for emitting point
@pyqtSlot()
def emitPoint(self):
self.showCenter.emit(self.lat, self.lng)
if __name__ == "__main__":
import sys
import geocoder
#Create an instance of the application
app = QGuiApplication(sys.argv)
#Create a QML engine
engine = QQmlApplicationEngine()
#Create a Point object
g = geocoder.ip('me')
center_point = Point(g.latlng[0], g.latlng[1])
#And register it in the context of QML
engine.rootContext().setContextProperty("center_point", center_point)
#Load the qml file into the engine
engine.load("main.qml")
engine.quit.connect(app.quit)
sys.exit(app.exec_())
main.qml
import QtQuick 2.5
import QtQml 2.0
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.2
import QtPositioning 5.9
import QtLocation 5.9
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Map Point demo")
color: "whitesmoke"
Plugin {
id: mapPlugin
name: "esri" //"mapboxgl" "osm" "esri"
}
Map {
id: map
anchors.fill: parent
plugin: mapPlugin
center: QtPositioning.coordinate(0.0, 0.0)
zoomLevel: 6
MapCircle {
id: dot
center: QtPositioning.coordinate(0.0, 0.0)
radius: 50
color: 'red'
}
Connections {
target: center_point
onEmitPoint: {
console.info("Point changed")
map.center = QtPositioning.coordinate(lat, lng)
dot.center = QtPositioning.coordinate(lat, lng)
}
}
}
Component.onCompleted: {
console.info("Signal Emitted")
center_point.emitPoint()
}
}
【问题讨论】:
标签: python python-3.x pyqt qml pyqt5