QThread finished () signal is never highlighted

Since I have a worker class that has 2 slots: StartWork () and StopWork (), then StartWork () alone runs an infinite loop (it just reads and reads the input camera non-stop) and the StopWork () method simply sets the bool variable to false (therefore, the loop inside StartWork () stops).

according to the QThread documentation, the best way to use them now is not to subclass, but to move workers to a thread, so what I do. the problem is that the start () signal from the stream is called, but the completed () signal is never called.

working class slots:

void StartWork () {running = true; while (works) {do work; }}

void StopWork () {running = false; }

QThread initialization and signal / slot connection:

thread = new QThread(); worker = new Worker(); worker.moveToThread(thread); QObject::connect(thread, SIGNAL(started()), worker, SLOT(StartWork())); QObject::connect(thread, SIGNAL(finished()), worker, SLOT(StopWork())); 

and on my QPushButton I do this:

 if(pushStartStop->text().toLower() == "start") { pushStartStop->setText("Stop"); thread->start(); } else { pushStartStop->setText("Start"); thread->quit(); } 

threaded> start () works fine, and StartWork () is called and everything is beautiful (the GUI works without blocks, etc.).

but thread-> quit () does nothing, it is called (because the button changes the text), but that's it. if I just call worker-> StopWork (), it works, but then I can not start it again.

I tried with thread-> exit (); but the results are the same. Also, I know that a subclass works, but it looks more ugly, and according to recent Qt documentation, the subclass is not optimal.

early.

+2
source share
1 answer

You have a forever loop:

 void StartWork() { running = true; while(running) { do work; } } 

This function will loop, so the thread's event loop is blocked right after the started() emitted. Thus, finished() cannot be selected.

Solution 1:

Add function

 void DoWork() { if(running) { do work } } 

For the worker and change

 void StartWork() { running = true; } 

Then just connect DoWork to the timer in the stream.

Solution 2:

Change function

 void StartWork() { running = true; while(running) { do work; QCoreApplication::processEvents(); } } 

With this solution, you will have to restart the thread when the worker stops his task ( StopWork() forces this function to end, so the event loop will not process events and the thread will be completed).

+5
source

Source: https://habr.com/ru/post/1446560/


All Articles