python - QGIS渲染shapefile时如何让Python等待
问题描述
我已经为我的代码编写了QGIS 2.8.1
可以成功截取一个形状文件的代码,但不幸的是,当我尝试使用多个形状文件时它不起作用。
所以基本上如果我allFiles = ["C:/Shapefiles/Map_00721.shp"]
在下面的代码中替换为allFiles = ["C:/Shapefiles/Map_00721.shp", "C:/Shapefiles/Map_00711.shp", "C:/Shapefiles/Map_00731.shp", "C:/Shapefiles/Map_00791.shp", "C:/Shapefiles/Map_00221.shp"]
,循环会遍历数组而不等待渲染和快照过程发生。
我已经尝试time.sleep
在下面的代码中使用,但它也停止了 shapefile 的渲染,结果没有按预期出现。
import ogr,os
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *
import qgis.utils
import glob
from time import sleep
import math
import processing
from processing.core.Processing import Processing
from PyQt4.QtCore import QTimer
Processing.initialize()
Processing.updateAlgsList()
OutputFileName = "ABC" # Temprory global placeholder for filename
canvas = iface.mapCanvas()
def startstuffs():
qgis.utils.iface.zoomToActiveLayer() # Zoom to Layer
scale=canvas.scale() # Get current Scale
scale = scale * 1.5
canvas.zoomScale(scale) # Zoomout a bit
QTimer.singleShot(2000,saveImg) # Jump to save img
def saveImg():
qgis.utils.iface.mapCanvas().saveAsImage(OutputFileName)
QgsMapLayerRegistry.instance().removeAllMapLayers()
# Add array of address below
allFiles = ["C:/Shapefiles/Map_00721.shp"]
filesLen = len(allFiles)
TexLayer = "C:/US_County_NAD27.shp"
for lop in range(filesLen):
currentShpFile = allFiles[lop]
currentShpFileName = currentShpFile.strip("C:/Shapefiles/")
OutputFileName = "C:/ImageOut/" + currentShpFileName + ".png"
wb = QgsVectorLayer(currentShpFile, currentShpFileName, 'ogr')
wbTex = QgsVectorLayer(TexLayer, 'CountyGrid', 'ogr')
QgsMapLayerRegistry.instance().addMapLayer(wb) # Add the shapefile
QgsMapLayerRegistry.instance().addMapLayer(wbTex) # Add the county shapefile
qgis.utils.iface.setActiveLayer(wb) # Makes wb as active shapefile
QTimer.singleShot(3000, startstuffs) # This start stuffs
print "Done!"
解决方案
避免使用time.sleep()
,因为这会完全停止你的整个程序。相反,使用processEvents()
which 允许您的程序在后台呈现。
import time
def spin(seconds):
"""Pause for set amount of seconds, replaces time.sleep so program doesn't stall"""
time_end = time.time() + seconds
while time.time() < time_end:
QtGui.QApplication.processEvents()
这种方法应该可以很好地快速修复,但从长远来看,它可能会产生难以跟踪的问题。最好使用带有事件循环的 QTimer 作为永久解决方案。
推荐阅读
- java - Spring boot - 动态加载war文件
- jquery - 将 chrome 更新到最新版本(83.0.4103.61)后,数据表中的不确定选择所有复选框无法正确呈现
- tensorflow - 我安装了 tensorflow 2.0 但 jupyter 没有看到它?
- javascript - Firefox 在编辑时错误地修剪尾随空格
- scala - Apache Flink - Kafka 生产者的 Json 案例类
- arcgis - ArcGIS JS API:使圆不缩放
- vue.js - 编译失败。./src/main.js 未找到模块:错误:无法解析 'C:\vue\testvueapp\src' 中的 '.plugins/vuetify'
- spring-boot - 当服务部署在 Google Cloud 中时,当 Spring Cloud Config 服务器的 POST /actuator/bus-refresh 出现“方法不允许”错误
- python - 在终端中多行打印列表
- ios - 是否需要释放 dispatch_queue_create 创建的 dispatch_queue_t