如何在 PyQGIS 中输入点坐标?

How to input a point coordinates in PyQGIS?

我想编写一个脚本来提示用户输入 X 和 Y 坐标。这些坐标将向现有形状文件添加一个点。另外,我应该使用哪个函数调用来获取这些坐标?

vectorLyr = QgsVectorLayer("D:/Projekty/qgis_projekt/forty922.shp", "Forty", "ogr")
vpr = vectorLyr.dataProvider()
x = QInputDialog.getDouble(None, 'input', 'Insert x: ')
y = QInputDialog.getDouble(None, 'input', 'Insert y: ')
pnt = QgsGeometry.fromPoint(QgsPoint(x,y))
f = QgsFeature()
f.setGeometry(pnt)
vpr.addFeatures([f])
vectorLyr.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([vectorLyr])

输入 window 工作正常,但 Python 控制台抛出此语句

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "c:/users/hubi/appdata/local/temp/tmpxkrjpx.py", line 5, in <module>
    pnt = QgsGeometry.fromPoint(QgsPoint(x,y))
TypeError: arguments did not match any overloaded call:
  QgsPoint(): too many arguments
  QgsPoint(QgsPoint): argument 1 has unexpected type 'tuple'
  QgsPoint(float, float): argument 1 has unexpected type 'tuple'
  QgsPoint(QPointF): argument 1 has unexpected type 'tuple'
  QgsPoint(QPoint): argument 1 has unexpected type 'tuple'

当我向我的 pnt 变量添加常量时,它工作得很好。

pnt = QgsGeometry.fromPoint(QgsPoint(361637,501172))

有什么想法吗?

查看堆栈跟踪中的以下行:

QgsPoint(QgsPoint): argument 1 has unexpected type 'tuple'

python 是解释器告诉你,当你期望一个整数时,你得到一个元组作为输入。将代码更改为以下内容:

vectorLyr = QgsVectorLayer("D:/Projekty/qgis_projekt/forty922.shp", "Forty", "ogr")
vpr = vectorLyr.dataProvider()
x = QInputDialog.getDouble(None, 'input', 'Insert x: ')
y = QInputDialog.getDouble(None, 'input', 'Insert y: ')
pnt = QgsGeometry.fromPoint(QgsPoint(x[0],y[0]))
f = QgsFeature()
f.setGeometry(pnt)
vpr.addFeatures([f])
vectorLyr.updateExtents()
QgsMapLayerRegistry.instance().addMapLayers([vectorLyr])

希望对您有所帮助!