Günlük

PyQt5 qthread example Düzenle


12 Nisan 2020 17:08 tarihinde Mehmet Özgür Bayhan tarafından yazılmıştır.


We are creating a worker.py file wihch is our threaded part:

# worker.py
from PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import time


class Worker(QObject):
    finished = pyqtSignal()
    intReady = pyqtSignal(int)


    @pyqtSlot()
    def procCounter(self): # A slot takes no params
        for i in range(1, 100):
            time.sleep(1)
            self.intReady.emit(i)

        self.finished.emit()

And the main window part which is our main thread running in main.py file

# main.py
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QGridLayout
import sys
import worker


class Form(QWidget):


    def __init__(self):
        super().__init__()
        self.label = QLabel("0")
 
        # 1 - create Worker and Thread inside the Form
        self.obj = worker.Worker()  # no parent!
        self.thread = QThread()  # no parent!

        # 2 - Connect Worker`s Signals to Form method slots to post data.
        self.obj.intReady.connect(self.onIntReady)

        # 3 - Move the Worker object to the Thread object
        self.obj.moveToThread(self.thread)

        # 4 - Connect Worker Signals to the Thread slots
        self.obj.finished.connect(self.thread.quit)

        # 5 - Connect Thread started signal to Worker operational slot method
        self.thread.started.connect(self.obj.procCounter)

        # * - Thread finished signal will close the app if you want!
        # self.thread.finished.connect(app.exit)

        # 6 - Start the thread
        self.thread.start()

        # 7 - Start the form
        self.initUI()


    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)
        grid.addWidget(self.label, 0, 0)

        self.move(300, 150)
        self.setWindowTitle('thread test')
        self.show()


    def onIntReady(self, i):
        self.label.setText("{}".format(i))
        # print(i)


app = QApplication(sys.argv)

form = Form()

sys.exit(app.exec_())

The only connection between worker and main is via emit and pyqtSignal. This is the critical part (çokomelli)

 

 

Reference: https://stackoverflow.com/a/33453124


Yorum Yazın:


Arama

Arşivler

  • 2020 (4)
    • Temmuz (1)
    • Nisan (2)
    • Şubat (1)
  • 2019 (1)
    • Mart (1)
  • 2018 (7)
    • Aralık (1)
    • Kasım (5)
    • Şubat (1)
  • 2017 (4)
    • Kasım (1)
    • Haziran (1)
    • Mart (1)
    • Ocak (1)
  • 2016 (18)
    • Aralık (2)
    • Kasım (3)
    • Ağustos (1)
    • Haziran (4)
    • Nisan (1)
    • Mart (1)
    • Şubat (1)
    • Ocak (5)
  • 2015 (10)
    • Eylül (2)
    • Ağustos (5)
    • Mayıs (1)
    • Mart (2)
  • 2014 (21)
    • Aralık (1)
    • Kasım (20)
"Even a man who is pure in heart, and says his prayers by night, may become a wolf when the wolfbane blooms, and the autumn moon is bright."

Listen Me!