pythonqtpyqtscheduled-tasks

Passing a parameter to QTimer timeout signal?


I'm using Python and PySide (the PyQt alternative). I have an application that runs in a background and I'd like to use QTimer to schedule some tasks to be performed.

However, I need the QTimer to call one method in my program, but this method requires the "initialization parameters" that will specify what exactly is method supposed to do.

Am I correct in thinking that I would need to subclass QTimer and override either the timeout or the start method? If so, then which one and how would I go about that? I have almost no experience overriding existing methods and Googling didn't turn up a lot of results (there were some with C++ which I don't understand). I have managed to do something (for example I overrode the start() method, but then the code of the original start method does not execute (understandably) and I have no idea what that code is supposed to be.

Or is there some other way?


Solution

  • However, I need the QTimer to call one method in my program, but this method requires the "initialization parameters" that will specify what exactly is method supposed to do.

    Are the initialization parameters changing? I would probably do something involving functools.partial to bind up some of the arguments, so if you have this

    import functools
    from PySide.QtCore import QTimer
    
    def onTimer(initParams):
        # use initParams
        # your code here...
    
    myInitParams = "Init!"
    timerCallback = functools.partial(onTimer, initParams=myInitParams)
    myTimer = QTimer()
    myTimer.timeout.connect(timerCallback)
    myTimer.start( 1000) #once a sec
    
    #Your QApplication goes below...
    

    If you want to give different init parameters depending on some current condition of your application, you'd probably do better to use custom signals/slots based on when that specific item changes. Or maintain whatever that "current" state is my modifying initParams elsewhere.