首页 > 学院 > 开发设计 > 正文

三、qml调用Q_INVOKABLE方法

2019-11-08 01:47:16
字体:
来源:转载
供稿:网友
qml调用Q_INVOKABLE关键字修饰的方法:1)C++类:方法的声明+实现2)main.cpp里注册3)qml里:引入注册的对象+对象实例化eg:1)MyTitle.h方法的声明#ifndef MYTITLE_H#define MYTITLE_H#include <QObject>//函数声明class MyTitle : public QObject{Q_OBJECTpublic://构造函数MyTitle();//析构函数~ MyTitle();//方法声明Q_INVOKABLE QStringshowTitle();};#endif // MYTITLE_H2)MyTitle.cpp 方法的实现#include "mytitle.h"#include <qdebug.h>//函数内容//构造函数MyTitle::MyTitle(){}MyTitle::~MyTitle(){}//函数的实现QStringMyTitle::showTitle(){return"hhh";}3)Main.cpp 注册对象#include <QGuiapplication>#include <QQmlApplicationEngine>#include <QtQml>#include <mytitle.h>int main(int argc, char *argv[]){QGuiApplication app(argc, argv);QQmlApplicationEngine engine;//注意:qmlRegisterType<>("包名【保证路径唯一】" ,主版本号, 次版本号,"类名【大写】")qmlRegisterType<MyTitle>("na.qt.mytitle",1,0,"MyTitle");engine.load(QUrl(QStringLiteral("qrc:/main.qml")));return app.exec();}4)qml 引入对象 + 对象实例化 + 使用对象调用方法import QtQuick 2.7import QtQuick.Window 2.2//与3)中的路径一致,别忘了版本号importna.qt.mytitle1.0Window {visible: truewidth: 640height: 480title: qsTr("Hello World")//对象实例化MyTitle{id:mt}Text {id: texttext:qsTr(mt.showTitle())//方法使用}}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表