如何用qstring数组调用QMetaMethod
How to invoke QMetaMethod with an array of QStrings?
QMetaObject系统提供了一些基本的反射API。我想做的是调用给定的槽或方法,通过这个系统是可用的。
但是,方法的参数和名称最初都是QString值。文档给出了一个示例:
QString retVal; QByteArray normalizedSignature = QMetaObject::normalizedSignature("compute(QString, int, double)"); int methodIndex = obj->metaObject()->indexOfMethod(normalizedSignature); QMetaMethod method = obj->metaObject()->method(methodIndex); method.invoke(obj, Qt::DirectConnection, Q_RETURN_ARG(QString, retVal), Q_ARG(QString, "sqrt"), Q_ARG(int, 42), Q_ARG(double, 9.7));
如果"compute"槽没有接受的一个QString,一个int和,调用将失败。
我特别强调。在这个例子中,我很无知。它显然使用了模板,而模板在动态上下文中是无用的。当我可以直接调用这个方法时,我真的看不出静态地使用这个API有什么目的。
假设我有这样一个函数:
void invokeSlot(QObject* target, const QString& slotName, const QStringList& arguments) {
// This is how I can get list of overloads by given name
const QMetaObject* obj = target_->metaObject();
QList<QMetaMethod> overloads;
for (int i = 0, l = obj->methodCount(); i < l; ++i) {
const QMetaMethod method = obj->method(i);
if( method.name() == name )
overloads.append(method);
}
// Now how to convert the arguments?
}
你可以假设我已经为类型转换准备了这个方法:
QVariant convertType(const QString& source, const QVariant::Type requiredType);
但是如何传递参数,即使我选择正确的重载和转换字符串所需类型的qvariant ?
你可以准备这个函数:
QGenericArgument convertType(const QString& source, const QVariant::Type requiredType);
通过在其中使用switch
es和Q_ARG
。
然后是一个大的switch
,其中包含invoke
s。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- 变量没有改变?通过向量的函数调用
- 没有为自己的结构调用列表推回方法
- 调用'begin(int [n])'没有匹配函数
- 什么时候调用析构函数
- 如何用参数值调用函数(仅在运行时已知)
- std::cout.imbue()多重调用
- 如何用qstring数组调用QMetaMethod