Interaction between threads and GUI
-
Dear all,
I'm a newbie in Qt (also in Python) and I'm facing an issue that needs help. I created a desktop application using PyQt5 include:- a socket connection to get data
- a thread to receive data from the socket and parse data to struct (called thread X)
- After parsing data done in thread X, I want to send data and notify to update the main window (GUI) but I don't know how to interact between Python thread and main thread (GUI)
Could you please give me some advice or solutions? Thank you very much
-
@ducdx said in Interaction between threads and GUI:
but I don't know how to interact between Python thread and main thread (GUI)
Using signals/slots.
In your receiver thread emit a signal which is connected to a slot in your GUI.But you should really rethink your design: is there really a need for threads at all? Qt networking (like most of Qt) is assynchronous, so usually there is no need to overcomplicate things with threads.
-
@ducdx
Hello and welcome.Cannot emphasize enough what @jsulm has said about " is there really a need for threads at all?". These days every beginner seems to come here and start out wanting to use threads. Threading is complicated, easy to get wrong, and mostly/often not needed.
Please at least start out with no threads. Do any parsing in the one and only main thread (in a slot). After you have it working, only then consider threading your code. Unless your "parsing" is really reading a lot of data or doing some very heavy computations it probably simply will not require a separate thread.
-
@jsulm Thank you for your answer very much
I am developing an application that connects to a hardware device via a socket. I used thread to receive data. As your idea, do I not need a thread to receive data from the socket? Can I call the recv() function on the main thread, right? -
@ducdx said in Interaction between threads and GUI:
Can I call the recv() function on the main thread, right?
So, you are not using Qt for networking (https://doc.qt.io/qt-5.15/qtnetwork-index.html)?
If not - why?
If you're using blocking calls then of course you need a second thread. But why not simply use Qt for networking? -
@ducdx
Not quite if you choose to userecv()
, because that is a blocking call, and if data is not available it will block interaction with your UI thread if called from there.Normally we do not use such functions from Qt any longer. Consider writing your code to use QTcpSocket instead of low-level socket functions like
recv()
. Then you can use signals and slots to receive and process the data from the main UI thread without needing a separate thread.