How to make a list of private slots in Qt?

1.4k Views Asked by At

A nice simple example would be nice. For my part, I have about 200 unique slots that I would like to append into a list, and then setup various connections using an iterating "for" loop.

3

There are 3 best solutions below

0
On
  1. Get a class's QMetaObject using QObject::metaObject() method.
  2. Retrieve a number of all methods with QMetaObject::methodCount().
  3. Iterating through all method indexes use QMetaObject::method() to get QMetaMethod.
  4. With QMetaMethod::methodType() it is possible to check if method is slot.
  5. Add signatures (QMetaMethod::signature()) of slots to list for later use in connect().
0
On

This response was offered to me on a forum. I am posting it here for reference:

QList<const char*> slotList;
slotList << SLOT(slot1());
slotList << SLOT(slot2());
// ...

for(int i=0; i< listOfButtons.size();++i) {
connect(listOfButtons->at(i), SIGNAL(clicked()), this, slotList.at(i));
}

http://www.qtcentre.org/threads/56224-A-list-for-storing-member-functions-slots

2
On

To retrieve the signature of QObject's methods (signals, slots, etc.) you can use meta object (QMetaObject) information. For example the following code (taken from Qt documentation) extracts all methods' signatures of the object:

const QMetaObject* metaObject = obj->metaObject();
QStringList methods;
for(int i = metaObject->methodOffset(); i < metaObject->methodCount(); ++i) {
    if (metaObject->method(i).methodType() == QMetaMethod::Slot) {
        methods << QString::fromLatin1(metaObject->method(i).signature());
    }
}

To check whether the method is a slot or a signal, you can use QMetaMethod::methodType() function. For signature use QMetaMethod::signature() (refer to the example above).

QMetaObject reference