[PyQt] Update GUI Table using QThread
sda at fstab.net
Fri Sep 1 13:51:50 BST 2017
On 2017-09-01 06:52, Hitesh Patel wrote:
> We are developing our control and monitoring system GUI using PyQt
> which require to handle big table so Qt main thread has to spent
> considerable time to create table which eventually hang the GUI.
What takes so long to update the table? Database or other network
requests? CPU intensive calculations?
> Can we update Qt table using QThread ?
Sure, signals and slots are used to not only connect between objects in
a single thread but are also able to safely cross thread boundaries.
Make sure you understand threading hazards related to multiple objects
in different threads accessing the same objects. Also, don't call any
GUI functions from threads, only interact by way of signals and slots
which were connected prior to moving the objects to different threads.
A pet peeve of mine is that people should first learn threads without
inheriting from QThread or threading.Thread. While sometimes inheriting
can be argued to be simpler I don't feel it helps to understand what is
going on. In other words, I recommend the first example, not the
Now back to the questions I started with. While threads in Python
certainly are 'real' threads, they do have limitations not present in
the same way as threads in C/C++, for example. Python has a Global
Interpreter Lock (GIL) which restricts there to only be one thread at a
time accessing Python objects. This means that unless you use good
C-extension modules for CPU intensive activities, your Python code will
never have more than one CPU worth of processor time. Moving a CPU
intensive activity to another thread can still sort of maintain GUI
responsiveness but it's not really great. If you're spending more time
waiting on blocking I/O calls such as network requests it can be
valuable to look into async frameworks such as asyncio and Twisted. I
personally use Twisted for all the CANbusnetworking in my PyQt5
application (serial at some point soon as well). I use qt5-reactor to
integrate the Twisted and Qt event loops. I do also have a thread
(spawned through Twisted actually) that does some more CPU intensive
activity to generate a model for a tree view but the progress bar in the
GUI is still not smooth during that time.
Let us know more details and we can try to offer more specific advice.
More information about the PyQt