您的位置:首页 > 编程语言 > Python开发

【多线程】python界面阻塞,白屏,not responding解决的简单例子

2013-07-23 17:05 543 查看
1 # -*- coding: utf-8 -*-
2
3 import sys, time
4 from PyQt4.QtCore import *
5 from PyQt4.QtGui import *
6 x = 0
7 class Window(QWidget):
8     def __init__(self, parent = None):
9         QWidget.__init__(self, parent)
10         self.thread = Worker()
11
12         # 提示信息
13         self.xLable = QLabel("Number of xTimes:")
14         # 下拉框
15         self.spinBox = QSpinBox()
16         self.spinBox.setMaximum(100)
17         self.spinBox.setValue(10)
18         self.startButton = QPushButton(self.tr("&Start"))
19         # 布局
20         layout = QGridLayout()
21         layout.addWidget(self.xLable, 0, 0)
22         layout.addWidget(self.spinBox, 0, 1)
23         layout.addWidget(self.startButton, 0, 2)
24         self.setLayout(layout)
25         # 标题
26         self.setWindowTitle(self.tr("Threading"))
27
28         # 信号
29         self.connect(self.thread, SIGNAL("finished()"), self.finishSend)
30         self.connect(self.thread, SIGNAL("update(int)"), self.updateGUIStatus)
31         self.connect(self.startButton, SIGNAL("clicked()"), self.sendAdvMail)
32
33     def sendAdvMail(self):
34         self.spinBox.setReadOnly(True)
35         self.startButton.setEnabled(False)
36         #传递值到线程中
37         self.thread.render(self.spinBox.value())
38
39     def updateGUIStatus(self, leftTime):
40         self.xLable.setText(str(leftTime))
41
42     def finishSend(self):
43         self.spinBox.setReadOnly(False)
44         self.startButton.setEnabled(True)
45
46 class Worker(QThread):
47     def __init__(self, parent = None):
48         QThread.__init__(self, parent)
49         self.exiting = False
50         self.xTimes = 0
51
52     def __del__(self):
53         self.exiting = True
54         self.wait()
55
56     def render(self, xTimes):
57         self.xTimes = xTimes
58         self.start()
59
60     def run(self):
61         # Note: This is never called directly. It is called by Qt once the
62         # thread environment has been set up.
63         n = self.xTimes
64         while not self.exiting and n > 0:
65             time.sleep(1)
66             #该信号引起界面更新
67             n -= 1
68             self.emit(SIGNAL("update(int)"), n)
69
70
71 if __name__ == "__main__":
72     app = QApplication(sys.argv)
73     window = Window()
74     window.show()
75     sys.exit(app.exec_())


编辑器加载中...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: