首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在QGIS渲染shapefile时让Python等待

如何在QGIS渲染shapefile时让Python等待
EN

Stack Overflow用户
提问于 2019-03-22 22:25:12
回答 1查看 1K关注 0票数 2

我已经为我的QGIS 2.8.1写了代码,它可以成功地截取一个形状文件的屏幕截图,但不幸的是,当我尝试多个shapefile时,它不能工作。

因此,基本上,如果我将下面代码中的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的渲染,结果并不像预期的那样。

代码语言:javascript
复制
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!"
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-26 05:15:07

避免使用time.sleep(),因为这会完全拖慢你的整个程序。取而代之的是使用processEvents(),它允许程序在后台呈现。

代码语言:javascript
复制
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。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55301747

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档