简体   繁体   中英

PyQt4: inheriting QThread

I have a QWidget which calls some python code using a QThread . This code then also does some logic and calls another class. In this class, I want to pass a signal up to my QWidget , so that "Hello World" is printed. The code as it stands gives the error sm instance has no attribute 'sayHello' , which I know - I'm just pretty clueless how to make the run method call a different class so that all the signals work.

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()

I had to change your code slightly to get it to run on my machine but manually passing the signal instance to the sc class definitely raises the signal. The output may be interleaved with the printing of the i loop.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM