在qgis中使用Python调度重复事件

0 投票
1 回答
991 浏览
提问于 2025-05-01 08:07

我需要在qgis中每隔n秒安排一个任务。在这个过程中,我还可以做其他事情(比如查看一个对象的属性)。

我在Python中实现了这样的代码:

import time,threading...

interval=60
def job():
   ....
   ....
   ....
   threading.Timer(interval,job).start()
threading.Timer(interval,job).start() 

但是当我运行这个脚本时,它就一直挂在那里,什么都不做。

为了完整起见,我把整个代码放在这里:

import time,threading
import re,glob,os
from PyQt4.QtGui import QColor

interval=5
def job():
    lay=qgis.utils.iface.activeLayer()
    iterator=range(50)
    counter=0
    for i in iterator:
        if lay<>None and not(re.search("com",lay.name())):
           QgsMapLayerRegistry.instance().removeMapLayer(lay.id())
           lay=qgis.utils.iface.activeLayer()
    dir="/home_local/titan/projDir/data/titan/shapefiles/shapefile/"
    lista=os.listdir(dir)
    exp="shp"
    for file in lista: 
        if re.search(exp,file):
           counter=counter+1           
           lay=qgis.utils.iface.addVectorLayer(dir+file,file+str(counter),"ogr") 
           symbols = lay.rendererV2().symbols()
           symbol = symbols[0]
           if re.search("F30",file):
               symbol.setColor(QColor.fromRgb(50,50,250))
           else :
               symbol.setColor(QColor.fromRgb(150,200,200))
           qgis.utils.iface.mapCanvas().refresh() 
           qgis.utils.iface.legendInterface().refreshLayerSymbology(lay)
           lay.setLayerTransparency(30)
    threading.Timer(interval,job).start()
threading.Timer(interval,job).start()

注意:如果不使用线程,这个任务是可以正常工作的。

暂无标签

1 个回答

0

试试用QTimer吧。你可以把它的超时信号连接到一个槽函数,这样就可以进行你的处理(如果需要的话,可以在一个Python线程中进行)。

from PyQt4.QtCore import QTimer
timer = QTimer()
timer.timeout.connect(my_slot)
timer.start(1000) # start 

撰写回答