三、qml调用Q_INVOKABLE方法

来源:互联网 发布:淘宝中国造 编辑:程序博客网 时间:2024/06/05 08:49
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_OBJECT
public:
//构造函数
MyTitle();
//析构函数
~ MyTitle();
//方法声明
Q_INVOKABLE QStringshowTitle();
};

#endif // MYTITLE_H
2)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.7
import QtQuick.Window 2.2
//与3)中的路径一致,别忘了版本号
importna.qt.mytitle1.0

Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")

//对象实例化
MyTitle{
id:mt
}

Text {
id: text
text:qsTr(mt.showTitle())//方法使用
}
}
0 0
原创粉丝点击