當前位置:
首頁 >
Qt文档阅读笔记-Q_INVOKABLE官方解析及Qt中反射的使用
發布時間:2025/3/15
25
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Qt文档阅读笔记-Q_INVOKABLE官方解析及Qt中反射的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Q_INVOKABLE宏定義了函數在元對象中可以進行調用,這個宏要寫到返回值的前面,也就是函數的開頭,如下例子:
class Window : public QWidget{Q_OBJECTpublic:Window();void normalMethod();Q_INVOKABLE void invokableMethod();};invokeableMethod()可以調用用Q_INVOKABLE修飾過的函數。加了Q_INVOKABLE的宏注冊到元對象系統里面,并且能夠被元對象系統使用,普通的沒有注冊過的函數是不能被使用的。如果是調用QML中的函數,返回的值是QObject指針或者QObject的衍生類指針,那么需要查看這個規則Data Type Conversion Between QML and C++在此不介紹此規則。
?
下面是博主的小栗子,Qt中使用反射。
反射這個在Java中相當重要,很多結構型和行為型的設計模式使用到反射,就會顯得簡單得多。
在部分的功能里面用反射也可以省略掉很多亂七八糟的板磚代碼。
程序運行截圖如下:
項目結構如下:
源碼如下:
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
?
?
總結
以上是生活随笔為你收集整理的Qt文档阅读笔记-Q_INVOKABLE官方解析及Qt中反射的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Boot笔记-线程池调度计
- 下一篇: cuda笔记-初始化矩阵及thread,