gpt4 book ai didi

c++ - 具有输出参数的 Qt invokeMethod 调用函数

转载 作者:行者123 更新时间:2023-11-30 03:25:35 25 4
gpt4 key购买 nike

我正在尝试找出 QMetaObject::invokeMethod 的用法。我有一个函数,它有一个参数(非 const QString),我希望它是输出,该函数没有返回值,对其调用 invokeMethod 总是失败,而另一个具有返回值且没有参数的函数可以被调用成功地。这是代码:

我的类.h

#include <QDebug>

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

我的类.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;
}

主要.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

我试了很多方法,都不行,有谁知道原因吗?提前致谢!

最佳答案

使用 Q_RETURN_ARG 时是获取方法返回的值,但如果你想传递一些参数,你必须使用 Q_ARG :

#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_ARG(QString &, msg));
qDebug() << "func2 returns" << val;

int ret = a.exec();
return ret;
}

输出:

"func succeeded"
func returns true
"func2 succeeded"
func2 returns true

关于c++ - 具有输出参数的 Qt invokeMethod 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48959156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com