Qt中使用qml的方法

1.1包含头文件//以下头文件均为 <>包含,因为编辑不允许所以使用""
#include “QApplication”
#include “QGuiApplication”
#include “QQmlApplicationEngine”
#include “QtQml”
#include “QQuickView”
#include <qtextcodec.h>
#include <qresource.h>
#include <qstring.h>

1.2 注册c++类到qml中
qmlRegisterType(“TestQt”, 1, 0, “testControl”);
其中testControl为c++类的名称,TestQt为qml使用的数据
当qml要使用testControl的类时,需要包含import TestQt1.0

注意:1.在Qt5.12.2中,在<>内,内的首字母需要大写
2.testControl类要集成QObject类

1.3 加载qml的启始文件
QQmlApplicationEngine engine;
// Register the property to QML
RegisterToQml(engine);
engine.load(QUrl(QStringLiteral(“qrc:///main.qml”)));

这个若用Qt Creator创建项目,会自动生成

1.4 qml使用的c++类的标准
void RegisterToQml(QQmlApplicationEngine& engine)
{
engine.rootContext()->setContextProperty(“myTestControl”, &STestControlUtility::getInstance());
}
其中"myTestControl"用于qml使用testControl类中函数的关联关键字
STestControlUtility::getInstance()为testControl类的实例化(单例)

1.5 c++类中将函数注册到qml中
(1)注册c++的函数到qml
Q_INVOKABLE void requestRecord(void);
只要在正常函数前面加了Q_INVOKABLE 关键字即可
使用方法:myTestControl.requestRecord()

(2)注册属性到qml
Q_PROPERTY(QString strASR READ getASRTxt NOTIFY notifyASRTxtChaned)
strASR为qml能使用的属性
getASRTxt为获取属性值的函数
notifyASRTxtChaned为信号,用于通知什么时候去调用getASRTxt()
使用方法:myTestControl.strASR

当检测到定义的值发生变化后,使用:emit notifyASRTxtChaned(); 即可

1.6 connect的使用
普通connect
connect(&STestControlUtility::getInstance(),SIGNAL(notifyPlayTTS()),this,SLOT(onNotifyPlayTTS()),Qt::QueuedConnection);

定时器使用:
#include
QTimer m_backTopPageTimer;

m_backTopPageTimer.start(5000);//启动定时器

connect(&m_backTopPageTimer, SIGNAL(timeout()), this, SLOT(onNotifyBackTopPage()),Qt::QueuedConnection);//关联槽函数

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值