Qt文档阅读笔记-Q_INVOKABLE官方解析及Qt中反射的使用
Q_INVOKABLE宏定義了函數(shù)在元對(duì)象中可以進(jìn)行調(diào)用,這個(gè)宏要寫到返回值的前面,也就是函數(shù)的開頭,如下例子:
class Window : public QWidget{Q_OBJECTpublic:Window();void normalMethod();Q_INVOKABLE void invokableMethod();};invokeableMethod()可以調(diào)用用Q_INVOKABLE修飾過(guò)的函數(shù)。加了Q_INVOKABLE的宏注冊(cè)到元對(duì)象系統(tǒng)里面,并且能夠被元對(duì)象系統(tǒng)使用,普通的沒(méi)有注冊(cè)過(guò)的函數(shù)是不能被使用的。如果是調(diào)用QML中的函數(shù),返回的值是QObject指針或者QObject的衍生類指針,那么需要查看這個(gè)規(guī)則Data Type Conversion Between QML and C++在此不介紹此規(guī)則。
?
下面是博主的小栗子,Qt中使用反射。
反射這個(gè)在Java中相當(dāng)重要,很多結(jié)構(gòu)型和行為型的設(shè)計(jì)模式使用到反射,就會(huì)顯得簡(jiǎn)單得多。
在部分的功能里面用反射也可以省略掉很多亂七八糟的板磚代碼。
程序運(yùn)行截圖如下:
項(xiàng)目結(jié)構(gòu)如下:
源碼如下:
ReflectTest.h
#ifndef REFLECTTEST_H #define REFLECTTEST_H#include <QObject>class ReflectTest : public QObject {Q_OBJECT public:ReflectTest(QObject *parent = nullptr);Q_INVOKABLE void setPrint(const QString &print);Q_INVOKABLE QString getPrint();Q_INVOKABLE QString testFunction(QString para);private:QString m_print;};#endif // REFLECTTEST_Hmain.cpp
#include <QCoreApplication> #include <QDebug> #include <QMetaObject> #include <QMetaMethod> #include "ReflectTest.h"int main(int argc, char *argv[]) {QCoreApplication a(argc, argv);ReflectTest test1;test1.setPrint("one");qDebug() << test1.getPrint();qDebug() << "----------華麗的分割線----------";int count = test1.metaObject()->methodCount();for(int i = 0; i < count; i++){qDebug() << test1.metaObject()->method(i).name();}qDebug() << "----------華麗的分割線----------";qDebug() << test1.getPrint();qDebug() << QMetaObject::invokeMethod(&test1, "setPrint", Qt::DirectConnection, Q_ARG(QString, "one+one"));QString retVal;QMetaObject::invokeMethod(&test1, "getPrint", Qt::DirectConnection, Q_RETURN_ARG(QString, retVal));qDebug() << retVal;QMetaObject::invokeMethod(&test1, "testFunction", Qt::DirectConnection, Q_RETURN_ARG(QString, retVal), Q_ARG(QString, "one+one+one"));qDebug() << retVal;return a.exec(); }ReflectTest.cpp
#include "ReflectTest.h"ReflectTest::ReflectTest(QObject *parent) : QObject(parent) {}void ReflectTest::setPrint(const QString &print) {m_print = print; }QString ReflectTest::getPrint() {return m_print; }QString ReflectTest::testFunction(QString para) {return "return:" + para; }源碼打包下載地址:
https://github.com/fengfanchen/Qt/tree/master/ReflectDemo
?
?
總結(jié)
以上是生活随笔為你收集整理的Qt文档阅读笔记-Q_INVOKABLE官方解析及Qt中反射的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Spring Boot笔记-线程池调度计
- 下一篇: cuda笔记-初始化矩阵及thread,