Search code examples
c++qtsignals-slots

Dynamic mapping of all QT signals of one object to one slot


I want to connect all signals of one QObject to a certain slot.

The slot looks something like this:

void SignalIntercepter::signalFired()
{
    std::cout << "Signal is fired!" << std::endl;
}

The following code is where the QObject will be passed to:

void SignalIntercepter::handleObject(QObject* object)
{
    const QMetaObject *me = object->metaObject();
    int methodCount = me->methodCount();
    for(int i = 0; i < methodCount; i++)
    {
        QMetaMethod method = me->method(i);
        if(method.methodType() == QMetaMethod::Signal)
        {
            // How do I connect this signal to the slot?
            // QObject::connect(object, ..., ..., ...);
        }
    }
}

Solution

  • have a look at

    const char * QMetaMethod::signature() const
    

    then you should be able to use it like

    QObject::connect(object, method->signature(), this, SLOT(signalFired()));
    

    you might need to add "2" before the method->signature() call because SIGNAL(a) makro is defined SIGNAL(a) "2"#a as mentioned Is it possible to see definition of Q_SIGNALS, Q_SLOT, SLOT(), SIGNAL() macros? (Qt)