Qt World Summit: Register Today!

Multithreading and sql / model-view

  • I'm new to Qt, having been using it for only a few months now. So far, I'm still in the learning stage, but really like it.

    I'm writing an application with sql operations in a thread of it's own. So far I've gotten the initialization code working well but I'm wondering if it's safe to have a model in one thread and a view in another? Since they seem to communicate over signals/slots, I would think so, but there is nothing definitive out there.

    Failing that, are there any reccomendations, examples or tutorials on how to accomplish sql over thread boundaries? I've searched and found nothing. There is much on threading and much on sql, but nothing about mixing them.

    Thanks in advance for your help.

  • No, it is not save to have a model in one thread, and a view in another. Both the model and the view object must live in the main GUI thread. While the model uses signals to tell the view about changes, the view makes direct method calls to methods like data() and flags(). Those will be dangerous in your scenario.

    The Sql itself also needs to be in its own thread. You can not use the same database connection from multiple threads in a save way. I understand that you would like to do the sql part in a thread other than the main thread, because it can be slow. However, it is up to you to provide the proper communication and synchronization between the model and the SQL backend then.

  • Thank you for a quick reply.

    Plan B was to use a QSharedDataPointer class which had among other things, a QList of QSqlRecords to transfer the data. Is this a safe approach?

  • You may have a look at the implementation of [[Doc:QFileSystemModel]], it uses a background thread to populate itself.

  • Thanks, I'll do that.

Log in to reply