动态映射一个对象的所有QT信号到一个插槽

时间:2015-04-24 15:56:36

标签: c++ qt signals-slots

我想将一个QObject的所有信号连接到某个插槽。

插槽看起来像这样:

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

以下代码是QObject传递给的地方:

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, ..., ..., ...);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

看看

const char * QMetaMethod::signature() const

那么你应该可以像

一样使用它
QObject::connect(object, method->signature(), this, SLOT(signalFired()));

您可能需要在"2"来电之前添加method->signature(),因为SIGNAL(a) makro定义为SIGNAL(a) "2"#a,如上所述Is it possible to see definition of Q_SIGNALS, Q_SLOT, SLOT(), SIGNAL() macros? (Qt)