QObject connect QMetaMethod signal to functor

  • Hi,
    I'm looking for a way to simplify a big part of my code by using the lambda functor call into QObject::connect().
    I have the name of the signal (string format, given at runtime), a pointer to the object, from which I could extract the QMetaMethod for that given signal.
    But the connect function only allow:

    • SIGNAL() marco to SLOT()/SIGNAL() macro
    • functor to functor
    • MetaMethod to MetaMethod
      I'm guessing it's easier to foward, but how could one do the follwoing?

    @void myCustomQObject::mySlot(const QString& signalName)
    //do something with string

    QPointer<QSignalMapper> mapper_; // define in header, create on object constructor

    void myCustomQObject::myFunction(QObject* const obj, const QString& signalName)
    // option A: emulate SIGNAL() macro and use signalMapper, work but get combersome when multiple
    // signal from a single object is launch, we need a list of QSignalMapper to handle multiple signal from single object
    mapper_->setMapping(obj, signalName);
    connect(obj, signalName.prepend("1").toStdString().c_str(), mapper_, SLOT(map()));
    connect(mapper_, SIGNAL(mapped(QString)), this, SLOT(mySlot(QString)));

    // option B: same as above but use the obj MetaObject to recover the signal method and use the signal method of mapper (cleaner to avoid emulating SIGNAL macro), still suffer the same problem with QSignalMapper
    auto objMeta = obj->metaObject;
    // option C: desired, would be clean and avoid using so many
    connect(obj, signalMetaMethod, & { mySlot(signalName); });

    The option C, become even more pratical if the signal have some arguments, but this does not seem to be possible, anybody have an idea how to acheive such a thing?

  • Moderators


    Connections to functors/lambdas use function pointers. They need to be resolved at compile-time, because the compiler needs to know what types of function pointers you are using. You can't use runtime strings.

    You could try passing function pointers instead of strings, but this will only work for signals/slots with the same parameter list.

    Perhaps this is where templates come in? (I haven't tried it myself so I don't know how much work is required)

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.