如何用qstring数组调用QMetaMethod

How to invoke QMetaMethod with an array of QStrings?

本文关键字:调用 QMetaMethod 数组 qstring 何用      更新时间:2023-10-16

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。