本文使用Qt 5.12.6 + MinGW7.3.0.64+win10环境+qtbase源码
我们来看一下以下几个问题,如果你大脑里面都有清晰的答案,请出门右转
- 什么moc( Meta-Object Compiler)预编译
- 为什么要有signals和slots关键字
- 信号槽连接有哪几种类型
- 信号和槽函数有什么区别
- connect到底干了什么
- 信号触发的原理
一.Meta-Object Compiler
新建一个qml工程,打开main.cpp
#include
#include
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
我们可以看到main函数中默认生成了一个信号槽
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
这是一种c++11新特性的写法,我们可以先略过。我们先看一下qobject.h中connect函数的其中一种定义
static QMetaObject::Connection connect(const QObject *sender, const QMetaMethod &signal,
const QObject *receiver, const QMetaMethod &method,
Qt::ConnectionType type = Qt::AutoConnection);
总共五个参数,sender和receiver都是QObject,signal和method都是QMetaMethod,type是Qt::ConnectionType,我们结合main函数中的connect范例来分别看看这几个参数。
sender对应范例中的engine,是一个QQmlApplicationEngine 对象,打开QQmlApplicationEngine 源码重点关注一下标红的部分
1.public QQmlEngine表明了继承关系(QQmlEngine : public QJSEngine: public QObject)
2.Q_OBJECT是一个非常重要的宏,他是Qt实现元编译系统的一个关键宏,这个宏展开后,里边包含了很多Qt帮我们写的代码,包括了变量定义、函数声明等等。为了方便没有下载Qt源码的同学,我们在刚才的例子中新加入一个没有父类的类ZConnection,然后执行qmake和make,编译通过后打开我们的工程目录,如果没有做特殊配置的话工程目录的同级目录会生成一个类似下面的文件夹
然后我们对刚才的类进行改造,让它继承自QObject,添加Q_OBJECT,并添加一个信号和一个槽函数,类似下面的样子
.h文件如下
#ifndef ZCONNECTION_H
#define ZCONNECTION_H
#include
class ZConnection : public QObject
{
Q_OBJECT
public:
explicit ZConnection(QObject *parent = nullptr);
public slots:
void testSlot();
signals:
void testSignal();
};
#endif // ZCONNECTION_H
.cpp文件如下
#include "zconnection.h"
#include
ZConnection::ZConnection(QObject *parent) : QObject(parent)
{
connect(this, &ZConnection::testSignal, this, &ZConnection::testSlot);
}
void ZConnection::testSlot()
{
qDebug() << Q_FUNC_INFO;
}
然后清空debug文件夹,执行qmake和make,然后再观察debug目录下的文件
我们会发现多了几个moc_开头的文件,我们打开moc_zconnection.cpp文件:
/****************************************************************************
** Meta object code from reading C++ file 'zconnection.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../testConnection/zconnection.h"
#include
#include
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'zconnection.h' doesn't include ."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.12.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_ZConnection_t {
QByteArrayData data[4];
char stringdata0[33];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_ZConnection_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_ZConnection_t qt_meta_stringdata_ZConnection = {
{
QT_MOC_LITERAL(0, 0, 11), // "ZConnection"
QT_MOC_LITERAL(1, 12, 10), // "testSignal"
QT_MOC_LITERAL(2, 23, 0), // ""
QT_MOC_LITERAL(3, 24, 8) // "testSlot"
},
"ZConnection\0testSignal\0\0testSlot"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_ZConnection[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 24, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
3, 0, 25, 2, 0x0a /* Public */,
// signals: parameters
QMetaType::Void,
// slots: parameters
QMetaType::Void,
0 // eod
};
void ZConnection::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->testSignal(); break;
case 1: _t->testSlot(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast(_a[0]);
{
using _t = void (ZConnection::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ZConnection::testSignal)) {
*result = 0;
return;
}
}
}
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject ZConnection::staticMetaObject = { {
&QObject::staticMetaObject,
qt_meta_stringdata_ZConnection.data,
qt_meta_data_ZConnection,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *ZConnection::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *ZConnection::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_ZConnection.stringdata0))
return static_cast(this);
return QObject::qt_metacast(_clname);
}
int ZConnection::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 2)
*reinterpret_cast(_a[0]) = -1;
_id -= 2;
}
return _id;
}
// SIGNAL 0
void ZConnection::testSignal()
{
QMetaObject::activate(this, &staticMetaObject, 0, nullptr);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
我们来看看这个moc文件中的几个函数
void ZConnection::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
QT_INIT_METAOBJECT const QMetaObject ZConnection::staticMetaObject
const QMetaObject *ZConnection::metaObject() const
void *ZConnection::qt_metacast(const char *_clname)
int ZConnection::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
void ZConnection::testSignal()
- signal
我们可以看到moc帮我们在这里添加了testSignal的实现,由此可见,信号其实也是一个函数,只是我们只管写信号声明,而信号实现moc会帮助我们自动生成,信号触发后实际调用的是QMetaObject::activate,activate函数具体又做了什么,我们在后面再展开来讲。槽函数我们不仅仅需要写函数声明,函数实现也必须自己写。
void ZConnection::testSignal()
{
QMetaObject::activate(this, &staticMetaObject, 0, nullptr);
}
这里Qt怎么会知道我们定义了信号呢?答案就是【signals】关键字,当moc发现这个标志后,默认我们是在定义信号,它则帮助我们生产了信号的实现体,【slots】关键字也是同样的道理,moc用来解析槽函数时用的。
- qt_static_metacall
根据函数索引调用槽函数,需要注意一个细节【这个回调中信号和槽都是可以被回调的】,自动生成代码如下
void ZConnection::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->testSignal(); break;
case 1: _t->testSlot(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast(_a[0]);
{
using _t = void (ZConnection::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ZConnection::testSignal)) {
*result = 0;
return;
}
}
}
Q_UNUSED(_a);
}
testSignal是一个信号声明,但是却也可以被回调,这也间接的说明了一个问题,信号是可以当槽函数一样使用的。
- staticMetaObject
构造一个QMetaObject对象,传入当前moc文件的动态信息 - metaObject
返回当前QMetaObject,一般而言,虚函数 metaObject() 仅返回类的 staticMetaObject对象。 - qt_metacast
是否可以进行类型转换,被QObject::inherits直接调用,用于判断是否是继承自某个类。判断时,需要传入父类的字符串名称。 - qt_metacall
调用函数回调,内部还是调用了qt_static_metacall函数,该函数被异步处理信号时调用,或者Qt规定的有一定格式的槽函数(on_xxx_clicked())触发
二.Connect
上面我们分析了moc帮助我们生成的moc文件,他是实现信号槽的基础,现在我们来了解下connect函数,看看他到底干了些什么。
先来看看connect的函数实现,我这里把涉及到的三个主要函数的实现都贴出来了,方便大家查看
QMetaObject::Connection QObject::connect(const QObject *sender, const QMetaMethod &signal,
const QObject *receiver, const QMetaMethod &method,
Qt::ConnectionType type)
{
if (sender == 0
|| receiver == 0
|| signal.methodType() != QMetaMethod::Signal
|| method.methodType() == QMetaMethod::Constructor) {
qWarning("QObject::connect: Cannot connect %s::%s to %s::%s",
sender ? sender->metaObject()->className() : "(null)",
signal.methodSignature().constData(),
receiver ? receiver->metaObject()->className() : "(null)",
method.methodSignature().constData() );
return QMetaObject::Connection(0);
}
int signal_index;
int method_index;
{
int dummy;
QMetaObjectPrivate::memberIndexes(sender, signal, &signal_index, &dummy);
QMetaObjectPrivate::memberIndexes(receiver, method, &dummy, &method_index);
}
const QMetaObject *smeta = sender->metaObject();
const QMetaObject *rmeta = receiver->metaObject();
if (signal_index == -1) {
qWarning("QObject::connect: Can't find signal %s on instance of class %s",
signal.methodSignature().constData(), smeta->className());
return QMetaObject::Connection(0);
}
if (method_index == -1) {
qWarning("QObject::connect: Can't find method %s on instance of class %s",
method.methodSignature().constData(), rmeta->className());
return QMetaObject::Connection(0);
}
if (!QMetaObject::checkConnectArgs(signal.methodSignature().constData(), method.methodSignature().constData())) {
qWarning("QObject::connect: Incompatible sender/receiver arguments"
"\n %s::%s --> %s::%s",
smeta->className(), signal.methodSignature().constData(),
rmeta->className(), method.methodSignature().constData());
return QMetaObject::Connection(0);
}
int *types = 0;
if ((type == Qt::QueuedConnection)
&& !(types = queuedConnectionTypes(signal.parameterTypes())))
return QMetaObject::Connection(0);
#ifndef QT_NO_DEBUG
check_and_warn_compat(smeta, signal, rmeta, method);
#endif
QMetaObject::Connection handle = QMetaObject::Connection(QMetaObjectPrivate::connect(
sender, signal_index, signal.enclosingMetaObject(), receiver, method_index, 0, type, types));
return handle;
}
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(sender);
QObject *r = const_cast(receiver);
int method_offset = rmeta ? rmeta->methodOffset() : 0;
Q_ASSERT(!rmeta || QMetaObjectPrivate::get(rmeta)->revision >= 6);
QObjectPrivate::StaticMetaCallFunction callFunction =
rmeta ? rmeta->d.static_metacall : 0;
QOrderedMutexLocker locker(signalSlotLock(sender),
signalSlotLock(receiver));
if (type & Qt::UniqueConnection) {
QObjectConnectionListVector *connectionLists = QObjectPrivate::get(s)->connectionLists;
if (connectionLists && connectionLists->count() > signal_index) {
const QObjectPrivate::Connection *c2 =
(*connectionLists)[signal_index].first;
int method_index_absolute = method_index + method_offset;
while (c2) {
if (!c2->isSlotObject && c2->receiver == receiver && c2->method() == method_index_absolute)
return 0;
c2 = c2->nextConnectionList;
}
}
type &= Qt::UniqueConnection - 1;
}
QScopedPointer c(new QObjectPrivate::Connection);
c->sender = s;
c->signal_index = signal_index;
c->receiver = r;
c->method_relative = method_index;
c->method_offset = method_offset;
c->connectionType = type;
c->isSlotObject = false;
c->argumentTypes.store(types);
c->nextConnectionList = 0;
c->callFunction = callFunction;
QObjectPrivate::get(s)->addConnection(signal_index, c.data());
locker.unlock();
QMetaMethod smethod = QMetaObjectPrivate::signal(smeta, signal_index);
if (smethod.isValid())
s->connectNotify(smethod);
return c.take();
}
void QObjectPrivate::addConnection(int signal, Connection *c)
{
Q_ASSERT(c->sender == q_ptr);
if (!connectionLists)
connectionLists = new QObjectConnectionListVector();
if (signal >= connectionLists->count())
connectionLists->resize(signal + 1);
ConnectionList &connectionList = (*connectionLists)[signal];
if (connectionList.last) {
connectionList.last->nextConnectionList = c;
} else {
connectionList.first = c;
}
connectionList.last = c;
cleanConnectionLists();
c->prev = &(QObjectPrivate::get(c->receiver)->senders);
c->next = *c->prev;
*c->prev = c;
if (c->next)
c->next->prev = &c->next;
if (signal < 0) {
connectedSignals[0] = connectedSignals[1] = ~0;
} else if (signal < (int)sizeof(connectedSignals) * 8) {
connectedSignals[signal >> 5] |= (1 << (signal & 0x1f));
}
}
大致流程如下
信号槽连接后在内存中以QObjectConnectionListVector对象存储,这是一个数组,Qt巧妙的借用了数组快速访问指定元素的方式,把信号所在的索引作为下标来索引他连接的Connection对象,众所周知一个信号可以被多个槽连接,那么我们的的数组自然而然也就存储了一个链表,用于方便的插入和移除,也就是ConnectionList对象。
三、signal&slot
首先来看一下ConnectionType
enum ConnectionType {
AutoConnection,
DirectConnection,
QueuedConnection,
BlockingQueuedConnection,
UniqueConnection = 0x80
};
- Qt::AutoConnection 自动连接,根据sender和receiver是否在一个线程里来决定使用哪种连接方式,同一个线程使用直连,否则使用队列连接
- Qt::DirectConnection 直连
- Qt::QueuedConnection 队列连接
- Qt::BlockingQueuedConnection 阻塞队列连接,顾名思义,虽然是跨线程的,但是还是希望槽执行完之后,才能执行信号的下一步代码
- Qt::UniqueConnection 唯一连接
前边我们已经提到信号触发后实际调用的QMetaObject::activate函数,大致流程如下图所示
QMetaObject::activate函数源码如下:
void QMetaObject::activate(QObject *sender, int signalOffset, int local_signal_index, void **argv)
{
int signal_index = signalOffset + local_signal_index;
if (sender->d_func()->blockSig)
return;
Q_TRACE_SCOPE(QMetaObject_activate, sender, signal_index);
if (sender->d_func()->isDeclarativeSignalConnected(signal_index)
&& QAbstractDeclarativeData::signalEmitted) {
Q_TRACE_SCOPE(QMetaObject_activate_declarative_signal, sender, signal_index);
QAbstractDeclarativeData::signalEmitted(sender->d_func()->declarativeData, sender,
signal_index, argv);
}
if (!sender->d_func()->isSignalConnected(signal_index, /*checkDeclarative =*/ false)
&& !qt_signal_spy_callback_set.signal_begin_callback
&& !qt_signal_spy_callback_set.signal_end_callback) {
// The possible declarative connection is done, and nothing else is connected, so:
return;
}
void *empty_argv[] = { 0 };
if (qt_signal_spy_callback_set.signal_begin_callback != 0) {
qt_signal_spy_callback_set.signal_begin_callback(sender, signal_index,
argv ? argv : empty_argv);
}
{
QMutexLocker locker(signalSlotLock(sender));
struct ConnectionListsRef {
QObjectConnectionListVector *connectionLists;
ConnectionListsRef(QObjectConnectionListVector *connectionLists) : connectionLists(connectionLists)
{
if (connectionLists)
++connectionLists->inUse;
}
~ConnectionListsRef()
{
if (!connectionLists)
return;
--connectionLists->inUse;
Q_ASSERT(connectionLists->inUse >= 0);
if (connectionLists->orphaned) {
if (!connectionLists->inUse)
delete connectionLists;
}
}
QObjectConnectionListVector *operator->() const { return connectionLists; }
};
ConnectionListsRef connectionLists = sender->d_func()->connectionLists;
if (!connectionLists.connectionLists) {
locker.unlock();
if (qt_signal_spy_callback_set.signal_end_callback != 0)
qt_signal_spy_callback_set.signal_end_callback(sender, signal_index);
return;
}
// 数组里面取链表
const QObjectPrivate::ConnectionList *list;
if (signal_index < connectionLists->count())
list = &connectionLists->at(signal_index);
else
list = &connectionLists->allsignals;
Qt::HANDLE currentThreadId = QThread::currentThreadId();
do {
QObjectPrivate::Connection *c = list->first;
if (!c) continue;
// We need to check against last here to ensure that signals added
// during the signal emission are not emitted in this emission.
QObjectPrivate::Connection *last = list->last;
do {
if (!c->receiver)
continue;
QObject * const receiver = c->receiver;
const bool receiverInSameThread = currentThreadId == receiver->d_func()->threadData->threadId.load();
// 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 ? argv : empty_argv, locker);
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;
QMetaCallEvent *ev = c->isSlotObject ?
new QMetaCallEvent(c->slotObj, sender, signal_index, 0, 0, argv ? argv : empty_argv, &semaphore) :
new QMetaCallEvent(c->method_offset, c->method_relative, c->callFunction, sender, signal_index, 0, 0, argv ? argv : empty_argv, &semaphore);
QCoreApplication::postEvent(receiver, ev);
locker.unlock();
semaphore.acquire();
locker.relock();
continue;
#endif
}
QConnectionSenderSwitcher sw;
if (receiverInSameThread) {
sw.switchSender(receiver, sender, signal_index);
}
if (c->isSlotObject) {
c->slotObj->ref();
QScopedPointer obj(c->slotObj);
locker.unlock();
{
Q_TRACE_SCOPE(QMetaObject_activate_slot_functor, obj.data());
obj->call(receiver, argv ? argv : empty_argv);
}
// Make sure the slot object gets destroyed before the mutex is locked again, as the
// destructor of the slot object might also lock a mutex from the signalSlotLock() mutex pool,
// and that would deadlock if the pool happens to return the same mutex.
obj.reset();
locker.relock();
} 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 methodIndex = c->method();
const int method_relative = c->method_relative;
const auto callFunction = c->callFunction;
locker.unlock();
if (qt_signal_spy_callback_set.slot_begin_callback != 0)
qt_signal_spy_callback_set.slot_begin_callback(receiver, methodIndex, argv ? argv : empty_argv);
{
Q_TRACE_SCOPE(QMetaObject_activate_slot, receiver, methodIndex);
callFunction(receiver, QMetaObject::InvokeMetaMethod, method_relative, argv ? argv : empty_argv);
}
if (qt_signal_spy_callback_set.slot_end_callback != 0)
qt_signal_spy_callback_set.slot_end_callback(receiver, methodIndex);
locker.relock();
} else {
const int method = c->method_relative + c->method_offset;
locker.unlock();
if (qt_signal_spy_callback_set.slot_begin_callback != 0) {
qt_signal_spy_callback_set.slot_begin_callback(receiver,
method,
argv ? argv : empty_argv);
}
{
Q_TRACE_SCOPE(QMetaObject_activate_slot, receiver, method);
metacall(receiver, QMetaObject::InvokeMetaMethod, method, argv ? argv : empty_argv);
}
if (qt_signal_spy_callback_set.slot_end_callback != 0)
qt_signal_spy_callback_set.slot_end_callback(receiver, method);
locker.relock();
}
if (connectionLists->orphaned)
break;
// 一个信号对应多个槽函数
} while (c != last && (c = c->nextConnectionList) != 0);
if (connectionLists->orphaned)
break;
} while (list != &connectionLists->allsignals &&
//start over for all signals;
((list = &connectionLists->allsignals), true));
}
if (qt_signal_spy_callback_set.signal_end_callback != 0)
qt_signal_spy_callback_set.signal_end_callback(sender, signal_index);
}
四、总结
Qt信号槽的实现原理其实就是函数回调,不同的是直连直接回调、队列连接使用Qt的事件循环隔离了一次达到异步,最终还是使用函数回调
- moc预编译帮助我们构建了信号槽回调的开头(信号函数体)和结尾(qt_static_metacall回调函数),中间的回调过程Qt已经在QOjbect函数中实现
- signals和slots就是为了方便moc解析我们的C++文件,从中解析出信号和槽
- 信号槽总共有5种连接方式,前四种是互斥的,可以表示为异步和同步。第五种唯一连接时配合前4种方式使用的
- 信号和槽本质上是一样的,但是对于使用者来说,信号只需要声明,moc帮你实现,槽函数声明和实现都需要自己写
- connect方法就是把发送者、信号、接受者和槽存储起来,供后续执行信号时查找
- 信号触发就是一系列函数回调