I have a simple form UI that has a slot for a button, starting a thread:
void MainWindow::LoadImage()
{
aThread->run();
}
And the run() method looks like this:
void CameraThread::run()
{
qDebug("Staring Thread");
while(1)
{
qDebug("ping");
QThread::sleep(1);
}
}
When I click the button that calls LoadImage(), the UI becomes unresponsive. I periodically see the “ping” message as the debug output but the UI hangs, does not respond to anything.
Why is my thread not running separately? CameraThread derived as public QThread
I am using gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5) with QT libraries and QT Creator from Ubuntu 10.04(x86) repositories.
Short answer: Start your thread by calling
aThread->start();notrun(), and make sure you thread’s run() method is protected (not public).Explanation
Calling
start()is the correct way to start the thread, as it provides priority scheduling and actually executes therun()method in its own thread context.It looks like you are going to be loading images in this thread, so I’m going to include some tips before you run into pitfalls many people fall into while using QThread
CameraThreadclass will not necessarily run in the thread’s context, remember only the run() method and methods called from it are running in a separate thread.IMHO, subclassing QThread in the majority of cases is not the way to go. You can do it much simpler with the following code, and it will save you many headaches.
Also read the Qt blog regarding this topic.