PyQt子線程處理業(yè)務(wù)事件的問題解決
在PyQt中是不推薦使用UI主線程來處理耗時(shí)操作的,會(huì)造成窗口組件阻塞。耗時(shí)操作一般放在子線程中。子線程處理完成后,可能需要更新窗口組件,但是PyQt不推薦使用子線程來更新主線程(也不是不能更新),這就用到了信號(hào)槽機(jī)制來更新主線程。
- 在QObject的一個(gè)子類中創(chuàng)建一個(gè)信號(hào)(
PyQt5.QtCore.pyqtSignal
)屬性 - 將這個(gè)信號(hào)屬性和其他類中的函數(shù)綁定,綁定的這個(gè)函數(shù)叫做整個(gè)信號(hào)的槽函數(shù)。一個(gè)信號(hào)可以和多個(gè)槽函數(shù)綁定。
- 該信號(hào)發(fā)出時(shí),就會(huì)調(diào)用對(duì)應(yīng)的槽函數(shù)
可能會(huì)有疑問,槽函數(shù)被執(zhí)行時(shí)所在的線程和發(fā)送信號(hào)的線程是不是同一個(gè)?
需要注意,信號(hào)一定義在QObject或其子類中。調(diào)用該屬性的emit方法發(fā)出信號(hào)后,和該信號(hào)綁定的槽函數(shù)都將要被調(diào)用,但是調(diào)用的線程并不一定是發(fā)送信號(hào)的這個(gè)線程,這和PyQt中的線程親和性(Thread Affinity)
有關(guān)。
線程親和性(Thread Affinity)
在 PyQt 中,一個(gè)對(duì)象可以被移動(dòng)到不同的線程中,但一個(gè)對(duì)象在同一時(shí)刻只能屬于一個(gè)線程。這是因?yàn)?Qt 使用線程親和性(Thread Affinity)的概念來管理對(duì)象所屬的線程。
每個(gè) Qt 對(duì)象都與一個(gè)特定的線程相關(guān)聯(lián),即它的線程親和性。對(duì)象的線程親和性決定了該對(duì)象的槽函數(shù)是在哪個(gè)線程中執(zhí)行。默認(rèn)情況下,對(duì)象在創(chuàng)建時(shí)會(huì)與創(chuàng)建它的線程相關(guān)聯(lián),但可以使用 moveToThread 方法將對(duì)象移動(dòng)到另一個(gè)線程中。
錯(cuò)誤示例:
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton,QFileDialog from PyQt5.QtCore import QThread,pyqtSignal,QObject import sys, threading class MyWindow(QMainWindow): def __init__(self, parent=None): super(MyWindow, self).__init__(parent) self.button = QPushButton('Hi') self.button.clicked.connect(self.on_click) self.setCentralWidget(self.button) def on_click(self): print("on_click",threading.current_thread().name) self.thread = MyThread(self) self.thread.start() def set_text(self,file_name): print("setText",threading.current_thread().name) self.button.setText(file_name) class MyThread(QThread): def __init__(self,mv:QMainWindow) -> None: super().__init__(None) self.mv = mv def run(self): print('run',threading.current_thread().name) QThread.sleep(5) self.mv.set_text("Hello World") if __name__ == '__main__': app = QApplication([]) window = MyWindow() window.show() sys.exit(app.exec_())
輸出結(jié)果:
on_click MainThread
run Dummy-1
setText Dummy-1 //子線程更新UI,不推薦
使用信號(hào)槽機(jī)制
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton,QFileDialog from PyQt5.QtCore import QThread,pyqtSignal,QObject import sys, threading class MyWindow(QMainWindow): def __init__(self, parent=None): super(MyWindow, self).__init__(parent) self.button = QPushButton('Hi') self.button.clicked.connect(self.on_click) self.setCentralWidget(self.button) def on_click(self): print("on_click",threading.current_thread().name) self.thread = MyThread(self) self.thread.pyqtSignal.connect(self.set_text) self.thread.start() def set_text(self,file_name): print("setText",threading.current_thread().name) self.button.setText(file_name) class MyThread(QThread): pyqtSignal = pyqtSignal(str) def __init__(self,mv:QMainWindow) -> None: super().__init__(None) self.mv = mv def run(self): print('run',threading.current_thread().name) QThread.sleep(5) self.pyqtSignal.emit("Hello World") if __name__ == '__main__': app = QApplication([]) window = MyWindow() window.show() sys.exit(app.exec_())
輸出結(jié)果:
on_click MainThread
run Dummy-1
setText MainThread //更新UI時(shí),執(zhí)行的線程為主線程
setText槽函數(shù)為什么會(huì)被主函數(shù)執(zhí)行,就是因?yàn)榫€程親和性,槽函數(shù)所在對(duì)象和MainThread綁定,當(dāng)然會(huì)被主線程所執(zhí)行。
但是這種將事務(wù)直接寫在run,PyQt5是不推薦的,正確寫法如下
創(chuàng)建一個(gè)類集成QObject,來做業(yè)務(wù)的處理。并將這個(gè)對(duì)象和新創(chuàng)建的線程通過moveToThread綁定,作為這個(gè)對(duì)象的親和線程。將QThread的started信號(hào)和這個(gè)業(yè)務(wù)事件綁定。線程啟動(dòng),發(fā)送started信號(hào),業(yè)務(wù)對(duì)象開始處理業(yè)務(wù),完成之后發(fā)送信號(hào)給主線程槽函數(shù)。
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton,QFileDialog from PyQt5.QtCore import QThread,pyqtSignal,QObject import sys, threading class MyWindow(QMainWindow): def __init__(self, parent=None): super(MyWindow, self).__init__(parent) self.button = QPushButton('Hi') self.button.clicked.connect(self.on_click) self.setCentralWidget(self.button) def on_click(self): print("on_click",threading.current_thread().name) self.thread = QThread() self.myHander = MyHandler() self.myHander.moveToThread(self.thread) self.myHander.pyqtSignal.connect(self.set_text) self.thread.started.connect(self.myHander.handle) self.thread.start() def set_text(self,file_name): print("setText",threading.current_thread().name) self.button.setText(file_name) class MyHandler(QObject): pyqtSignal = pyqtSignal(str) def handle(self): print('handle',threading.current_thread().name) self.pyqtSignal.emit("Hello World") if __name__ == '__main__': app = QApplication([]) window = MyWindow() window.show() sys.exit(app.exec_())
子線程中調(diào)用QFileDialog
如果在子線程中調(diào)用了QFileDialog窗口選擇文件,QFileDialog窗口出現(xiàn)后幾秒后程序會(huì)崩潰,代碼如下
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton,QFileDialog from PyQt5.QtCore import QThread,pyqtSignal,QObject import sys, threading class MyWindow(QMainWindow): def __init__(self, parent=None): super(MyWindow, self).__init__(parent) self.button = QPushButton('Hi') self.button.clicked.connect(self.on_click) self.setCentralWidget(self.button) def on_click(self): print("on_click",threading.current_thread().name) self.thread = MyThread(self) self.thread.pyqtSignal.connect(self.set_text) self.thread.start() def set_text(self,file_name): print("setText",threading.current_thread().name) self.button.setText(file_name) class MyThread(QThread): pyqtSignal = pyqtSignal(str) def __init__(self,mv:QMainWindow) -> None: super().__init__(None) self.mv = mv def run(self): print('run',threading.current_thread().name) file_name = QFileDialog.getOpenFileName(self.mv, '選擇文件', './', 'Excel files(*.xlsx , *.xls)') print(file_name) self.pyqtSignal.emit("Hello World") if __name__ == '__main__': app = QApplication([]) window = MyWindow() window.show() sys.exit(app.exec_())
輸出結(jié)果:
on_click MainThread
run Dummy-1
QObject::setParent: Cannot set parent, new parent is in a different thread
CoCreateInstance failed (操作成功完成。)
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QApplication(0x21fb451d190), parent's thread is QThread(0x21fb443b430), current thread is MyThread(0x21fb8788df0)
CoCreateInstance failed (操作成功完成。)
QObject::startTimer: Timers cannot be started from another thread
問題原因
PyQt中,必須在主線程中來創(chuàng)建子對(duì)象。
到此這篇關(guān)于PyQt子線程處理業(yè)務(wù)事件的問題解決的文章就介紹到這了,更多相關(guān)PyQt子線程內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python開發(fā)圍棋游戲的實(shí)例代碼(實(shí)現(xiàn)全部功能)
圍棋是一種古老而復(fù)雜的策略棋類游戲,起源于中國,已有超過2500年的歷史,本文介紹了如何用Python開發(fā)一個(gè)簡(jiǎn)單的圍棋游戲,實(shí)例代碼涵蓋了游戲的基本規(guī)則、界面設(shè)計(jì)、棋盤實(shí)現(xiàn)、棋子管理、游戲邏輯等多個(gè)方面,通過逐步實(shí)現(xiàn)落子、吃子、判斷勝負(fù)等功能2024-12-12python實(shí)現(xiàn)異步回調(diào)機(jī)制代碼分享
本文介紹了python實(shí)現(xiàn)異步回調(diào)機(jī)制的功能,大家參考使用吧2014-01-01python Aligo庫設(shè)置json路徑使用詳解
這篇文章主要為大家介紹了python Aligo庫設(shè)置json路徑使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11python實(shí)現(xiàn)一個(gè)通用的插件類
插件管理器用于注冊(cè)、銷毀、執(zhí)行插件,本文主要介紹了python實(shí)現(xiàn)一個(gè)通用的插件類,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-04-04Python3爬蟲中Splash的知識(shí)總結(jié)
在本篇文章里小編給大家整理的是關(guān)于Python3爬蟲中Splash的知識(shí)總結(jié)內(nèi)容,需要的朋友們可以學(xué)習(xí)參考下。2020-07-07