尝试学习QThread。我希望此按钮在启动时启动计时器,并在5秒钟后将文本更改为“已停止”。
如果运行此命令,则5秒钟后我收到一条消息,提示Python已崩溃。我做错什么了吗?
终止()后跟运行()是可接受的方法吗?看来行得通,因为如果我不断按下按钮,应用程序将不会崩溃
import sys
import time
from PySide.QtGui import QPushButton, QApplication
from PySide.QtCore import SIGNAL, QThread
class testThread(QThread):
def __init__(self):
QThread.__init__(self)
self.timeout = SIGNAL('timeout')
def __del__(self):
self.wait()
def run(self):
time.sleep(5)
self.emit(self.timeout, 'from thread')
class testButton(QPushButton):
def __init__(self):
super(testButton, self).__init__()
self.setText('Running...')
self.timer = testThread()
self.connect(self.timer, self.timer.timeout, self.timeout)
self.clicked.connect(self.resetTimer)
self.timer.start()
def timeout(self):
self.setText('Stopped')
def resetTimer(self):
self.timer.terminate()
self.setText('Running...')
self.timer.start()
if __name__=='__main__':
app = QApplication(sys.argv)
button = testButton()
button.show()
button.raise_()
sys.exit(app.exec_())
更新-将SIGNAL切换为Signal即可。很好奇为什么。这是改变的地方
testThread:
class testThread(QThread):
timeout = Signal(str)
def __init__(self):
QThread.__init__(self)
def __del__(self):
self.wait()
def run(self):
time.sleep(5)
self.timeout.emit('')
与信号连接testButton
self.timer.timeout.connect(self.timeout)