从主函数向线程发送信号? [英] Sending a signal from main function to a thread?

查看:152
本文介绍了从主函数向线程发送信号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Pyqt4在python中制作GUI.我想将信号从主GUI发送到线程以执行功能.我知道如何将信号从线程发送到主GUI,但我不知道相反的事情.我也想通过信号传递变量.

I am using Pyqt4 to make GUI in python. I want to send a signal from the main GUI to a thread in order to make a function. I know how to send a signal from thread to the main GUI but I don't know the reverse thing. Also I want to pass an variable with signal.

类似:

class MainGUI()
     def function
         value = 5
         self.emit(QtCore.Signal("Signal(int)"),value)


class thread(QtCore.QThread)
     def _init_(self)
          Qtcore.QThread._init_()
          self.connect(Qt.SIGNAL("Signal(int)"),self.run())

     def run(self,value):
         time.sleep(value)

因此,每当从主GUI发送信号时,我都希望在线程中并行运行该功能而不冻结GUI.

So every time that the signal is transmitted from the main GUI I want to run the function in the thread in parallel without freezing the GUI.

任何帮助,我们将不胜感激, 喷射

Any help would be appreciated, Jet

推荐答案

正确的方法是创建将被移动到线程的对象.您不需要子类

The proper way is to create object which will be moved to thread. You don't need to subclass QtCore.QThread!

类似的东西(免责声明:我比Python多C ++)

More or less something like that (disclaimer: I'm more C++ than Python):

myThread = QtCore.QThread()
testObject = YourClassWithSlots() # NO PARENT HERE
testObject.moveToThread(myThread)
myThread.start()

从那时起,所有连接的testObject插槽(具有默认的连接类型)将在线程myThread中运行.

From that point all connected slots of testObject (with default connection type) will be run in thread myThread.

有用的链接:

  • http://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/
  • http://doc.qt.io/qt-5/qt.html#ConnectionType-enum
  • http://doc.qt.io/qt-5/qobject.html#moveToThread

更多细节请@Ezee

More details to please @Ezee

class YourClassWithSlots(QtCore.QObject) :
    @Slot(int)
    def havyTaskMethod(self, value) :
         # long runing havy task
         time.sleep(value)

self.myThread = QtCore.QThread(self)
self.testObject = YourClassWithSlots() # NO PARENT HERE
self.testObject.moveToThread(myThread) # this makes slots to be run in specified thread
self.myThread.start()
self.connect(Qt.SIGNAL("Signal(int)"), self.testObject.havyTaskMethod)

这篇关于从主函数向线程发送信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆