The signal/slot mechanism in Qt, is a static mechanism. The classes have to be preprocessed by the moc compiler.
Now I want to create signals and slots dynamically at run-time.
I already have a working solution, but it feels to me like a hack, although I am using publicly available methods.
This is the code for dynamic slots:
bool DynamicQObject::connectDynamicSlot(const QString &objectName, QObject *pSourceObject, QMetaMethod signalMethod)
{
QByteArray slotName = signalMethod.name().prepend("on").append("(");
QStringList parameters;
for (int i = 0, j = signalMethod.parameterCount(); i < j; ++i)
{
parameters << QMetaType::typeName(signalMethod.parameterType(i));
}
slotName.append(parameters.join(",")).append(")");
QByteArray theSignal = QMetaObject::normalizedSignature(signalMethod.methodSignature().constData());
QByteArray theSlot = QMetaObject::normalizedSignature(slotName);
if (!QMetaObject::checkConnectArgs(theSignal, theSlot))
{
return false;
}
int signalId = pSourceObject->metaObject()->indexOfSignal(theSignal);
if (signalId < 0)
{
return false;
}
int slotId = slotIndices.value(theSlot, -1);
if (slotId < 0)
{
slotId = slotList.size();
slotIndices[theSlot] = slotId;
slotList.append(createSlot(theSlot, objectName, signalMethod));
}
return QMetaObject::connect(pSourceObject, signalId, this, slotId + metaObject()->methodCount());
}
As you can see, I make intensive use of the QMetaObject, and particularly the index of the slots (method count).
The code for dynamic signals is comparable.
Now my question is: how future proof is this solution, especially because I assume that the index must be at least one bigger than the methodCount()?
socketIoObject.connect("customEvent", &socketIoObject, [=](Event e){ process event }
– Kurt PattynDynamicQObject
. What's important is how you integrate this with the metacall machinery. Connecting events to lambdas or event emission can be done without need for dynamic signals/slots. You gain nothing by repurposingQObject::connect
. You should simply create your own method for that, IMHO. – Kuba hasn't forgotten Monica