[Qt-interest] Basic QThread question

Andre Somers andre at familiesomers.nl
Tue Apr 27 09:47:46 CEST 2010


On 27-4-2010 9:14, Phil wrote:
> Thank you for reading this.
>
> This is the basic situation.
>
> My main class polls a hardware device every second which returns an int
> value. The hardware device is slow and so the GUI is blocked for about half a
> second each second.
>
> To overcome the blocking, the hardware class is now sub-classed from
> QThread and has a function similar to the following as well as a run()
> function:
>
> int hardware::getValue()
> {
>      return x;
> }
>
> I can see that the run() function starts each second and then stops as it
> should.
>
> My question is, how do I have run() return the value x? Should I periodically
> call run() from the main class (hardware.run()) which in turn calls getValue()
> which in turn emits a signal to return x to the main class via the signal/slot
> mechanism?
>
> It seems a bit convoluted, perhaps there is a more practical method?
>
>    
There are many options. I'll mention two. Based your current setup 
(subclassing from QThread), you could simply add a signal with the int 
value to your subclassed Thread class, and emit that. You can connect to 
this signal from your main thread. Note that you can have your thread 
have it's own eventloop. That means that you can create an instance of 
your hardware class from the thread's run function. You can then make 
getValue a public slot that you call periodically, and have getValue 
send a signal for each new value it finds.

An alternative setup, would be to ditch your own QThread, and use 
QtConcurrent::run instead. You can use a QFutureWatcher on the QFuture 
that QtConcurrent::run returns to get a signal that the function 
returned. In this case, you would have to trigger this run function 
periodically from somewhere though.

My preference would be to create a class that encapsulates all the 
components you need: the timer, the thread to run the hardware poll, and 
the hardware poll itself.

André




More information about the Qt-interest-old mailing list