PyQt4:继承QThread

时间:2013-11-22 15:12:44

标签: python pyqt

我有QWidget使用QThread调用一些python代码。这段代码也会做一些逻辑并调用另一个类。在本课程中,我想将信号传递到QWidget,以便打印“Hello World”。它所代表的代码给出了错误sm instance has no attribute 'sayHello',我知道 - 我只是非常无知如何使run方法调用另一个类,以便所有信号都能正常工作。

widget.py

from prog import TaskThread
from PyQt4 import QtCore, QtGui
class MyWidget(QtGui.QWidget):
  def __init__(self):
    self.btn = QtGui.QPushButton('Run!', self)
    self.btn.clicked.connect(self.onStart)
    self.myLongTask = TaskThread()
    self.myLongTask.sayHello.connect(self.sayHi)

  def onStart(self):
    self.myLongTask.start()

  def sayHi(self):
    print "hello world"

prog.py

from PyQt4 import QtCore 
from sm import sc
class TaskThread(QtCore.QThread):
  sayHello = QtCore.pyqtSignal()
  def run(self):
    sm.sc()

sm.py

class sc():
  def __init__(self):
    for i in range(0,50):
      print i
      if i == 5: self.sayHello.emit()

1 个答案:

答案 0 :(得分:3)

我不得不稍微更改你的代码以使其在我的机器上运行,但是手动将信号实例传递给sc类肯定会提高信号。输出可以与i循环的打印交错。

<强> widget.py

from prog import TaskThread
import sys
from PyQt4 import QtCore, QtGui

class flexemWidget(QtGui.QWidget):
  def __init__(self):
    super(flexemWidget, self).__init__()
    self.btn = QtGui.QPushButton('Run!', self)
    self.btn.clicked.connect(self.onStart)
    self.myLongTask = TaskThread()
    self.myLongTask.sayHello.connect(self.sayHi)
    self.show()

  def onStart(self):
    self.myLongTask.start()

  def sayHi(self):
    print "hello world" 

app = QtGui.QApplication(sys.argv)
ex = flexemWidget()
sys.exit(app.exec_())

<强> prog.py

from PyQt4 import QtCore 
from sm import sc
class TaskThread(QtCore.QThread):
  sayHello = QtCore.pyqtSignal()
  def run(self):
    sc(self.sayHello)

<强> sc.py

from PyQt4 import QtCore
class sc():
  def __init__(self, signal):
    for i in range(0,50):
      print i
      if i == 5: signal.emit()