Qt 的反射(Reflection)应用

反射, 在我看来 就是 运行时把字符串映射为类.

我不是很专业, 还望各位大佬嘴下留情.....

参考  https://blog.csdn.net/kenier/article/details/62041312
      https://blog.csdn.net/liulong1567/article/details/45273017

 第一种方式:

//
class TestReflection : public QObject
{
    Q_OBJECT
public:
    //此处必须使用 Q_INVOKABLE 
    Q_INVOKABLE explicit TestReflection(QObject *parent = nullptr):QObject(parent)
    {
        m_name.clear();
    }
    Q_INVOKABLE QString name() const 
    {
        return m_name;
    }
private:
    QString m_name;
};

    //调用
    qRegisterMetaType<TestReflection*>();
    int type = QMetaType::type("TestReflection*");

    const QMetaObject *metaObj = QMetaType::metaObjectForType(type);
    QObject *obj = metaObj->newInstance(Q_ARG(QString, QStringLiteral("Reflection")),
                                        Q_ARG(QObject*, nullptr));
    TestReflection *test = qobject_cast<TestReflection*>(obj);
    QString retVal;
    QMetaObject::invokeMethod(test, "name", Qt::DirectConnection,
                              Q_RETURN_ARG(QString, retVal));
    qDebug() << "result: " << retVal;

 第二种方式:

//
#include <QObject>
#include <QtDebug>
#include <QByteArray>
#include <QMetaObject>
#include <QHash>
class A : public QObject
{
    Q_OBJECT
public:
    A(QObject *p) : QObject(p)
    {
        qDebug() << Q_FUNC_INFO;
    }
    Q_INVOKABLE void name()
    {
        qDebug() << Q_FUNC_INFO;
    }
};

//
class ObjectFactory
{
public:
    template<typename T> static void registerClass()
    {
        qDebug() << "class name: [" << typeid(T).name() << "]";
        constructors().insert( T::staticMetaObject.className(), &constructorHelper<T> );
    }

    static QObject* createObject( const QByteArray& className, 
                                  QObject* parent = nullptr )
    {
        Constructor constructor = constructors().value( className );
        if ( constructor == nullptr )
            return nullptr;
        return (*constructor)( parent );
    }

private:
    typedef QObject* (*Constructor)( QObject* parent );

    template<typename T> static QObject* constructorHelper( QObject* parent )
    {
        return new T( parent );
    }

    static QHash<QByteArray, Constructor>& constructors()
    {
        static QHash<QByteArray, Constructor> instance;
        return instance;
    }
};

//调用
    ObjectFactory::registerClass<A>();
    A* object = (A*)ObjectFactory::createObject( "A" );
    if(object)
    {
        QMetaObject::invokeMethod(object, "name", Qt::DirectConnection);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值