Best way to have a QObject-derived class run stuff each frame (or in it's own thread)? [Qt/QML C++]



  • Background: I have a custom QObject-derived class that wraps an SDL2 context for polling inputs for gamepad/joystick-like devices. After initializing SDL, each frame (or, maybe in a new thread) this class will need to (1) poll events from SDL's event queue and (2) process the returned events to determine what kind of event occurred. After processing events, I plan on emitting event-specific signals to be easily used by my other QObjects. I happen to be using QML within my project, but if I understand correctly, this shouldn't require QML interaction at all and is more of a general question about QObjects...

    So how can I poll/process/emit events each frame within my custom QObject subclass? Is there some kind of 'update' function that Qt calls for each QObject that I can overwrite? Does each object contain some kind of thread that runs independently that I can use? Or do I have to manually create my own thread in the QObject-derived class' constructor?


  • Moderators

    Hi,

    Yes, the principles here apply to all QObjects. They apply to both C++ and QML code.

    QObjects do not contain threads. Rather, each object has a "thrad affinity". Please start by reading the "QObject|Thread Affinity":http://qt-project.org/doc/qt-5/qobject.html#thread-affinity article.

    I don't know the specifics of SDL events, but this is the general approach for polling:

    Make your polling function a slot of your wrapper QObject.

    Connect that slot to a QTimer's timeout() signal (see http://qt-project.org/doc/qt-5/QTimer.html )

    Run your timer at your desired polling interval. Then, every time the timer emits the timeout() signal, your polling slot will run.

    After you have finished processing your SDL events, emit the results in a signal. You will need to declare the signal in your wrapper QObject too.

    If you want to use a high polling rate, or the processing takes a long time, you might need to move your QObject to a separate thread.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.