1

So I'm new to QGIS and Qt, and trying to write a simple toy python plugin. I'm trying to get the plugin to do "stuff" at regularly timed intervals, and to test, I'm just trying to get the script to write to the plugin's log, which I can view in QGIS.

According to this, I should be using the QTimer class to make an asynchronous thread.

This notes how to actually use the timer, and is largely the script I'm basing mine on.

And this notes how to write to the log.

So here's my code:

def runTick(self):
    QgsMessageLog.logMessage("called runtick", "myPlugin")
    timer = QTimer()
    timer.timeout.connect(self.tick)
    QgsMessageLog.logMessage("starting tick", "myPlugin")
    timer.start(1000)

def tick(self):
    QgsMessageLog.logMessage("tick", "superrefresh")

When I run it, I get:

called runtick
starting tick

and then nothing. This is rather annoying, since I'd like to be able to know if my script is actually running what I tell it to run, or if it has just decided that doing what I tell it to is not worth the trouble.

2

Figured it out! A bit more googling provided the answer, here

You have to keep a reference totimer

If you don't, it willget garbage-collected, and f() will never be called.

Since I was keeping my timer object in the runTick() function, it got destroyed as soon as the function finished executing. I resolved the issue by the timer a property of the class containing runTick().

class myClass:
    def __init__(self):
        timer = None

    def runTick(self):
        QgsMessageLog.logMessage("called runtick", "myPlugin")
        self.timer = QTimer()
        self.timer.timeout.connect(self.tick)
        QgsMessageLog.logMessage("starting tick", "myPlugin")
        self.timer.start(1000)
    def tick(self):
        ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy