Qt QMetaObject::invokeMethod

简介

QMetaObject::invokeMethod是一个静态函数,用于在Qt信号槽机制之外,异步调用QObject子类的公开槽函数或者调用任意可调用对象。主要处理不同线程异步调用或延时操作。


参数

复制代码
bool QMetaObject::invokeMethod(QObject *obj, 
                              const char *member,
                              Qt::ConnectionType type = Qt::AutoConnection,
                              QGenericReturnArgument ret = QGenericReturnArgument(),
                              QGenericArgument val0 = QGenericArgument(),
                              QGenericArgument val1 = QGenericArgument(),
                              QGenericArgument val2 = QGenericArgument(),
                              QGenericArgument val3 = QGenericArgument(),
                              QGenericArgument val4 = QGenericArgument(),
                              QGenericArgument val5 = QGenericArgument(),
                              QGenericArgument val6 = QGenericArgument(),
                              QGenericArgument val7 = QGenericArgument(),
                              QGenericArgument val8 = QGenericArgument(),
                              QGenericArgument val9 = QGenericArgument());
  • obj:调用槽函数的对象指针。
  • member:槽函数的名字,以字符串的方式。
  • type:连接类型,默认为 Qt::AutoConnection,可以根据需要选择 Qt::DirectConnection(直接连接,同步调用)或 Qt::QueuedConnection(队列连接,异步调用)
  • ret:返回值,需要用QGenericReturnArgument包装。
  • val:槽函数的参数,需要用QGenericArgument包装。

示例:

void test(); //无参数

bool testSlot(int value); //带参数

复制代码
//异步执行test函数
QMetaObject::invokeMethod(this, "test", Qt::QueuedConnection);

int arg = 666;
QGenericArgument  argVa1("value", &arg);
QGenericReturnArgument ret("result", &returnValue);
QMetaObject::invokeMethod(myObject,"testSlot",Qt::QueuedConnection,ret,argVa1);

注意:

调用槽函数时,必须确保被调用的对象存在且它所在的线程已经进入了事件循环(GUI线程就是事件循环线程)。如果不在GUI现场,则需要保证对象的生命周期足够长,知道参函数被调用完成为止。

相关推荐
用户805533698031 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner1 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz6 天前
QML Hello World 入门示例
qt
xcyxiner9 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner10 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner10 天前
DicomViewer (添加模型类)3
qt
xcyxiner11 天前
DicomViewer (目录调整) 2
qt
xcyxiner11 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
LDR00613 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术13 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript