











对象A通过信号sginal1链接 子线程的成员对象B的槽函数slot1。
则 emit sginal1 后会在子线程中调用槽函数1
伪代码
Qthread b;
B.movethread(&b);
connect(&A,SIGNAL(XXX()),&B,SLOT(YYY()));
通过 QMetaObject::InvokedMethod(...) 直接调用 子线程的成员变量槽函数,或用 Q_INVOKABLE 标识的函数。
下面对第二种方法 介绍
bool QMetaObject::invokeMethod(
QObject *obj,
const char *method,
Qt::ConnectionType type,
QGenericReturnArgument ret,
QGenericArgument val0 = QGenericArgument(nullptr),
QGenericArgument val1 = QGenericArgument(),
...
);
调用示例:
// 目标方法(在某个 QObject 派生类中)
Q_INVOKABLE void myMethod(int num, const QString &text);
// 调用代码
int value = 42;
QString text = "Hello";
QMetaObject::invokeMethod(
obj,
"myMethod",
Qt::AutoConnection,
Q_ARG(int, value),
Q_ARG(QString, text)
);
需要先注册自定义类型到 Qt 的元类型系统:
// 在头文件中声明自定义类型
struct MyCustomType {
int id;
QString name;
};
Q_DECLARE_METATYPE(MyCustomType)
qRegisterMetaType("MyCustomType");
// 目标方法
Q_INVOKABLE void handleCustomType(const MyCustomType &data);
// 调用代码
MyCustomType data;
data.id = 1;
data.name = "Test";
QMetaObject::invokeMethod(
obj,
"handleCustomType",
Qt::AutoConnection,
Q_ARG(MyCustomType, data)
);
如果方法有返回值,使用 Q_RETURN_ARG 捕获:
// 目标方法
Q_INVOKABLE int calculate(int a, int b);
// 调用代码
int result;
QMetaObject::invokeMethod(
obj,
"calculate",
Qt::DirectConnection,
Q_RETURN_ARG(int, result),
Q_ARG(int, 3),
Q_ARG(int, 5)
);
qDebug() << "Result:" << result; // 输出 8
指定 Qt::QueuedConnection 进行异步调用:
QMetaObject::invokeMethod(
obj,
"updateUI",
Qt::QueuedConnection,//*****************88
Q_ARG(QString, "New Text")
);
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。