Python + instance sub-thread updates the UI interface PyQT5

Today small for everyone to share examples of child threads update the UI interface of a Python + PyQT5 has a good reference value, we want to help. Come and see, to follow the small series together
sub-thread can not update the UI interface, in terms of the mobile terminal. Visit the Android UI is not locked, multiple threads can simultaneously access the same update UI controls. That is among the UI when accessed, android system controls are not thread-safe, which will result in multi-threaded mode, prone to uncontrollable common error when multiple threads access the same update UI controls. So Android provisions can only access the UI in the UI thread, access to the Android UI equivalent from another angle plus lock, a pseudo-lock.

QThread in use in PyQT5

from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import time
  
#继承QThread
  
class Mythread(QThread):
  # 定义信号,定义参数为str类型
  breakSignal = pyqtSignal(int)
  
  def __init__(self, parent=None):
    super().__init__(parent)
    # 下面的初始化方法都可以,有的python版本不支持
    # super(Mythread, self).__init__()
  
  def run(self):
      #要定义的行为,比如开始一个活动什么的
  
      for i in(1,1000):
  
        print(i)
        self.breakSignal.emit(i)
       
  
  
if __name__ == '__main__':
  app = QApplication([])
  dlg = QDialog()
  dlg.resize(400, 300)
  dlg.setWindowTitle("自定义按钮测试")
  dlgLayout = QVBoxLayout()
  dlgLayout.setContentsMargins(40, 40, 40, 40)
  btn = QPushButton('测试按钮')
  dlgLayout.addWidget(btn)
  dlgLayout.addStretch(40)
  dlg.setLayout(dlgLayout)
  dlg.show()
  
  
  def chuli(a):
    # dlg.setWindowTitle(s)
    btn.setText(str(a))
  
  # 创建线程
  thread = Mythread()
  # # 注册信号处理函数
  thread.breakSignal.connect(chuli)
  # # 启动线程
  thread.start()
  dlg.exec_()
  app.exit()

Refresh UI may be similar in python using message passing mechanism.

Variable may be modified in the main thread child thread, the main thread and draw read a variable manner.
We recommend the python learning sites to see how seniors are learning! From basic python script, reptiles, django, data mining, programming techniques, as well as to combat zero-based sorting data items, given to every love learning python small partner! Python veteran day have to explain the timing of technology, to share some of the ways to learn and need to pay attention to small details, click python learners to join our gathering

Python + above this instance the child thread to update the UI interface PyQT5 is small series to share the entire contents of everyone, and I hope to give you a reference

Published 51 original articles · won praise 17 · views 30000 +

Guess you like

Origin blog.csdn.net/haoxun02/article/details/104418910