简体   繁体   中英

How to get class function names list? Qt C++

For example I do have this code:

class MyClass : public QObject
{
    Q_OBJECT
public:
    void MyClass()
    {
    QStringList selfFunctionList;
    //Get functions list
    qDebug()<<selfFunctionList;
    }
    void function1(){}
    void function435(){}
};

How do I set to selfFunctionList list of "function1" and "function435"?

You can use the staticMetaObject for that.

class Test : public QObject
{
    Q_OBJECT
public:
    explicit Test(QObject *parent = 0) :
        QObject(parent)
    {
        for (int n = 0; n < staticMetaObject.methodCount(); n++) {
           functions.append(QString::fromLocal8Bit(staticMetaObject.method(n).name()));
        }
        qDebug() << functions;
    }

signals:
    void testSignal();

private slots:   
    void privateTestFunction() {}

public slots:   
    void publicTestFunction() {}

private:
    QStringList functions;
};

One condition, the functions need to be declared as slots or signal.

Output:

("destroyed","destroyed","objectNameChanged","deleteLater","_q_reregisterTimers",
"testSignal","privateTestFunction","publicTestFunction")

C++ does not have the sort of self-awareness ( reflection ) you seem to want here. That is, there is no programmatic way to get the string name of a function and enter it into a container without hand-coding it. Qt does a very limited amount of this with its signals and slots, but not functions in general. So you will have to write

MyClass::MyClass(...)
{
   selfFunctionList << function1 << function345 << ... etc.
}

as the constructor, or something thing similar.

Edit : OP brought these macros to my attention which give you a bit of introspection, but implementing them to solve OP's problem would be far more arduous than the above, see comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM