PDA

View Full Version : [solved] Understanding QML / C++ Event Loops



kachofool
20th March 2011, 19:52
Hi,

I'm trying to load a C++ object from qml, but it freezes the UI. Here's what I tried/understood:

Method One: I have a simple qml button, and when I click it, I directly invoke the C++ object's load slot. Loading takes a couple of seconds, during which the UI is frozen. It should be frozen; the thread that's running the UI is now processing my C++ load function.

Method Two: I have a simple qml button, and when I click it, I directly invoke the C++ object's special placeholder function. All this function does is emit a signal from the C++ object, which is connected to the C++ object's Load slot. Again, the UI freezes for a couple of seconds. I thought that the C++ object lies in a different thread, the UI thread should only emit the signal, but this doesn't happen... the UI thread executes the Load slot too, since it freezes up for the same time as Method One.

Method Three: Tried to set it up so that the QML emits a signal to the C++ object instead of invoking a C++ object slot directly. Problem is that my QML Element lies inside a QML Loader{} from another QML file. I tried, but I couldn't use QObject's findChild() method to find the specific object I need to receive the signal from.

When I check the running process with gdb, I see that two threads are started up. I thought one thread was for the QML view, and the other for the rest of the app. Is this wrong? Do I need a third thread?

edit: Adding a thread solved this problem.

main.cpp: contains my declarative view and main object
I throw my main object in another thread, and everything works as it should :)

vishalrocks101
10th May 2011, 10:38
Hi,

I am also facing this same problem.. can u please show some code how did u solved ur problem. ie how did you placed ur object into another thread .. plz help me on this issue.

Thanks with Regards,
Vishal

kachofool
10th May 2011, 19:24
Hi Vishal,

I don't currently have any working code I can show you, but I can explain what I did and it should be straightforward to implement the code yourself. The code you have that's freezing up the UI should be implemented in a separate worker thread. Subclass the QThread class for this. My QThread class doesn't do anything special. I just reimplemented the run() function as follows:



void MyThread::run()
{ exec(); }


You can then use QObject's moveToThread function to have that object's events processed in another thread (the one you created earlier).



MyThread* myBusyThread = new MyThread;
customQObject* myBusyObject = new customQObject;
myBusyObject->moveToThread(myBusyThread);
myBusyThread->start();


Invoke the methods that cause your GUI to normally freeze up (the heavy processing ones) using signals and slots and the processing for that object should be done in a separate thread, leaving the UI responsive.