Сервис недоступен

Наконец-то я найду ответ на свой вопрос в следующем блоге:

https://martinfitzpatrick.name/article/multithreading-pyqt-applications-with-qthreadpool/

это действительно отличный учебник, после ознакомления с документацией в блоге я смог изменить один из примеров, чтобы изменить текст элемента управления меткой в ​​режиме реального времени; вот окончательный код:

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import time

class Worker(QRunnable):
    def __init__(self, fn, *args, **kwargs):
        super(Worker, self).__init__()        
        self.args = args
        self.kwargs = kwargs
        self.fn = fn

    @pyqtSlot()
    def run(self):
        #print(self.args, self.kwargs)
        print("Thread start") 
        time.sleep(0.2)
        self.fn(*self.args, **self.kwargs)  #ejecuta la funcion recibida


class MainWindow(QMainWindow):


    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.threadpool = QThreadPool()
        print("Multithreading with maximum %d threads" % self.threadpool.maxThreadCount())

        self.counter = 0

        layout = QVBoxLayout()

        self.l = QLabel("Start")
        self.l2 = QLabel("xxxxx")
        b = QPushButton("DANGER!")
        b.pressed.connect(self.oh_no)

        layout.addWidget(self.l)
        layout.addWidget(self.l2)
        layout.addWidget(b)

        w = QWidget()
        w.setLayout(layout)

        self.setCentralWidget(w)

        self.show()

        self.etiqueta="rrrrrrrrrr"

        self.timer = QTimer()
        self.timer.setInterval(500)
        self.timer.timeout.connect(self.recurring_timer)
        self.timer.start()

    def oh_no(self):
        self.etiqueta="hhhhhhhhhhhhhhhhh"
        worker = Worker(self.execute_this_fn,'4444')
        self.threadpool.start(worker)

    def recurring_timer(self):
        self.counter +=1
        self.l.setText("Counter: %d" % self.counter)


    def execute_this_fn(self,x):
        print("Hello!")
        self.l2.setText(x)


app = QApplication([])
window = MainWindow()
app.exec_()

0
задан user7705245 19 January 2019 в 10:12
поделиться