pyqgis学习

时间:2023-01-24 18:27:29

1.
错误:ImportError: No module named qgis.core
解决方法:python的qgis,初始化变量:
D:\PROGRA~1\QGIS3~1.0\OSGeo4W.bat
D:\PROGRA~1\QGIS3~1.0\bin\py3_env.bat
D:\PROGRA~1\QGIS3~1.0\bin\qt5_env.bat
SET PYTHONPATH=D:\PROGRA~1\QGIS3~1.0\apps\qgis\python;D:\PROGRA~1\QGIS3~1.0\apps\Qt5\plugins
SET PATH=D:\PROGRA~1\QGIS3~1.0\apps\Qt5\plugins;%PATH%

2.
错误:This application failed to start because it could not find or load the Qt platform plugin "windows"
in "".
解决方法:把 包含qwindows.dll的目录platform复制到 D:\Program Files\QGIS 3.0\bin

3.
错误:QgisProject.read和QgisVectorLayer构造失败
解决方法:
环境变量没有设定好,在qgis.bat基础上去掉启动qgis,增加环境变量PYTHONPATH

4.
错误:QtCore.pyqtSignal信号发射接收问题解决
解决方法:
1.QtCore.pyqtSignal必须声明为类的变量
2.所在类必须继承与QtObject
3.构造函数必须直接调用QtCore.QObject.__init__(self)

5.
错误:在qtthread中启动httpserver崩溃的问题
解决方法:
1.原因python的httpserver模块默认打印到控制台,会导致qgis应为同步问题崩溃
2.重载BaseHTTPRequestHandler的log_message方法,去掉打印

5.
多线程使用HTTPServer服务,并和主线程通讯的例子

from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer
from PyQt5 import QtCore
import time class MyHttpServer(HTTPServer):
def log_message(self, format, *args):
pass class TodoHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path != '/':
self.send_error(, "File not found.")
return
self.send_response()
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(b"{}") self.server.request_.emit( 5.0, 5.0 ) def log_message(self, format, *args):
pass class TestRun(QtCore.QObject): request_ = QtCore.pyqtSignal(float, float) def __init__(self):
QtCore.QObject.__init__(self) def run(self):
#for i in range(,):
# time.sleep(0.1)
# print(i)
#print('-- server running --')
server = MyHttpServer(('localhost', ), TodoHandler)
server.request_ = self.request_
server.serve_forever() class TestRev(QtCore.QObject):
def __init__(self):
QtCore.QObject.__init__(self) def onRequest(self, x, y):
ext = iface.mapCanvas().extent()
ext += QgsVector(int(x),int(y))
iface.mapCanvas().setExtent(ext) def onError(self, e, exception_string):
print('Worker thread raised an exception:\n'.format(exception_string)) a = TestRev() r = TestRun()
t = QtCore.QThread()
r.moveToThread(t)
r.request_.connect(a.onRequest)
t.started.connect(r.run)
t.start()