invokeMethod 的使用



  • 想搞清楚invokeMethod用法,函数func2,无返回值,有一个non const 输出参数,用 invokeMethod调用, 总是失败,而另一个函数func,有返回值,没有任何参数,用 invokeMethod调用就能成功,这两个函数功效一样,就想知道怎样调用 func2才是正确的。代码如下:
    myclass.h
    #include <QDebug>

    class MyClass: public QObject
    {
        Q_OBJECT
    public:
        MyClass() {}
        ~MyClass() {}
    public slots:
        QString func();
        void func2(QString& res);
    };
    

    myclass.cpp

    #include "myclass.h"
    
    QString MyClass::func()
    {
        QString res = "func succeeded";
    	qDebug() << res;
        return res;
    }
    
    void MyClass::func2(QString& res)
    {
        res = "func2 succeeded";
        qDebug() << res;
        return;
    }
    

    main.cpp

    #include <QCoreApplication>
    #include "myclass.h"
    
    int main(int argc, char *argv[])
    {
        QString msg;
        MyClass myobj;
    
        QCoreApplication a(argc, argv);
    
        bool val = QMetaObject::invokeMethod(&myobj, "func", Q_RETURN_ARG(QString, msg));
        qDebug() << "func returns" << val;
    
        val = QMetaObject::invokeMethod(&myobj, "func2", Q_RETURN_ARG(QString, msg));
        qDebug() << "func2 returns" << val;
    
        int ret = a.exec();
        return ret;
    }
    

    运行结果:
    $ ./test
    "func succeeded"
    func returns true
    QMetaObject::invokeMethod: No such method MyClass::func2()
    Candidates are:
    func2(QString&)
    func2 returns false

    试了几种调用 func2的方法,总有各种各样的错误。请高手解答。


  • Moderators

    @Tegan 如果 func2 无返回值,那么您不应该使用 Q_RETURN_ARG

    请阅读 https://doc.qt.io/qt-5/qmetaobject.html#invokeMethod

    QString text = "Hello";
    QMetaObject::invokeMethod(&myobj, "func2", Q_ARG(QString, text));
    

    从Qt 5.10开始,您也可以使用:

    // Function pointer
    QString msg;
    QMetaObject::invokeMethod(&myobj, &MyClass::func, &msg);
    qDebug() << "Return value:" << msg;
    
    // Lambda
    QMetaObject::invokeMethod(&myobj, [&myObj]
    {
        myObj.func2("Hello");
    });
    

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.