I am new to pyqt, so I hope that there’s nothing wrong with what I'm trying to do. I tried to create an interaction between QThreads using PyQt signals. In particular, what I would like to do is to emit a signal from a stream, and this signal must interrupt what the stream does to run a particular method. By the way, I have problems with this, so I wonder if what I'm trying to do is legal.
For example, now I was trying to do something like this:
import sys
import time
from PyQt4 import QtGui as qt
from PyQt4 import QtCore as qtcore
from PyQt4.QtCore import QThread
import threading
app = qt.QApplication(sys.argv)
class widget(qt.QWidget):
def __init__(self, parent=None):
qtcore.QObject.__init__(self)
def appinit(self):
self.mysignal = qtcore.SIGNAL("mysignal")
thread = mythread(self)
thread.start()
time.sleep(5)
print "before emit",str(threading.current_thread())
self.emit(self.mysignal,"hello, I'm thread "+str(threading.current_thread()))
print "after emit",str(threading.current_thread())
class mythread(QThread):
def __init__(self,parent):
qtcore.QThread.__init__(self, parent=app)
self.parent=parent
def run(self):
self.mysignal = qtcore.SIGNAL("mysignal")
self.connect(self.parent, self.mysignal, self.myfunc)
for i in range(15):
print "**",threading.current_thread(),i
time.sleep(1)
def myfunc(self, msg):
print threading.current_thread(), msg, "Enter"
time.sleep(5)
print threading.current_thread(), msg, "Exit"
def main():
mywidget = widget()
mywidget.show()
qtcore.QTimer.singleShot(0, mywidget.appinit)
sys.exit(app.exec_())
main()
The output I get is:
** <_DummyThread(Dummy-1, started daemon 1968)> 0
** <_DummyThread(Dummy-1, started daemon 1968)> 1
** <_DummyThread(Dummy-1, started daemon 1968)> 2
** <_DummyThread(Dummy-1, started daemon 1968)> 3
** <_DummyThread(Dummy-1, started daemon 1968)> 4
before emit <_MainThread(MainThread, started 2928)>
<_MainThread(MainThread, started 2928)> hello, I'm thread <_MainThread(MainThread, started 2928)> Enter
** <_DummyThread(Dummy-1, started daemon 1968)> 5
** <_DummyThread(Dummy-1, started daemon 1968)> 6
** <_DummyThread(Dummy-1, started daemon 1968)> 7
** <_DummyThread(Dummy-1, started daemon 1968)> 8
** <_DummyThread(Dummy-1, started daemon 1968)> 9
<_MainThread(MainThread, started 2928)> hello, I'm thread <_MainThread(MainThread, started 2928)> Exit
after emit <_MainThread(MainThread, started 2928)>
** <_DummyThread(Dummy-1, started daemon 1968)> 10
** <_DummyThread(Dummy-1, started daemon 1968)> 11
** <_DummyThread(Dummy-1, started daemon 1968)> 12
** <_DummyThread(Dummy-1, started daemon 1968)> 13
** <_DummyThread(Dummy-1, started daemon 1968)> 14
, mythread myfunc. , mythread , myfunc . ( ), .
, , , , . - ? , .