简体   繁体   中英

Communicate from Main Application Thread to Seperate QThread

I have this basic app working. It creates a new thread, and starts it. Then it uses signals to communicate back to the main thread for something else to happen.

My question is how do I pass data from the main thread to the new thread that is created, this part really doesn't make sense to me. Or is there another way altogether to do threading back and forth. Essentially the main thread and the new thread will run for the entire life of the application, so they need to communicate back and forth.

As a note I am a web developer so native apps are new to me. Also I am still new to qt and pyqt so not sure how to do this.

import sys

from PyQt4 import QtGui
from PyQt4.QtCore import QThread, pyqtSignal


class Thread(QThread):
    message_recieved = pyqtSignal(object)

    def run(self):
        self.message_recieved.emit('hello')

class Main(QtGui.QMainWindow):
    def __init__(self, parent = None):
        QtGui.QMainWindow.__init__(self,parent)

        self.initUI()

        self.thread = Thread()
        self.thread.message_recieved.connect(self.message)
        self.thread.start()

    def message(self, msg):
        print msg

    def initUI(self):
        self.setGeometry(100, 100, 800, 600)
        self.setWindowTitle("Test App")

def main():
    app = QtGui.QApplication(sys.argv)

    main = Main()
    main.show()

    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

You shouldn't subclass QThread . You should have a worker sent on the thread you created. Have a look at this link to get best practices regarding threading in Qt: http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/ The example is in C++, but can be easily translated to Python. Good luck!

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