PDA

View Full Version : Thread..:/



Molier
5th December 2010, 01:59
I still make frist steps with Threads, however i know how they work.

I have a strange situation:


- MainWindow which based on (inherits) QMainWindow (this class contains method calculate(), and variable bool StartStop)

Variable StartStop is steered by button (on/off).

I want use calculate method when i click on a button.
Unfortunately calculate method is not so short. So calculate() takes some time, and GUI of program does not respond.
Is there any nice opportunity to put a thread which is sensitive for StartStop variable?
Note that this is only one class. Moreover calculate() operates on some variables of MainWindow class.
I was thinking of emitting signals. Any other ideas?

tbscope
5th December 2010, 06:29
Create a qobject based subclass that contains the signals and slots you want. Implement the complete calculation code inside this qobject subclass.

In your main window, create an object based on this subclass (the calculation object).
Connect all the signals and slots of the calculation object to your mainwindow object or other objects
Then create a new empty qthread object.
Move the calculation object to the new thread.
Start the new thread.

The on/off button can be connected to the thread start/stop slots or the calculation object itself. You have to see whatever makes more sense.

Alternatively, you can use QtConcurrent.

Molier
5th December 2010, 19:25
That is pretty nice idea (however it took some for me to seperate blocks of code and organize them in other way).

So now i have:

-class MainWindow (contains Draw member)
-class engine (resposible for some network data streaming and writing into files)
-class Draw (which inherits engine and QObject) - resposible for drawing and contains QGraphicsScene member.

Class Draw has SLOT: loop().


void Draw::loop()
{
while(1){
for(int a=0;a<200;a++){
for(int b=0;b<8;b++)inttab[b]=b;calculate();}
}

}


MainWindow constructor contains this:




MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{


grafika=new Draw();
connect(ui->actionStart,SIGNAL(triggered()),grafika,SLOT(loop( ))); // this line makes program terminated, why?
this->moveToThread(&watek); //there is a member QThread watek
//....etc.

}

wysota
5th December 2010, 23:25
You are moving a widget to a thread? That is bound to fail.

Molier
6th December 2010, 04:11
U r right in deed.