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);//關聯槽函數