How to find out from the slot whose signal this slot named?

I mean, if I have many different signals that are connected to the same slot. I saw this question, but cannot understand the link in the answer. Can you give me a simple example?

+7
c ++ qt qt-signals qtcore qmetaobject
source share
1 answer

I think you can use this method: [protected] int QObject::​senderSignalIndex() const

From the Qt documentation:

Returns the meta method index of the signal that calls the current executable slot , which is a member of the class returned by the sender (). If called outside the slot activated by a signal, -1 is returned.

For signals with default parameters, this function will always return an index with all parameters, regardless of what was used when connecting () . For example, a broken signal (QObject * obj = 0) will have two different indexes (with and without a parameter), but this function will always return an index with a parameter. This does not apply when overloading signals with various parameters.

A warning. This feature violates the object-oriented principle of modularity . However, accessing the signal index can be useful when many signals are connected to the same slot.

A warning. The return value of this function is invalid when the slot is called through Qt :: DirectConnection from a thread other than this stream of objects. Do not use this function in this type of script.

This feature was introduced in Qt 4.8.

Here is a small example that I created for you that demonstrates how it works:

 #include <QTimer> #include <QMetaObject> #include <QMetaMethod> #include <QCoreApplication> #include <QDebug> #include <QObject> class Foo : public QObject { Q_OBJECT public slots: void mySlot() { QMetaMethod metaMethod = sender()->metaObject()->method(senderSignalIndex()); qDebug() << metaMethod.name(); qDebug() << metaMethod.methodSignature(); qApp->quit(); } }; #include "main.moc" int main(int argc, char **argv) { QCoreApplication coreApplication(argc, argv); QTimer timer; Foo foo; QObject::connect(&timer, &QTimer::timeout, &foo, &Foo::mySlot); timer.setSingleShot(true); timer.start(1000); return coreApplication.exec(); } 

main.pro

 TEMPLATE = app TARGET = main QT = core CONFIG += c++11 SOURCES += main.cpp 

Assembly and launch

 qmake && make && ./main 

Exit

 "timeout" "timeout()" 
+12
source share

All Articles