在pyqt5中使用qthread的时候,要注意把所有qthread的对象在主类中的init(或者放在所有类函数的外面)中进行实例化,不然可能在多个qthread互相调用的时候,emit重复的信号。一般比较正确的写法如下所示,基本照着这种框架搭建都是没问题的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
# -*- coding: utf-8 -*- import sys import time from pyqt5.qtwidgets import * from pyqt5.qtcore import * class mainui(qwidget): def __init__( self ): super (mainui, self ).__init__() self .resize( 400 , 200 ) self .setwindowtitle( 'qthread例子' ) # 实例化多线程对象 self .thread = worker() # 实例化列表控件与按钮控件 self .listfile = qlistwidget() self .btnstart = qpushbutton( '开始' ) self .btn_over = qpushbutton( '结束' ) # 把控件放置在栅格布局中 layout = qgridlayout( self ) layout.addwidget( self .listfile, 0 , 0 , 1 , 2 ) layout.addwidget( self .btnstart, 1 , 0 ) layout.addwidget( self .btn_over, 1 , 1 ) # 信号与槽函数的连接 self .btnstart.clicked.connect( self .slotstart) self .btn_over.clicked.connect( self .slot_btn_over) # 建立线程信号的槽连接 self .thread.trigger.connect( self .slotadd) def slotadd( self , msg): print (msg) if int (msg) % 2 = = 0 : self .listfile.additem(msg) else : pass self .thread.exit() def slotstart( self ): self .btnstart.setenabled(false) self .thread.start() def slot_btn_over( self ): self .btnstart.setenabled(true) self .thread.terminate() self .thread.num = 0 class worker(qthread): trigger = pyqtsignal( str ) num = 0 def __init__( self ): super (worker, self ).__init__() def run( self ): while true: print ( 'num= ' , self .num) if self .num % 2 = = 0 : self .trigger.emit( str ( 50 )) elif self .num = = 200 : self .num = 0 else : pass time.sleep( 0.1 ) self .num + = 1 if __name__ = = '__main__' : app = qapplication(sys.argv) w = mainui() w.show() sys.exit(app.exec_()) |
以上这篇pyqt5中qthread在使用时出现重复emit的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/shangxiaqiusuo1/article/details/90678857