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

问题描述 投票:1回答:1

我已经为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的呈现,并且结果与预期不符。

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!"
python pyqt pyqt4 shapefile qgis
1个回答
1
投票

避免使用time.sleep(),因为那样会完全停止整个程序。而是使用processEvents(),它允许您的程序在后台呈现。

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用于永久解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.