qml 與 c++ 的美麗邂逅
TRANSCRIPT
回顧一下...QML是什麼 ?
● 描述性語言● property, method, signal
● javascript 控制
Ref: http://www.slideshare.net/jackyang5000/hello-qml-42873653
import QtQuick 2.3
import QtQuick.Window 2.2
Window {
visible: true
width: 360
height: 360
MouseArea {
anchors.fill: parent
onClicked: {
Qt.quit();
}
}
Text {
text: qsTr("Hello World")
anchors.centerIn: parent
}
}
複雜一些,我們可以做到這樣...
有了 QML還需要 C++ ?
如果要這樣...
或者這樣...
或這樣...
我們要如何讓 QML使用這些功能 ?
● 透過 c++ 使用 third-party library
● 讓資料的擷取, 儲存, 操作更為方便● Client/Server 架構
讓 Application更 powerful~
首先, 我們所認識的彼此...
C++ class
● member variable
● member function
● event notify
QML type
● property
● function
● signal
一個 Qt C++ class的概念
● Based on QObject
● Q_OBJECT
Tool: moc (meta-object compiler)o moc 參考 c++ header, 產生出 moc_className.cpp
o moc_className.cpp 描述 signals, slot, property
Ref: http://doc.qt.io/qt-5/metaobjects.html
Qt C++ object 對應到 QML object
● member variable by Q_PROPERTY
o -> QML property
● member function by Q_INVOKABLE prefix
o -> QML function
● event notify define in signals
o -> QML signal
* property/function name 都小寫開頭
方法一:將 C++嵌入至 QML
● QQmlContext::setContextObject
● QQmlContext::setContextProperty
Ref: http://doc.qt.io/qt-5/qtqml-cppintegration-
exposecppattributes.html
main.cpp
QML
方法二:註冊成為一個 QML type
● QML object typeo Rectangle, Text, Image, ListModel…
● Object type from QML documento MyButton.qml
● Object type from c++o Register c++ object to QML
#include <QtQml>
qmlRegisterType<className>(url, version major,
version minor, qml name)
Ref: http://doc.qt.io/qt-5/qtqml-cppintegration-
definetypes.html
qmlRegisterType
main.cpp
main.qml
方法三: QML plugin dll
如何製作 ? by QtCreator
設定 class 名稱 & QML import 路徑
QML 啟動時, 會去 call 此 plugin 的 registerType
Ref: http://doc.qt.io/qt-5/qtqml-modules-cppplugins.html
qmldir
module HanGee.Hackathon (qml import 路徑)
plugin TestQmlExtPlugin (dll 名稱)
QML如何使用 plugin dll ?
方法一:
方法二: 設環境變數
Windows: set QML2_IMPORT_PATH=your_plugin_dir
Linux:export QML2_IMPORT_PATH = /your_plugin_dir
開始讓你 QML更強大吧 !!