python multithreaded programming: On PyQt5 asynchronous refresh UI and multi-threaded Python summary

Today small for everyone to share a UI refresh On PyQt5 asynchronous and multi-threaded Python summary, a good reference value, we want to help. Come and see, to follow the small series together
currently need to do a task interface program, PyQt is a very convenient option, QT rich controls and python programming convenience. Recent cases encountered when performing background tasks interface interface stuck to solve the case here records.

PyQt

About PyQt

PyQt is a python interface to Qt, PyQt fewer documents, but the interface and functions can be totally based Qt, we inherited a lot of control and signaling mechanisms in Qt, very convenient. Following introduction of a basic PyQt program.

  • It is imported from three principal package

  • from PyQt5.QtWidgets import common controls

  • PyQt5.QtCore core functional class, such as QT, QThread, pyqtSignal

  • PyQt5.QtGui UI classes, such as QFont

  • Basic structure of the program:

- class Example(QWidget):
 def __init__(self):
  super()__init__()
  self.setupUI()
 
 def setupUI():
  self.show()
  pass
  # 设置UI
if __name__ == '__main__':
 app = QApplication(sys.argv) # 启动app
 ex = Example() # 实例化一个自己派生的
 # 也可以实例化库中的控件
 # q = QPushButton()
 # q.show()
 sys.exit(app.exec_())

In general:

  1. First examples of APP

  2. Examples of predefined controls derived from the library or their own controls, remember to call the show () function

  3. Execution and Safety Exit

Python Multithreaded

python multithreading more convenient to use, mainly used threading.Thread categories:

  1. Thread started using the start () function

  2. If you need to wait for a thread of execution using join, so that the main thread is blocked

Implementation of a

Directly into the function, start threads, you can pass parameters

import time, threading
def threadFunction():
 while True:
  print(11111)
  time.sleep()
# 用于命名,可以通过threading.current_thread().name获得
t = threading.Thread(target=threadFunction, name='funciton')
# 如果线程有参数
t = threading.Thread(target=threadFunction, args=(), name='funciton')
t.start()

Implementation of the two

Inherited Thread, override the run method

from threading import Thread
import time
 
class Example(Thread):
 def __init__(self):
  super().__init__()
 
 def run(self):
  while True:
   time.sleep(1)
   print(11111111)
 
if __name__ == '__main__':
 a = Example()
 a.start()
 a.join()
 print(222222222)

note:

  1. The method makes use join the main thread is blocked here, waiting for child thread end, in which you can set the blocking time

  2. a.setDaemon (True) before setting the start, we can ensure that upon termination of the main thread, the child thread also terminated

Signaling mechanism

Signaling mechanism in QT can write callback convenient.

  1. Many such control signals have a predetermined clicked, clicked.connect directly connected to the slot function.

  2. Qt inherited from class, then a custom class variable signal, the connection signal instances it

. lass Example(QWidget):
 signal = pyqtSignal() # 括号里填写信号传递的参数
 # 发射信号
 def func(self):
  self.signal.emit()
 
# 使用信号
a = Example()
a.signal.connect(callback)
 
# 槽函数
def callback():
 pass

UI revamp

In the interface, usually there will be some button, when clicked, trigger events, such as to download a file or do some operations that will be time-consuming, if not finished in time, the main thread will block, so the interface will appear not responding state, so you must use multiple threads to solve this problem.

We recommend learning Python buckle qun: 774711191, look at how seniors are learning! From basic web development python script to, reptiles, django, data mining, etc. [PDF, actual source code], zero-based projects to combat data are finishing. Given to every little python partner! Every day, Daniel explain the timing Python technology, to share some of the ways to learn and need to pay attention to small details, click on Join us python learner gathering
attention:

  1. PyQt5 not refresh thread in the child thread, this will cause the interface card dead, and therefore can not use the conventional multi-threaded refreshed UI.

  2. But it must be to achieve communication between the child thread and the main thread, otherwise it is impossible to know whether the task is completed. So use PyQt5 in QThread, so that both can use the signaling mechanism, but also be able to use multiple threads.

  3. When the multi-thread starts, registration signal, the function and the function in the slot in the thread, when the task is completed, the transmitted signal, in the main thread to update the UI.

Note: Due need to register signals, thread need to be inherited from the class QThread

class Example(QThread):
 signal = pyqtSignal() # 括号里填写信号传递的参数
 def __init__(self):
  super().__init__()
 
 def __del__(self):
  self.wait()
 
 def run(self):
  # 进行任务操作
  self.signal.emit() # 发射信号
 
# UI类中
def buttonClick(self)
 self.thread = Example()
 self.thread.signal.connect(self.callback)
 self.thread.start() # 启动线程
 
def callbakc(self):
 pass

If wrong, please correct me -

On PyQt5 over this asynchronous refresh UI and multi-threaded Python is a summary of the entire contents of a small series for everyone to share

Published 35 original articles · won praise 9 · views 10000 +

Guess you like

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