Qt World Summit: Register Today!

Multithread for QML property binding

  • QML property could be bound to a Q_PROPERTY of an QObject, and once the property changed, it will notify the QML to change the property and its apperance. But the mechanism is done in main thread. If the property changed frequently(may.. 1000 times in a second), the main thread will be cannot afford it. May I leverage the multi-core CPU to solve this problem? It seems difficult due to the multi-thread concurrent issue as far as I know.

  • It is actually not. Qt provides low-level and high-level "mutlithreading functionality":http://qt-project.org/doc/qt-4.8/threads.html to compute your data in a secondary thread and raise the notify signal once done.

    But the question is: do you really need to generate a new value each millisecond? If it is just for display purposes it definitely isn't. The frame rate of QML is most probably capped way under 1000 fps for technical reasons, the frame rate of your eyes is even lower.

  • Hi Lukas,
    Thanks for your reply.
    In my case, I want to display a timestamp overlay my video player (so..about 30 times updating in a second), and my video player support multiple channels, so it could exceed 1000 times updating in a second.
    I am doing the computing in another thread now, but I think a simple signal/slot with 1000 times in a second is also heavy..

  • I see. I would not take a detour by a binding then, but create a custom QDeclarativeItem (or QQuickItem for QtQuick 2) for (just) displaying the timestamp overlay.

    If the timestamp needs to be computed you can still offload this to a worker thread. If the timestamp is an atomic value, only read in the display thread and only written in the worker thread you can use a non-guarded shared variable.

    If the timestamp just needs to be read from somewhere (and not computed) you should not use a worker thread, as they do not come for free as well and the overhead might outweigh the advantage gained.

  • I think create a custom QQuickItem is a good solution, but it seems it will decrease the advantage of QML. In the original design, the timestamp is just a value without appearance, and then the QML could determine its look, such as font family, size, color and even the digit of timestamp.
    But maybe it is the only solution..Thank you for your suggestion.

  • Alternatively, provide a second Q_PROPERTY which is updated less frequently, and bind to it instead of the original property. I assume that you have control over the setter function of the original function? Modify it so that it also updates the new property value, every 100 updates or something (and then make sure you manually emit the change notification for the second property value in that case, too).

Log in to reply