• qt中的信号与槽


    连接形式

    connect有好几种形式

    static QMetaObject::Connection connect(const QObject *sender, const char *signal, const QObject *receiver, const char *member, Qt::ConnectionType = Qt::AutoConnection);
    
    static QMetaObject::Connection connect(const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type = Qt::AutoConnection);
    
    inline QMetaObject::Connection connect(const QObject *sender, const char *signal, const char *member, Qt::ConnectionType type = Qt::AutoConnection) const;
    
    • 1
    • 2
    • 3
    • 4
    • 5

    连接方式有

    连接类型说明
    Qt::AutoConnection如果发送者和接收者在同一线程,使用Qt::DirectConnection,否则使用Qt::QueuedConnection
    Qt::DirectConnection信号被发射时立即执行,信号和槽函数在同一线程
    Qt::QueuedConnection在事件循环回到接收者线程后执行槽函数,信号和槽函数不在同一线程
    Qt::BlockingQueuedConnection信号线程会阻塞直到槽函数执行完毕,当信号与槽函数在同一线程时,不能使用这种方式
    Qt::UniqueConnection表示不能重复连接信号和槽

    涉及到的宏

    # define SLOT(a)     "1"#a
    # define SIGNAL(a)   "2"#a
    
    • 1
    • 2

    connect底层到底做了什么呢?
    其实际上添加发送者对应信号索引的监听器列表中

    QObjectPrivate::Connection *QMetaObjectPrivate::connect(const QObject *sender,
                                     int signal_index, const QMetaObject *smeta,
                                     const QObject *receiver, int method_index,
                                     const QMetaObject *rmeta, int type, int *types)
    {
        QObject *s = const_cast<QObject *>(sender);
        QObject *r = const_cast<QObject *>(receiver);
    
        int method_offset = rmeta ? rmeta->methodOffset() : 0;
        Q_ASSERT(!rmeta || QMetaObjectPrivate::get(rmeta)->revision >= 6);
        QObjectPrivate::StaticMetaCallFunction callFunction = rmeta ? rmeta->d.static_metacall : nullptr;
    
        QOrderedMutexLocker locker(signalSlotLock(sender),
                                   signalSlotLock(receiver));
    
        QObjectPrivate::ConnectionData *scd  = QObjectPrivate::get(s)->connections.loadRelaxed();
        if (type & Qt::UniqueConnection && scd) {
            if (scd->signalVectorCount() > signal_index) {
                const QObjectPrivate::Connection *c2 = scd->signalVector.loadRelaxed()->at(signal_index).first.loadRelaxed();
    
                int method_index_absolute = method_index + method_offset;
    
                while (c2) {
                    if (!c2->isSlotObject && c2->receiver.loadRelaxed() == receiver && c2->method() == method_index_absolute)
                        return nullptr;
                    c2 = c2->nextConnectionList.loadRelaxed();
                }
            }
            type &= Qt::UniqueConnection - 1;
        }
    
        std::unique_ptr<QObjectPrivate::Connection> c{new QObjectPrivate::Connection};
        c->sender = s;
        c->signal_index = signal_index;
        c->receiver.storeRelaxed(r);
        QThreadData *td = r->d_func()->threadData;
        td->ref();
        c->receiverThreadData.storeRelaxed(td);
        c->method_relative = method_index;
        c->method_offset = method_offset;
        c->connectionType = type;
        c->isSlotObject = false;
        c->argumentTypes.storeRelaxed(types);
        c->callFunction = callFunction;
    
        QObjectPrivate::get(s)->addConnection(signal_index, c.get());
    
        locker.unlock();
        QMetaMethod smethod = QMetaObjectPrivate::signal(smeta, signal_index);
        if (smethod.isValid())
            s->connectNotify(smethod);
    
        return c.release();
    }
    
    void QObjectPrivate::addConnection(int signal, Connection *c)
    {
        Q_ASSERT(c->sender == q_ptr);
        ensureConnectionData();
        ConnectionData *cd = connections.loadRelaxed();
        cd->resizeSignalVector(signal + 1);
    
        ConnectionList &connectionList = cd->connectionsForSignal(signal);
        if (connectionList.last.loadRelaxed()) {
            Q_ASSERT(connectionList.last.loadRelaxed()->receiver.loadRelaxed());
            connectionList.last.loadRelaxed()->nextConnectionList.storeRelaxed(c);
        } else {
            connectionList.first.storeRelaxed(c);
        }
        c->id = ++cd->currentConnectionId;
        c->prevConnectionList = connectionList.last.loadRelaxed();
        connectionList.last.storeRelaxed(c);
    
        QObjectPrivate *rd = QObjectPrivate::get(c->receiver.loadRelaxed());
        rd->ensureConnectionData();
    
        c->prev = &(rd->connections.loadRelaxed()->senders);
        c->next = *c->prev;
        *c->prev = c;
        if (c->next)
            c->next->prev = &c->next;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82

    在添加连接设置连接对象时,将isSlotObject设置为false,callFunction设置为接收对象元对象的static_metacall

    QObjectPrivate::StaticMetaCallFunction callFunction = rmeta ? rmeta->d.static_metacall : nullptr;
    
    • 1

    在doActivate调用时就会走callFunction分支

    什么时候会触发接收者的调用

    在emit 触发信号时。
    moc(元对象编译器)在处理定义有SIGNALS的类时,会针对定义的信号生成对应的处理函数,在内部会调用QMetaObject::active方法,其定义为

    void QMetaObject::activate(QObject *sender, const QMetaObject *m, int local_signal_index,
                               void **argv)
    {
        int signal_index = local_signal_index + QMetaObjectPrivate::signalOffset(m);
    
        if (Q_UNLIKELY(qt_signal_spy_callback_set.loadRelaxed()))
            doActivate<true>(sender, signal_index, argv);
        else
            doActivate<false>(sender, signal_index, argv);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    doActivate会从发送者的信号索引取出连接列表,调用处理函数
    对于 Qt::AutoConnection,会判断发送线程和接收处理线程是否在同一线程,如果在同一线程,QMetaObject::metacall作同步调用,否则生成QMetaCallEvent发送qt的事件处理线程中
    对于 Qt::DirectConnection, QMetaObject::metacall作同步调用
    对于Qt::QueuedConnection,直接生成QMetaCallEvent发送qt的事件处理线程中
    对于Qt::BlockingQueuedConnection,如果发现发送线程和接收处理线程是在同一线程,输出告警日志,会使用信号量QSemaphore,生成QMetaCallEvent发送qt的事件处理线程中等待处理结果

    template <bool callbacks_enabled>
    void doActivate(QObject *sender, int signal_index, void **argv)
    {
        QObjectPrivate *sp = QObjectPrivate::get(sender);
    
        if (sp->blockSig)
            return;
    
        if (sp->isDeclarativeSignalConnected(signal_index)
                && QAbstractDeclarativeData::signalEmitted) {
            Q_TRACE_SCOPE(QMetaObject_activate_declarative_signal, sender, signal_index);
            QAbstractDeclarativeData::signalEmitted(sp->declarativeData, sender,
                                                    signal_index, argv);
        }
    
        const QSignalSpyCallbackSet *signal_spy_set = callbacks_enabled ? qt_signal_spy_callback_set.loadAcquire() : nullptr;
    
        void *empty_argv[] = { nullptr };
        if (!argv)
            argv = empty_argv;
    
        if (!sp->maybeSignalConnected(signal_index)) {
            // The possible declarative connection is done, and nothing else is connected
            if (callbacks_enabled && signal_spy_set->signal_begin_callback != nullptr)
                signal_spy_set->signal_begin_callback(sender, signal_index, argv);
            if (callbacks_enabled && signal_spy_set->signal_end_callback != nullptr)
                signal_spy_set->signal_end_callback(sender, signal_index);
            return;
        }
    
        if (callbacks_enabled && signal_spy_set->signal_begin_callback != nullptr)
            signal_spy_set->signal_begin_callback(sender, signal_index, argv);
    
        bool senderDeleted = false;
        {
        Q_ASSERT(sp->connections.loadAcquire());
        QObjectPrivate::ConnectionDataPointer connections(sp->connections.loadRelaxed());
        QObjectPrivate::SignalVector *signalVector = connections->signalVector.loadRelaxed();
    
        const QObjectPrivate::ConnectionList *list;
        if (signal_index < signalVector->count())
            list = &signalVector->at(signal_index);
        else
            list = &signalVector->at(-1);
    
        Qt::HANDLE currentThreadId = QThread::currentThreadId();
        bool inSenderThread = currentThreadId == QObjectPrivate::get(sender)->threadData->threadId.loadRelaxed();
    
        // We need to check against the highest connection id to ensure that signals added
        // during the signal emission are not emitted in this emission.
        uint highestConnectionId = connections->currentConnectionId.loadRelaxed();
        do {
            QObjectPrivate::Connection *c = list->first.loadRelaxed();
            if (!c)
                continue;
    
            do {
                QObject * const receiver = c->receiver.loadRelaxed();
                if (!receiver)
                    continue;
    
                QThreadData *td = c->receiverThreadData.loadRelaxed();
                if (!td)
                    continue;
    
                bool receiverInSameThread;
                if (inSenderThread) {
                    receiverInSameThread = currentThreadId == td->threadId.loadRelaxed();
                } else {
                    // need to lock before reading the threadId, because moveToThread() could interfere
                    QMutexLocker lock(signalSlotLock(receiver));
                    receiverInSameThread = currentThreadId == td->threadId.loadRelaxed();
                }
    
    
                // determine if this connection should be sent immediately or
                // put into the event queue
                if ((c->connectionType == Qt::AutoConnection && !receiverInSameThread)
                    || (c->connectionType == Qt::QueuedConnection)) {
                    queued_activate(sender, signal_index, c, argv);
                    continue;
    #if QT_CONFIG(thread)
                } else if (c->connectionType == Qt::BlockingQueuedConnection) {
                    if (receiverInSameThread) {
                        qWarning("Qt: Dead lock detected while activating a BlockingQueuedConnection: "
                        "Sender is %s(%p), receiver is %s(%p)",
                        sender->metaObject()->className(), sender,
                        receiver->metaObject()->className(), receiver);
                    }
                    QSemaphore semaphore;
                    {
                        QBasicMutexLocker locker(signalSlotLock(sender));
                        if (!c->receiver.loadAcquire())
                            continue;
                        QMetaCallEvent *ev = c->isSlotObject ?
                            new QMetaCallEvent(c->slotObj, sender, signal_index, argv, &semaphore) :
                            new QMetaCallEvent(c->method_offset, c->method_relative, c->callFunction,
                                               sender, signal_index, argv, &semaphore);
                        QCoreApplication::postEvent(receiver, ev);
                    }
                    semaphore.acquire();
                    continue;
    #endif
                }
    
                QObjectPrivate::Sender senderData(receiverInSameThread ? receiver : nullptr, sender, signal_index);
    
                if (c->isSlotObject) {
                    c->slotObj->ref();
    
                    struct Deleter {
                        void operator()(QtPrivate::QSlotObjectBase *slot) const {
                            if (slot) slot->destroyIfLastRef();
                        }
                    };
                    const std::unique_ptr<QtPrivate::QSlotObjectBase, Deleter> obj{c->slotObj};
    
                    {
                        Q_TRACE_SCOPE(QMetaObject_activate_slot_functor, obj.get());
                        obj->call(receiver, argv);
                    }
                } else if (c->callFunction && c->method_offset <= receiver->metaObject()->methodOffset()) {
                    //we compare the vtable to make sure we are not in the destructor of the object.
                    const int method_relative = c->method_relative;
                    const auto callFunction = c->callFunction;
                    const int methodIndex = (Q_HAS_TRACEPOINTS || callbacks_enabled) ? c->method() : 0;
                    if (callbacks_enabled && signal_spy_set->slot_begin_callback != nullptr)
                        signal_spy_set->slot_begin_callback(receiver, methodIndex, argv);
    
                    {
                        Q_TRACE_SCOPE(QMetaObject_activate_slot, receiver, methodIndex);
                        callFunction(receiver, QMetaObject::InvokeMetaMethod, method_relative, argv);
                    }
    
                    if (callbacks_enabled && signal_spy_set->slot_end_callback != nullptr)
                        signal_spy_set->slot_end_callback(receiver, methodIndex);
                } else {
                    const int method = c->method_relative + c->method_offset;
    
                    if (callbacks_enabled && signal_spy_set->slot_begin_callback != nullptr) {
                        signal_spy_set->slot_begin_callback(receiver, method, argv);
                    }
    
                    {
                        Q_TRACE_SCOPE(QMetaObject_activate_slot, receiver, method);
                        QMetaObject::metacall(receiver, QMetaObject::InvokeMetaMethod, method, argv);
                    }
    
                    if (callbacks_enabled && signal_spy_set->slot_end_callback != nullptr)
                        signal_spy_set->slot_end_callback(receiver, method);
                }
            } while ((c = c->nextConnectionList.loadRelaxed()) != nullptr && c->id <= highestConnectionId);
    
        } while (list != &signalVector->at(-1) &&
            //start over for all signals;
            ((list = &signalVector->at(-1)), true));
    
            if (connections->currentConnectionId.loadRelaxed() == 0)
                senderDeleted = true;
        }
        if (!senderDeleted) {
            sp->connections.loadRelaxed()->cleanOrphanedConnections(sender);
    
            if (callbacks_enabled && signal_spy_set->signal_end_callback != nullptr)
                signal_spy_set->signal_end_callback(sender, signal_index);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
  • 相关阅读:
    Java版工程行业管理系统源码-专业的工程管理软件- 工程项目各模块及其功能点清单
    L52.linux命令每日一练 -- 第八章 Linux磁盘与文件系统管理命令 -- resize2fs和fsck
    什么是遗留代码:有效地处理遗留代码的8个小贴士
    解决Antd 二次封装表格的可编辑功能(editable table)不生效的问题
    ASEMI整流桥SKBPC3516,SKBPC3516参数,SKBPC3516应用
    t-SNE——高维特征可视化分析
    C专家编程 第9章 再论数组 9.2 为什么会发生混淆
    PMP子过程定义总结
    如何选币与确定对应策略研究
    Windows ssh免密访问Linux服务器
  • 原文地址:https://blog.csdn.net/wuli2496/article/details/130774968