简体   繁体   English

PyQt4:继承QThread

[英]PyQt4: inheriting QThread

I have a QWidget which calls some python code using a QThread . 我有一个QWidget ,使用QThread调用一些python代码。 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. 在这个课程中,我想将信号传递给我的QWidget ,以便打印“Hello World”。 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. 现在的代码给出了错误sm instance has no attribute 'sayHello' ,我知道 - 我只是很无知如何让run方法调用一个不同的类,以便所有信号都能正常工作。

widget.py 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 prog.py

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

sm.py 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. 我不得不稍微更改你的代码以使其在我的机器上运行,但手动将信号实例传递给sc类肯定会提高信号。 The output may be interleaved with the printing of the i loop. 输出可以与i循环的打印交错。

widget.py 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 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 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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