SlideShare a Scribd company logo
© Integrated Computer Solutions, Inc. All Rights Reserved
Best Practices in Qt
Quick/QML - Part 1
Justin Noel
Senior Consulting Engineer
ICS, Inc.
© Integrated Computer Solutions, Inc. All Rights Reserved
Agenda
• Building Blocks of QML
• Qt Properties
• Declarative Code
• Anchors
© Integrated Computer Solutions, Inc. All Rights Reserved
Building Blocks of QML
© Integrated Computer Solutions, Inc. All Rights Reserved
QObject
• Heart and Soul of Qt Object
• Signals and Slots are implemented here
• QObjects can have “child objects”
• Parents have some control over children
• Deleting them, laying them out, etc
• Also Qt Properties!
© Integrated Computer Solutions, Inc. All Rights Reserved
Introspection
• QObjects can report at runtime
• Class name, Super class
• Lists of signals and list their arguments
• Lists of functions and list their arguments
• Invoke methods by name
• QMetaObject::invokeMethod(objPtr,
“function”…)
© Integrated Computer Solutions, Inc. All Rights Reserved
Meta Object Compiler
• Introspection info is generated by moc
• Reads header files. Writes source code
• moc -o moc_class.cpp class.h
• MetaObject is static
• One instance per QObject subclass
© Integrated Computer Solutions, Inc. All Rights Reserved
QQuickItem
• Most Qt Objects inherit QObject
• QQuickItem is no exception
• Gets many of it’s features directly from QObject
• We will be leveraging these capabilities throughout
class
© Integrated Computer Solutions, Inc. All Rights Reserved
Deferred Deletion
• Qt is an event driven GUI toolkit
• Deleting object can be tricky in an event based
system
• Deleting objects from within an event
• Deleting the sender object from a signal and slot
connection
• QObject has a deleteLater() method
© Integrated Computer Solutions, Inc. All Rights Reserved
deleteLater()
• Posts an event to the event loop
• On the next lap of the loop
• The object is deleted and all events cleared
• destroy() in QML is QObject::deleteLater()
© Integrated Computer Solutions, Inc. All Rights Reserved
QVariant
• Qt’s “Anything” class
• Think: Typed void*
• Supports most Qt data types out of the box
• Easy to add support for your own types
• Automatically supports all pointer types
© Integrated Computer Solutions, Inc. All Rights Reserved
QVariant and QML
• QVariant maps to var in JavaScript
• Used to pass data back and forth to C++
• If you register your types correctly you can attain
runtime type safety
© Integrated Computer Solutions, Inc. All Rights Reserved
QVariant Containers
• QVariantList maps to Array in JavaScript
• QList<QVariantMap> can be used with JSON syntax
JavaScript
• Better off using QJson classes
• If you are using JSON data
• Easier to convert back to JSON
© Integrated Computer Solutions, Inc. All Rights Reserved
Qt Properties
© Integrated Computer Solutions, Inc. All Rights Reserved
Qt Properties
• Combination of Get/Set/Notify
• Allows introspection system to use these functions
as one concept
• Properties have been in Qt for a very long time
• Qt Designer is based on properties
• QML is also based on properties
© Integrated Computer Solutions, Inc. All Rights Reserved
Declaration of a Qt Property
#include <QObject>
class Car : public QObject
{
Q_OBJECT
Q_PROPERTY(int value READ value
WRITE setValue
NOTIFY valueChanged)
public:
int getValue() const;
void setValue(int newValue);
signals:
void valueChanged(int value);
};
© Integrated Computer Solutions, Inc. All Rights Reserved
Qt Property with Enum
#include <QObject>
class Car : public QObject
{
Q_OBJECT
Q_PROPERTY(KeyState keyState READ keyState
NOTIFY keyStateChanged)
public:
enum KeyState {
KeyOff,
KeyOn,
KeyStart
} Q_ENUM(KeyState);
[...]
};
© Integrated Computer Solutions, Inc. All Rights Reserved
Qt Properties in C++
void someFunction(Qobject* obj)
{
// Getting
QVariant propValue = obj->property(“value”);
qDebug() << propValue.typeName() << propValue.toInt();
//Setting
QVariant newValue = QVariant::fromValue(Car::KeyOn);
obj->setProperty(“keyState”, newValue);
}
© Integrated Computer Solutions, Inc. All Rights Reserved
Dynamic Propeties
• Properties are Key-Value Pairs
• QObject can create properties on demand
• Less type safe, but perfectly useful for QML
obj->setProperty(“newPropName”, 1);
obj->setProperty(“another”, “Value”);
int propInt = obj->property(“newPropName”).toInt();
QString propString = obj->property(“another”).toString();
© Integrated Computer Solutions, Inc. All Rights Reserved
Declarative Code
© Integrated Computer Solutions, Inc. All Rights Reserved
Basic QML Syntax
• QML is declarative language
• With hooks for procedural JavaScript
• Use as little JavaScript as possible
• QML files a read at runtime
• The declarative parts create C++ instances
• JavaScript is JIT interpreted
© Integrated Computer Solutions, Inc. All Rights Reserved
QtQuick Hello World
import QtQuick 2.2
Rectangle{
id: toplevel
color: “blue”
Text {
text: “Hello World”
}
MouseArea {
anchors.fill: parent
onClicked: Qt.quit()
}
}
© Integrated Computer Solutions, Inc. All Rights Reserved
Qt Quick Items
• Rectangle, Text and MouseArea
• Are implemented in C++
• Instances of QQuickRectangle, QQuickText, Etc
• Loading QML is slower than compiled code
• At runtime performance is great
© Integrated Computer Solutions, Inc. All Rights Reserved
QML Bindings
• “:” is the binding operator
• Right of the binding operator is JavaScript
• Text {
text: “Hello World ” + Math.rand()
}
© Integrated Computer Solutions, Inc. All Rights Reserved
Bindings are Declarative
• When any property used in a binding changes the
expression is recalculated
Gauge {
value: Math.min(gaugeMax, Math.max(gaugeMin, oilPressure.value))
}
• Value is updated whenever properties
change
• gaugeMax, gaugeMin or oilPressure.value
© Integrated Computer Solutions, Inc. All Rights Reserved
JavaScript is Procedural
• Avoid this!
Gauge {
Component.onCompleted: {
setGaugeValue(oilPressure.value)
oilPressure.valueChanged.connect(setGaugeValue)
}
onGaugeMinChanged: setGaugeValue(value)
onGaugeMaxChanged: setGaugeValue(value)
function setGaugeValue(oilValue) {
value = Math.min(gaugeMax, Math.max(gaugeMin, oilValue))
}
}
© Integrated Computer Solutions, Inc. All Rights Reserved
Broken Bindings
• Assignment operator breaks bindings
• Binding works for awhile. Then doesn’t.
• Solution: Use states or Qt.binding(function(){…})
• More in later in the webinar series
Gauge {
id: gauge
visible: Dashboard.isOilPressureVisible
}
Button {
onClicked: { // Tries to temporarily hide gauge
if(gauge.visible)
gauge.visible = false
else
gauge.visible = Dashboard.isOilPressureVisible
}
}
© Integrated Computer Solutions, Inc. All Rights Reserved
Anchors
© Integrated Computer Solutions, Inc. All Rights Reserved
Dead Reckoning Layout
Item {
width: 800; height: 400;
Rectangle {
id:rectA
color: 'red‘
height: 50 ; width: 70
x: 0; y: 0
}
Rectangle {
id:rectB
color: 'blue‘
height: rectA.height * 2; width: rectA.width * 2
x: 0; y: 100
}
}
© Integrated Computer Solutions, Inc. All Rights Reserved
Why is dead reckoning bad?
• The good:
• It resizes correctly
• It uses bindings so it’s “declarative”
• The bad:
• There are a lot of binding re-calculations
• Each recalculation is run in JavaScript
• Cascading bindings cause intermediate states
© Integrated Computer Solutions, Inc. All Rights Reserved
Binding Recalculation
• This example has ~40 items
• If each item needs 2 bindings
• 80 Recalculations on resize
• Not including intermediate states
© Integrated Computer Solutions, Inc. All Rights Reserved
Intermediate States
Example 2.2. src/anchors/tst_bindings_1.qml
Item {
property int c: a + b
property int a
property int b: a
onAChanged: console.log("a == " + a)
onBChanged: console.log("b == " + b)
onCChanged: console.log("c == " + c)
Component.onCompleted: a = 1
}
Output:
a == 1
c == 1
b == 1
c == 2
© Integrated Computer Solutions, Inc. All Rights Reserved
Anchors Are Better!
• Anchors are stored and calculated in C++
• Remember all Items are actually C++ instances
• Anchors let you attach an item to other items
• Parent item
• Any sibling item
• Anyone remember the Motif Form Widget?
• Eerily similar. What’s old is new again!
© Integrated Computer Solutions, Inc. All Rights Reserved
Anchor Lines
• There are 6 anchors lines all Items have
• Text item has a 7th anchor called baseline
• Bottom of text without descenders
© Integrated Computer Solutions, Inc. All Rights Reserved
Setting Anchors
Rectangle {
width: 800; height:600
Rectangle {
id: rect1
width: 400
anchors.top: parent.top
anchors.bottom: parent.bottom
}
Rectangle {
id: rect2
anchors {
top: parent.top; bottom: parent.bottom
left: rect1.right; right: parent.right
}
}
}
© Integrated Computer Solutions, Inc. All Rights Reserved
Anchor Margins
• Each item has 6 adjustable margins
• Not shown are [horizontal|vertical]CenterOffset
• Text has a baselineOffset margin
• anchors.margins sets all outer margins at once
© Integrated Computer Solutions, Inc. All Rights Reserved
Complex Anchors
• Set multiple anchors at once
• anchors.fill: anotherItem
• Sets left, right, top and bottom
• Can use all outer margins
• anchors.centerIn: anotherItem
• Sets horizontalCenter and verticalCenter
• Can use horizontal and vertical offsets
© Integrated Computer Solutions, Inc. All Rights Reserved
Best Practices in Qt Quick/QML
- Part 2
June 22, 1 pm EDT
https://www.ics.com/webinar/best-practices-qt-quickqml-part-2
© Integrated Computer Solutions, Inc. All Rights Reserved
Thank You!
Justin Noel
Senior Consulting Engineer
ICS, Inc.

More Related Content

What's hot (20)

PPTX
Qt Qml
Steven Song
 
PDF
Qt multi threads
Ynon Perek
 
PPTX
Qt for beginners part 1 overview and key concepts
ICS
 
PDF
Qt Application Programming with C++ - Part 1
Emertxe Information Technologies Pvt Ltd
 
PDF
Best Practices in Qt Quick/QML - Part IV
ICS
 
PDF
Basics of Model/View Qt programming
ICS
 
PPTX
UI Programming with Qt-Quick and QML
Emertxe Information Technologies Pvt Ltd
 
PDF
Qt Application Programming with C++ - Part 2
Emertxe Information Technologies Pvt Ltd
 
PDF
Best Practices in Qt Quick/QML - Part III
ICS
 
PPTX
Qt Framework Events Signals Threads
Neera Mital
 
PDF
Qt programming-using-cpp
Emertxe Information Technologies Pvt Ltd
 
PPTX
Hello, QML
Jack Yang
 
PDF
QVariant, QObject — Qt's not just for GUI development
ICS
 
PDF
02 - Basics of Qt
Andreas Jakl
 
ODP
Qt 5 - C++ and Widgets
Juha Peltomäki
 
PDF
Qt and QML performance tips & tricks for Qt 4.7
Pasi Kellokoski
 
PDF
Qt for Beginners Part 3 - QML and Qt Quick
ICS
 
PDF
Qt Design Patterns
Ynon Perek
 
PDF
Introduction to Qt Creator
Qt
 
PPT
Qt Technical Presentation
Daniel Rocha
 
Qt Qml
Steven Song
 
Qt multi threads
Ynon Perek
 
Qt for beginners part 1 overview and key concepts
ICS
 
Qt Application Programming with C++ - Part 1
Emertxe Information Technologies Pvt Ltd
 
Best Practices in Qt Quick/QML - Part IV
ICS
 
Basics of Model/View Qt programming
ICS
 
UI Programming with Qt-Quick and QML
Emertxe Information Technologies Pvt Ltd
 
Qt Application Programming with C++ - Part 2
Emertxe Information Technologies Pvt Ltd
 
Best Practices in Qt Quick/QML - Part III
ICS
 
Qt Framework Events Signals Threads
Neera Mital
 
Hello, QML
Jack Yang
 
QVariant, QObject — Qt's not just for GUI development
ICS
 
02 - Basics of Qt
Andreas Jakl
 
Qt 5 - C++ and Widgets
Juha Peltomäki
 
Qt and QML performance tips & tricks for Qt 4.7
Pasi Kellokoski
 
Qt for Beginners Part 3 - QML and Qt Quick
ICS
 
Qt Design Patterns
Ynon Perek
 
Introduction to Qt Creator
Qt
 
Qt Technical Presentation
Daniel Rocha
 

Similar to Best Practices in Qt Quick/QML - Part 1 of 4 (20)

PDF
Porting Motif Applications to Qt - Webinar
ICS
 
PDF
Porting Motif Applications to Qt - Webinar
Janel Heilbrunn
 
PDF
Fun with QML
ICS
 
PDF
Best Practices in Qt Quick/QML - Part 2
ICS
 
PDF
Best Practices in Qt Quick/QML - Part 2
Janel Heilbrunn
 
ZIP
Building Web Apps Sanely - EclipseCon 2010
Chris Ramsdale
 
PPTX
Robust C++ Task Systems Through Compile-time Checks
Stoyan Nikolov
 
PPTX
Getting Started with Datatsax .Net Driver
DataStax Academy
 
ODP
Qt Workshop
Johan Thelin
 
ODP
Treinamento Qt básico - aula II
Marcelo Barros de Almeida
 
PDF
Qt for beginners part 4 doing more
ICS
 
PDF
Petri Niemi Qt Advanced Part 2
NokiaAppForum
 
PDF
Ceilometer + Heat = Alarming
Nicolas (Nick) Barcet
 
PPTX
Cassandra Day NY 2014: Getting Started with the DataStax C# Driver
DataStax Academy
 
ZIP
Google Developer Fest 2010
Chris Ramsdale
 
KEY
JBoss World 2010
Chris Ramsdale
 
PDF
Hybrid Apps (Native + Web) via QtWebKit
Ariya Hidayat
 
PDF
Scripting Your Qt Application
account inactive
 
PDF
Introduction to the Qt Quick Scene Graph
ICS
 
PPTX
Javascript
Sun Technlogies
 
Porting Motif Applications to Qt - Webinar
ICS
 
Porting Motif Applications to Qt - Webinar
Janel Heilbrunn
 
Fun with QML
ICS
 
Best Practices in Qt Quick/QML - Part 2
ICS
 
Best Practices in Qt Quick/QML - Part 2
Janel Heilbrunn
 
Building Web Apps Sanely - EclipseCon 2010
Chris Ramsdale
 
Robust C++ Task Systems Through Compile-time Checks
Stoyan Nikolov
 
Getting Started with Datatsax .Net Driver
DataStax Academy
 
Qt Workshop
Johan Thelin
 
Treinamento Qt básico - aula II
Marcelo Barros de Almeida
 
Qt for beginners part 4 doing more
ICS
 
Petri Niemi Qt Advanced Part 2
NokiaAppForum
 
Ceilometer + Heat = Alarming
Nicolas (Nick) Barcet
 
Cassandra Day NY 2014: Getting Started with the DataStax C# Driver
DataStax Academy
 
Google Developer Fest 2010
Chris Ramsdale
 
JBoss World 2010
Chris Ramsdale
 
Hybrid Apps (Native + Web) via QtWebKit
Ariya Hidayat
 
Scripting Your Qt Application
account inactive
 
Introduction to the Qt Quick Scene Graph
ICS
 
Javascript
Sun Technlogies
 
Ad

More from ICS (20)

PDF
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
PDF
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
PDF
Exploring Wayland: A Modern Display Server for the Future
ICS
 
PDF
Threat Modeling & Risk Assessment Webinar: A Step-by-Step Example
ICS
 
PDF
8 Mandatory Security Control Categories for Successful Submissions
ICS
 
PDF
Future-Proofing Embedded Device Capabilities with the Qt 6 Plugin Mechanism.pdf
ICS
 
PDF
Choosing an Embedded GUI: Comparative Analysis of UI Frameworks
ICS
 
PDF
Medical Device Cyber Testing to Meet FDA Requirements
ICS
 
PDF
Threat Modeling and Risk Assessment Webinar.pdf
ICS
 
PDF
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
ICS
 
PDF
Webinar On-Demand: Using Flutter for Embedded
ICS
 
PDF
A Deep Dive into Secure Product Development Frameworks.pdf
ICS
 
PDF
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
ICS
 
PDF
Practical Advice for FDA’s 510(k) Requirements.pdf
ICS
 
PDF
Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...
ICS
 
PDF
Overcoming CMake Configuration Issues Webinar
ICS
 
PDF
Enhancing Quality and Test in Medical Device Design - Part 2.pdf
ICS
 
PDF
Designing and Managing IoT Devices for Rapid Deployment - Webinar.pdf
ICS
 
PDF
Quality and Test in Medical Device Design - Part 1.pdf
ICS
 
PDF
Creating Digital Twins Using Rapid Development Techniques.pdf
ICS
 
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Threat Modeling & Risk Assessment Webinar: A Step-by-Step Example
ICS
 
8 Mandatory Security Control Categories for Successful Submissions
ICS
 
Future-Proofing Embedded Device Capabilities with the Qt 6 Plugin Mechanism.pdf
ICS
 
Choosing an Embedded GUI: Comparative Analysis of UI Frameworks
ICS
 
Medical Device Cyber Testing to Meet FDA Requirements
ICS
 
Threat Modeling and Risk Assessment Webinar.pdf
ICS
 
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
ICS
 
Webinar On-Demand: Using Flutter for Embedded
ICS
 
A Deep Dive into Secure Product Development Frameworks.pdf
ICS
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
ICS
 
Practical Advice for FDA’s 510(k) Requirements.pdf
ICS
 
Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...
ICS
 
Overcoming CMake Configuration Issues Webinar
ICS
 
Enhancing Quality and Test in Medical Device Design - Part 2.pdf
ICS
 
Designing and Managing IoT Devices for Rapid Deployment - Webinar.pdf
ICS
 
Quality and Test in Medical Device Design - Part 1.pdf
ICS
 
Creating Digital Twins Using Rapid Development Techniques.pdf
ICS
 
Ad

Recently uploaded (20)

PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 

Best Practices in Qt Quick/QML - Part 1 of 4

  • 1. © Integrated Computer Solutions, Inc. All Rights Reserved Best Practices in Qt Quick/QML - Part 1 Justin Noel Senior Consulting Engineer ICS, Inc.
  • 2. © Integrated Computer Solutions, Inc. All Rights Reserved Agenda • Building Blocks of QML • Qt Properties • Declarative Code • Anchors
  • 3. © Integrated Computer Solutions, Inc. All Rights Reserved Building Blocks of QML
  • 4. © Integrated Computer Solutions, Inc. All Rights Reserved QObject • Heart and Soul of Qt Object • Signals and Slots are implemented here • QObjects can have “child objects” • Parents have some control over children • Deleting them, laying them out, etc • Also Qt Properties!
  • 5. © Integrated Computer Solutions, Inc. All Rights Reserved Introspection • QObjects can report at runtime • Class name, Super class • Lists of signals and list their arguments • Lists of functions and list their arguments • Invoke methods by name • QMetaObject::invokeMethod(objPtr, “function”…)
  • 6. © Integrated Computer Solutions, Inc. All Rights Reserved Meta Object Compiler • Introspection info is generated by moc • Reads header files. Writes source code • moc -o moc_class.cpp class.h • MetaObject is static • One instance per QObject subclass
  • 7. © Integrated Computer Solutions, Inc. All Rights Reserved QQuickItem • Most Qt Objects inherit QObject • QQuickItem is no exception • Gets many of it’s features directly from QObject • We will be leveraging these capabilities throughout class
  • 8. © Integrated Computer Solutions, Inc. All Rights Reserved Deferred Deletion • Qt is an event driven GUI toolkit • Deleting object can be tricky in an event based system • Deleting objects from within an event • Deleting the sender object from a signal and slot connection • QObject has a deleteLater() method
  • 9. © Integrated Computer Solutions, Inc. All Rights Reserved deleteLater() • Posts an event to the event loop • On the next lap of the loop • The object is deleted and all events cleared • destroy() in QML is QObject::deleteLater()
  • 10. © Integrated Computer Solutions, Inc. All Rights Reserved QVariant • Qt’s “Anything” class • Think: Typed void* • Supports most Qt data types out of the box • Easy to add support for your own types • Automatically supports all pointer types
  • 11. © Integrated Computer Solutions, Inc. All Rights Reserved QVariant and QML • QVariant maps to var in JavaScript • Used to pass data back and forth to C++ • If you register your types correctly you can attain runtime type safety
  • 12. © Integrated Computer Solutions, Inc. All Rights Reserved QVariant Containers • QVariantList maps to Array in JavaScript • QList<QVariantMap> can be used with JSON syntax JavaScript • Better off using QJson classes • If you are using JSON data • Easier to convert back to JSON
  • 13. © Integrated Computer Solutions, Inc. All Rights Reserved Qt Properties
  • 14. © Integrated Computer Solutions, Inc. All Rights Reserved Qt Properties • Combination of Get/Set/Notify • Allows introspection system to use these functions as one concept • Properties have been in Qt for a very long time • Qt Designer is based on properties • QML is also based on properties
  • 15. © Integrated Computer Solutions, Inc. All Rights Reserved Declaration of a Qt Property #include <QObject> class Car : public QObject { Q_OBJECT Q_PROPERTY(int value READ value WRITE setValue NOTIFY valueChanged) public: int getValue() const; void setValue(int newValue); signals: void valueChanged(int value); };
  • 16. © Integrated Computer Solutions, Inc. All Rights Reserved Qt Property with Enum #include <QObject> class Car : public QObject { Q_OBJECT Q_PROPERTY(KeyState keyState READ keyState NOTIFY keyStateChanged) public: enum KeyState { KeyOff, KeyOn, KeyStart } Q_ENUM(KeyState); [...] };
  • 17. © Integrated Computer Solutions, Inc. All Rights Reserved Qt Properties in C++ void someFunction(Qobject* obj) { // Getting QVariant propValue = obj->property(“value”); qDebug() << propValue.typeName() << propValue.toInt(); //Setting QVariant newValue = QVariant::fromValue(Car::KeyOn); obj->setProperty(“keyState”, newValue); }
  • 18. © Integrated Computer Solutions, Inc. All Rights Reserved Dynamic Propeties • Properties are Key-Value Pairs • QObject can create properties on demand • Less type safe, but perfectly useful for QML obj->setProperty(“newPropName”, 1); obj->setProperty(“another”, “Value”); int propInt = obj->property(“newPropName”).toInt(); QString propString = obj->property(“another”).toString();
  • 19. © Integrated Computer Solutions, Inc. All Rights Reserved Declarative Code
  • 20. © Integrated Computer Solutions, Inc. All Rights Reserved Basic QML Syntax • QML is declarative language • With hooks for procedural JavaScript • Use as little JavaScript as possible • QML files a read at runtime • The declarative parts create C++ instances • JavaScript is JIT interpreted
  • 21. © Integrated Computer Solutions, Inc. All Rights Reserved QtQuick Hello World import QtQuick 2.2 Rectangle{ id: toplevel color: “blue” Text { text: “Hello World” } MouseArea { anchors.fill: parent onClicked: Qt.quit() } }
  • 22. © Integrated Computer Solutions, Inc. All Rights Reserved Qt Quick Items • Rectangle, Text and MouseArea • Are implemented in C++ • Instances of QQuickRectangle, QQuickText, Etc • Loading QML is slower than compiled code • At runtime performance is great
  • 23. © Integrated Computer Solutions, Inc. All Rights Reserved QML Bindings • “:” is the binding operator • Right of the binding operator is JavaScript • Text { text: “Hello World ” + Math.rand() }
  • 24. © Integrated Computer Solutions, Inc. All Rights Reserved Bindings are Declarative • When any property used in a binding changes the expression is recalculated Gauge { value: Math.min(gaugeMax, Math.max(gaugeMin, oilPressure.value)) } • Value is updated whenever properties change • gaugeMax, gaugeMin or oilPressure.value
  • 25. © Integrated Computer Solutions, Inc. All Rights Reserved JavaScript is Procedural • Avoid this! Gauge { Component.onCompleted: { setGaugeValue(oilPressure.value) oilPressure.valueChanged.connect(setGaugeValue) } onGaugeMinChanged: setGaugeValue(value) onGaugeMaxChanged: setGaugeValue(value) function setGaugeValue(oilValue) { value = Math.min(gaugeMax, Math.max(gaugeMin, oilValue)) } }
  • 26. © Integrated Computer Solutions, Inc. All Rights Reserved Broken Bindings • Assignment operator breaks bindings • Binding works for awhile. Then doesn’t. • Solution: Use states or Qt.binding(function(){…}) • More in later in the webinar series Gauge { id: gauge visible: Dashboard.isOilPressureVisible } Button { onClicked: { // Tries to temporarily hide gauge if(gauge.visible) gauge.visible = false else gauge.visible = Dashboard.isOilPressureVisible } }
  • 27. © Integrated Computer Solutions, Inc. All Rights Reserved Anchors
  • 28. © Integrated Computer Solutions, Inc. All Rights Reserved Dead Reckoning Layout Item { width: 800; height: 400; Rectangle { id:rectA color: 'red‘ height: 50 ; width: 70 x: 0; y: 0 } Rectangle { id:rectB color: 'blue‘ height: rectA.height * 2; width: rectA.width * 2 x: 0; y: 100 } }
  • 29. © Integrated Computer Solutions, Inc. All Rights Reserved Why is dead reckoning bad? • The good: • It resizes correctly • It uses bindings so it’s “declarative” • The bad: • There are a lot of binding re-calculations • Each recalculation is run in JavaScript • Cascading bindings cause intermediate states
  • 30. © Integrated Computer Solutions, Inc. All Rights Reserved Binding Recalculation • This example has ~40 items • If each item needs 2 bindings • 80 Recalculations on resize • Not including intermediate states
  • 31. © Integrated Computer Solutions, Inc. All Rights Reserved Intermediate States Example 2.2. src/anchors/tst_bindings_1.qml Item { property int c: a + b property int a property int b: a onAChanged: console.log("a == " + a) onBChanged: console.log("b == " + b) onCChanged: console.log("c == " + c) Component.onCompleted: a = 1 } Output: a == 1 c == 1 b == 1 c == 2
  • 32. © Integrated Computer Solutions, Inc. All Rights Reserved Anchors Are Better! • Anchors are stored and calculated in C++ • Remember all Items are actually C++ instances • Anchors let you attach an item to other items • Parent item • Any sibling item • Anyone remember the Motif Form Widget? • Eerily similar. What’s old is new again!
  • 33. © Integrated Computer Solutions, Inc. All Rights Reserved Anchor Lines • There are 6 anchors lines all Items have • Text item has a 7th anchor called baseline • Bottom of text without descenders
  • 34. © Integrated Computer Solutions, Inc. All Rights Reserved Setting Anchors Rectangle { width: 800; height:600 Rectangle { id: rect1 width: 400 anchors.top: parent.top anchors.bottom: parent.bottom } Rectangle { id: rect2 anchors { top: parent.top; bottom: parent.bottom left: rect1.right; right: parent.right } } }
  • 35. © Integrated Computer Solutions, Inc. All Rights Reserved Anchor Margins • Each item has 6 adjustable margins • Not shown are [horizontal|vertical]CenterOffset • Text has a baselineOffset margin • anchors.margins sets all outer margins at once
  • 36. © Integrated Computer Solutions, Inc. All Rights Reserved Complex Anchors • Set multiple anchors at once • anchors.fill: anotherItem • Sets left, right, top and bottom • Can use all outer margins • anchors.centerIn: anotherItem • Sets horizontalCenter and verticalCenter • Can use horizontal and vertical offsets
  • 37. © Integrated Computer Solutions, Inc. All Rights Reserved Best Practices in Qt Quick/QML - Part 2 June 22, 1 pm EDT https://www.ics.com/webinar/best-practices-qt-quickqml-part-2
  • 38. © Integrated Computer Solutions, Inc. All Rights Reserved Thank You! Justin Noel Senior Consulting Engineer ICS, Inc.