Search code examples
c++qtqtcoremocqmetaobject

Qt metaObject->indexOfMethod always return -1


I have one function declared in Foo class:

Q_INVOKABLE void setImageUrl(const QString &imageUrl);

However I cannot get the function index of that method:

Foo* foo = new Foo();
const QMetaObject* metaObject = foo->metaObject();
QString functionNameWithparameter("setImageUrl(QString)");
int functionIndex = metaObject->indexOfMethod(functionNameWithParameter.toStdString().c_str());

if (functionIndex >= 0) {
 // never the case
}

What am I missing?


Solution

  • Apart from the two compiler errors, your approach seems to be correct. I assume that you had some changes that required to rerun moc, but you have not actually done so. This is the working code for me.

    main.cpp

    #include <QMetaObject>
    #include <QDebug>
    #include <QString>
    
    class Foo : public QObject
    {
        Q_OBJECT
        public:
            explicit Foo(QObject *parent = Q_NULLPTR) : QObject(parent) {}
        Q_INVOKABLE void setImageUrl(const QString &) {}
    };
    
    #include "main.moc"
    
    int main()
    {
        Foo* foo = new Foo();
        const QMetaObject* metaObject = foo->metaObject();
        QString functionNameWithParameter("setImageUrl(QString)");
        qDebug() << metaObject->indexOfMethod(functionNameWithParameter.toStdString().c_str());
        return 0;
    }
    

    main.pro

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

    Build and Run

    qmake && make && ./main
    

    Output

    5