Important: Please read the Qt Code of Conduct -

Moving an object to a different thread

  • Hi

    My application uses a custom serialization mechanism.
    Phase 1) The mechanism loads clusters of data on a separate thread, creates all appropriate objects there and so on.
    Phase 2) Once they are all fully deserialized, it hands them over to the main application thread and finishes the serialization there by for example setting up connections between objects etc.

    This mechanism is a new addition to my framework - before that I was deserializing everything on the main thread.

    The problem I have is that some of the objects that are created during deserializatiuon are Qt objects ( a bunch of widgets basically ).
    They all record the ids of a thread they were created on. And when the time comes for "phase 2", these objects start complaing that they all don't belong to this thread and therefore can have no signals sent etc.

    So I found a method on QObject, called 'moveToThread'. The little bugger's not very helpful though, as it performs a check and prevents from moving objects from a different thread to the current thread ( WHY scuh a constraint, I have no clue ).

    Does anyone have an idea how can I go about this? I can guarantee that the objects will only be createad on a separate thread, and from that point on they will all be living and operating on the main thread.


  • Moderators

    Call moveToThread() from the current thread to "push" the object to a different thread. Qt has that constraint because it's dangerous to "pull" an object from a different thread: What will happen if the object is moved, while it is in the middle of processing data in its original thread?

Log in to reply