Threading in PyQt
-
26-05-2021 - |
Frage
I am developing a software which has a virtual piano and that can be controlled by a midi keyboard. What I'm trying to do is I want a thread watching the midi inputs ans when there is a data coming corresponding process should be triggered ( here playing the sound and animating the key). How can I do it with Qt Threading and events?
Lösung
Here is a good page on how to use custom signals: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/new_style_signals_slots.html
- Old style: http://pyqt.sourceforge.net/Docs/PyQt4/old_style_signals_slots.html
- New style: http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html
And here is a page showing how to use QThread: http://joplaete.wordpress.com/2010/07/21/threading-with-pyqt4/
Thats pretty much all you need. You create the QThread with a run() function that will loop and monitor your midi port, and then emit a custom signal. You would start this thread with your application launch. And you would connect the QThread's custom signal that you created to a handlers on your main app or whatever widget should be notified.
Andere Tipps
Here you have small example:
import time
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import SIGNAL, QObject
class DoSomething(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
def run(self):
time.sleep(3)
self.emit(SIGNAL('some_signal'))
def signalHandler():
# We got signal!
print 'Got signal!'
sys.exit(0)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
# Create new thread object.
d = DoSomething()
# Connect signalHandler function with some_signal which
# will be emited by d thread object.
QObject.connect(d, SIGNAL('some_signal'), signalHandler, QtCore.Qt.QueuedConnection)
# Start new thread.
d.start()
app.exec_()