2

How to call a method asynchronously in PyQt5 using Python3?

I have tried to use a signal to do it.

import sys
from time import sleep

from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel


class MainWindow(QMainWindow):
    asyncFuncSignal = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.initUi()

    def initUi(self):
        self.label = QLabel(self)
        self.label.setText("loading...")

        # Trying to call 'self.asyncFunc' asynchronously
        self.asyncFuncSignal.connect(self.asyncFunc)
        self.asyncFuncSignal.emit()

        print("loaded")

    def asyncFunc(self):
        # Doing something hard that takes time
        # I have used 'sleep' to implement the delay
        sleep(2)

        self.label.setText("done")
        print("asyncFunc finished")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

This program tries to finish asyncFunc before writing "loaded". But I would like the program to finish initUi immediately with shown loading... in the label and after that the text done appears in 2 seconds.

What is the best and the shortest way to do it?

It's said here http://pyqt.sourceforge.net/Docs/PyQt5/signals_slots.html I can use queued connections but I haven't found an example how to implement it.

1 Answer 1

1

PyQt5.QtCore.Qt.QueuedConnection may help. Just replace

self.asyncFuncSignal.connect(self.asyncFunc)

with

from PyQt5.QtCore import Qt

...

self.asyncFuncSignal.connect(self.asyncFunc, Qt.QueuedConnection)
Sign up to request clarification or add additional context in comments.

3 Comments

how would you do this if the asyn function was called from a button?
I guess at least you can call .emit() of your signal variable inside of another function bounded to the button in the standard way. Haven't you tried it yet?
I just came back to this and this no longer seems to work - at least i just tried the code 1:1 with Python 3.8.6 and PyQt5 5.15.6 - the label starts empty, freezes for 2 seconds and then shows "done"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.