Problem calling fucntion with lambda along with QTimer.singleShot

824 Views Asked by At

I tried to called a function with delay time with of help of QTimer.singleShot function but is not yielding any output.

from PyQt5.QtCore import QTimer

list1=[1,2,3,4,5]
delay = 2500

def calling_func():
    if list1:
        list_item = list1.pop()
        QTimer.singleShot(delay, lambda: target_func(list_item))


def target_func(list_item):
    print("fid= ",list_item)
    QTimer.singleShot(delay, calling_func)


calling_func()

I am expecting to output list_item value one by one in target_func but the function is not being called.

1

There are 1 best solutions below

0
On BEST ANSWER

The asynchronous elements of Qt such as signals and timers use the eventloop for their execution, in your case there are none so it fails. The solution is to create a Q{Core, Gui, }Application:

from PyQt5.QtCore import QCoreApplication, QTimer

list1=[1,2,3,4,5]
delay = 2500

def calling_func():
    if list1:
        list_item = list1.pop()
        QTimer.singleShot(delay, lambda: target_func(list_item))


def target_func(list_item):
    print("fid= ",list_item)
    QTimer.singleShot(delay, calling_func)

app = QCoreApplication([])
calling_func()
app.exec_()