Jetmir
Jetmir

Reputation: 21

Sending a signal from main function to a thread?

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.

something like:

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)

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

Upvotes: 1

Views: 1664

Answers (1)

Marek R
Marek R

Reputation: 37667

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

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()

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

Useful links:


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)

Upvotes: 1

Related Questions