With QML there is a new, fantastic way of creating a rich UI for desktop, mobile, and embedded apps. We will go over briefly the history of QML and how you can harness this new language to make your apps easier and faster to develop. We will go over the basics of QML, signals & slots, ways to protect the QML code and also talk about how to use QML with your C++ code. With QML in your tool belt, making Qt applications is quicker to develop and maintain.
2. History
• Started by Haavard Nord and Erik Chambe-Eng in 1991
• Founded Trolltech three years later
• Acquired by Nokia in 2008
• QML is created for mobile development (n900 and N1)
• Sold to Digia in 2011
• Transfered to QT Company
• Current version of QT is 5.9
3. QML
• Declarative JavaScript language with built in
hooks for Cpp
• All signal, slots and properties on a c++ class
are automatically exposed to QML
• Can expose C++ method with Q_INVOKABLE
• Prototype inheritance
4. Basic Types
QML C++
string QString
int int
bool bool
double double
real float
url QUrl
var QVariant
list QList
12. QML To C++
QList<QObject *> objList = engine.rootObjects();
QObject *qmlObject = nullptr;
qmlObject = objList[0];//assumes the top object has the
signal
QObject::connect(qmlObject, SIGNAL(click(QString)),
&cppObjWithSlot,
SLOT(processClick(QString)));
13. Exposing C++ to QML
• Signal and Slots
• Methods with Q_INVOKABLE
• Properties Q_PROPERTY
14. Assume the C++
class MessageBoard : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE bool postMessage(const QString &msg) ;
Q_PROPERTY(MessageBody* body READ body WRITE setBody NOTIFY bodyChanged)
signals:
void newMessagePosted(const QString &subject);
public slots:
void refresh();
};
int main(int argc, char *argv[]) {
MessageBoard msgBoard;
QQuickView view;
view.engine()->rootContext()->setContextProperty("msgBoard", &msgBoard);
view.setSource(QUrl::fromLocalFile("MyItem.qml"));
}
15. QML Calling C++
// MyItem.qml
import QtQuick 2.0
Item {
MouseArea {
anchors.fill: parent
onClicked: {
var result = msgBoard.postMessage("Hello from QML")
msgBoard.refresh();
}
MessageBoard {
body: MessageBody {
}
onNewMessagePosted: console.log("New message received:", subject)
}
}
}
16. Javascript in QML
• Can be in a binding
• Standalone function
• Imported from a .js file