Logo Search packages:      
Sourcecode: qt4-x11 version File versions  Download package

void QObject::moveToThread ( QThread targetThread  )  [inherited]

Changes the thread affinity for this object and its children. The object cannot be moved if it has a parent. Event processing will continue in the targetThread.

To move an object to the main thread, use QApplication::instance() to retrieve a pointer to the current application, and then use QApplication::thread() to retrieve the thread in which the application lives. For example:


If targetThread is zero, all event processing for this object and its children stops.

Note that all active timers for the object will be reset. The timers are first stopped in the current thread and restarted (with the same interval) in the targetThread. As a result, constantly moving an object between threads can postpone timer events indefinitely.

A QEvent::ThreadChange event is sent to this object just before the thread affinity is changed. You can handle this event to perform any special processing. Note that any new events that are posted to this object will be handled in the targetThread.

This function is not thread-safe; the current thread must be same as the current thread affinity. In other words, this function can only "push" an object from the current thread to another thread, it cannot "pull" an object from any arbitrary thread to the current thread.
See also:

Definition at line 1383 of file qobject.cpp.


    if (d->threadData->thread == targetThread) {
        // object is already in this thread

    if (d->parent != 0) {
        qWarning("QObject::moveToThread: Cannot move objects with a parent");
    if (d->isWidget) {
        qWarning("QObject::moveToThread: Widgets cannot be moved to a new thread");

    QThreadData *currentData = QThreadData::current();
    QThreadData *targetData = targetThread ? QThreadData::get2(targetThread) : new QThreadData(0);
    if (d->threadData->thread == 0 && currentData == targetData) {
        // one exception to the rule: we allow moving objects with no thread affinity to the current thread
        currentData = d->threadData;
    } else if (d->threadData != currentData) {
        qWarning("QObject::moveToThread: Current thread (%p) is not the object's thread (%p).\n"
                 "Cannot move to target thread (%p)\n",
                 d->threadData->thread, currentData->thread, targetData->thread);

    // prepare to move

    QWriteLocker locker(QObjectPrivate::readWriteLock());
    if (currentData != targetData) {
        while (currentData && !currentData->postEventList.mutex.tryLock()) {

    // keep currentData alive (since we've got it locked)

    // move the object
    d_func()->setThreadData_helper(currentData, targetData);

    if (currentData != targetData) {
        if (currentData)

    // now currentData can commit suicide if it wants to

Generated by  Doxygen 1.6.0   Back to index