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

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

2011-12-29 12:04 639 查看
# -*- coding: utf-8 -*-

import sys, time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
x = 0
class Window(QWidget):
def __init__(self, parent = None):
QWidget.__init__(self, parent)
self.thread = Worker()

# 提示信息
self.xLable = QLabel("Number of xTimes:")
# 下拉框
self.spinBox = QSpinBox()
self.spinBox.setMaximum(100)
self.spinBox.setValue(10)
self.startButton = QPushButton(self.tr("&Start"))
# 布局
layout = QGridLayout()
layout.addWidget(self.xLable, 0, 0)
layout.addWidget(self.spinBox, 0, 1)
layout.addWidget(self.startButton, 0, 2)
self.setLayout(layout)
# 标题
self.setWindowTitle(self.tr("Threading"))

# 信号
self.connect(self.thread, SIGNAL("finished()"), self.finishSend)
self.connect(self.thread, SIGNAL("update(int)"), self.updateGUIStatus)
self.connect(self.startButton, SIGNAL("clicked()"), self.sendAdvMail)

def sendAdvMail(self):
self.spinBox.setReadOnly(True)
self.startButton.setEnabled(False)
#传递值到线程中
self.thread.render(self.spinBox.value())

def updateGUIStatus(self, leftTime):
self.xLable.setText(str(leftTime))

def finishSend(self):
self.spinBox.setReadOnly(False)
self.startButton.setEnabled(True)

class Worker(QThread):
def __init__(self, parent = None):
QThread.__init__(self, parent)
self.exiting = False
self.xTimes = 0

def __del__(self):
self.exiting = True
self.wait()

def render(self, xTimes):
self.xTimes = xTimes
self.start()

def run(self):
# Note: This is never called directly. It is called by Qt once the
# thread environment has been set up.
n = self.xTimes
while not self.exiting and n > 0:
time.sleep(1)
#该信号引起界面更新
n -= 1
self.emit(SIGNAL("update(int)"), n)

if __name__ == "__main__":
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())


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