简体   繁体   English

从主应用程序线程进行通信以分隔QThread

[英]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. 注意,我是一名Web开发人员,因此原生应用对我来说是新的。 Also I am still new to qt and pyqt so not sure how to do this. 另外我还是qtpyqt新手,所以不确定如何执行此操作。

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 . 您不应该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. 查看此链接以获得有关Qt中线程的最佳实践: http : //mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/示例使用C ++,但可以轻松转换为Python。 Good luck! 祝好运!

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

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