SlideShare a Scribd company logo
Qt Quick Best Practices
Part I
Justin Noel
Senior Consulting Engineer
ICS, Inc.
Agenda
• Building Blocks of QML
• Qt Properties
• Declarative Code
• Anchors
Building Blocks of QML
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!
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”…)
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
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
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
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()
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
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
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
Qt Properties
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
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);
};
Qt Property with Enum
#include <QObject>
class Car : public QObject
{
Q_OBJECT
Q_ENUMS(KeyState)
Q_PROPERTY(KeyState keyState READ keyState NOTIFY keyStateChanged)
public:
enum KeyState {
KeyOff,
KeyOn,
KeyStart
};
[...]
};
Getting and Setting Qt Properties
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);
}
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();
Declarative Code
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
QtQuick Hello World
import QtQuick 2.2
Rectangle{
id: toplevel
color: “blue”
Text {
text: “Hello World”
}
MouseArea {
anchors.fill: parent
onClicked: Qt.quit()
}
}
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
QML Bindings
• “:” is the binding operator
• Right of the binding operator is JavaScript
• Text {
text: “Hello World ” + Math.rand()
}
• If the expression is simple
• The full JavaScript interpreter may be skipped
• More on this later in the webinar series
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
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))
}
}
Broken Bindings
• Assignment operator breaks bindings
• Binding works for awhile. Then doesn’t.
• Solution: Use States
• 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
}
}
Anchors
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
}
}
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
Binding Recalculation
• This example has ~40 items
• If each item needs 2 bindings
• 80 Recalculations on resize
• Not including intermediate states
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
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!
Anchor Lines
• There are 6 anchors lines all Items have
• Text item has a 7th anchor called baseline
• Bottom of text without descenders
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
}
}
}
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
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
Upcoming Webinars
• Qt Quick Best Practices
• Part 2 July 9th 1:00 PM EST
• Creating New Items
• States and Transitions
• Part 3 July 23 1:00 PM EST
• C++ Integration
• Creating QML Modules
• Part 4 August 6th 1:00 PM EST
• Dynamic Item Creation
• Keyboard Input Handling
• Performance Tips
Register Now: ics.com/webinars
Thank You!
Justin Noel
Senior Consulting Engineer
ICS, Inc.

More Related Content

PDF
Best Practices in Qt Quick/QML - Part III
 
PDF
Best Practices in Qt Quick/QML - Part II
 
PDF
Best Practices in Qt Quick/QML - Part 1 of 4
 
PDF
Best Practices in Qt Quick/QML - Part IV
 
PDF
In-Depth Model/View with QML
 
PDF
Best Practices in Qt Quick/QML - Part 3
 
PDF
Qt for Beginners Part 3 - QML and Qt Quick
 
PPTX
Qt Framework Events Signals Threads
Best Practices in Qt Quick/QML - Part III
 
Best Practices in Qt Quick/QML - Part II
 
Best Practices in Qt Quick/QML - Part 1 of 4
 
Best Practices in Qt Quick/QML - Part IV
 
In-Depth Model/View with QML
 
Best Practices in Qt Quick/QML - Part 3
 
Qt for Beginners Part 3 - QML and Qt Quick
 
Qt Framework Events Signals Threads

What's hot (20)

PDF
Lessons Learned from Building 100+ C++/Qt/QML Devices
 
PDF
QThreads: Are You Using Them Wrong?
 
PDF
Qt Internationalization
 
PPTX
UI Programming with Qt-Quick and QML
ODP
Qt Workshop
PDF
Qt Application Programming with C++ - Part 2
PDF
Qt multi threads
PDF
Introduction to QML
PDF
Basics of Model/View Qt programming
 
PDF
Qt and QML performance tips & tricks for Qt 4.7
PDF
Qt Application Programming with C++ - Part 1
PPTX
Hello, QML
PDF
Best Practices in Qt Quick/QML - Part 4
 
ODP
Qt 5 - C++ and Widgets
PDF
PDF
02 - Basics of Qt
PPTX
Qt test framework
 
PPTX
Qt for beginners part 1 overview and key concepts
 
ODP
Unit testing with Qt test
PDF
JavaScript - Chapter 4 - Types and Statements
Lessons Learned from Building 100+ C++/Qt/QML Devices
 
QThreads: Are You Using Them Wrong?
 
Qt Internationalization
 
UI Programming with Qt-Quick and QML
Qt Workshop
Qt Application Programming with C++ - Part 2
Qt multi threads
Introduction to QML
Basics of Model/View Qt programming
 
Qt and QML performance tips & tricks for Qt 4.7
Qt Application Programming with C++ - Part 1
Hello, QML
Best Practices in Qt Quick/QML - Part 4
 
Qt 5 - C++ and Widgets
02 - Basics of Qt
Qt test framework
 
Qt for beginners part 1 overview and key concepts
 
Unit testing with Qt test
JavaScript - Chapter 4 - Types and Statements
Ad

Viewers also liked (17)

PDF
Qt for beginners part 2 widgets
 
PDF
[Webinar] 10 Keys to Ensuring Success for Your Next Qt Project
 
PDF
Qt for beginners part 4 doing more
 
PPTX
Qt for beginners part 5 ask the experts
 
ODP
Intro to QML / Declarative UI
PPTX
Practical QML - Key Navigation, Dynamic Language and Theme Change
PPSX
Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...
PDF
Qt Design Patterns
PDF
[Webinar] QtSerialBus: Using Modbus and CAN bus with Qt
 
PPTX
Introduction to Qt
PDF
Optimizing Performance in Qt-Based Applications
PDF
Airports can maximize capacity with minimal capital investment through effect...
PPTX
Qt Memory Management & Signal and Slots
PDF
Serving QML applications over the network
PDF
GMock framework
PPTX
Test driving QML
PDF
QML + Node.js
Qt for beginners part 2 widgets
 
[Webinar] 10 Keys to Ensuring Success for Your Next Qt Project
 
Qt for beginners part 4 doing more
 
Qt for beginners part 5 ask the experts
 
Intro to QML / Declarative UI
Practical QML - Key Navigation, Dynamic Language and Theme Change
Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...
Qt Design Patterns
[Webinar] QtSerialBus: Using Modbus and CAN bus with Qt
 
Introduction to Qt
Optimizing Performance in Qt-Based Applications
Airports can maximize capacity with minimal capital investment through effect...
Qt Memory Management & Signal and Slots
Serving QML applications over the network
GMock framework
Test driving QML
QML + Node.js
Ad

Similar to Best Practices in Qt Quick/QML - Part I (20)

PDF
Scripting Your Qt Application
PDF
Raffaele Rialdi
ZIP
Cappuccino - A Javascript Application Framework
PDF
Petri Niemi Qt Web Kit
PDF
Petri Niemi Qt Advanced Part 1
PDF
QVariant, QObject — Qt's not just for GUI development
 
PDF
04 - Qt Data
PDF
The Ring programming language version 1.9 book - Part 111 of 210
PDF
Aplicações assíncronas no Android com
Coroutines & Jetpack
PDF
Aplicações Assíncronas no Android com Coroutines e Jetpack
PPTX
Graal in GraalVM - A New JIT Compiler
PDF
06 - Qt Communication
PDF
The Ring programming language version 1.10 book - Part 104 of 212
PDF
Run-time of Node.js : V8 JavaScript Engine
PDF
Tips and tricks for building high performance android apps using native code
PDF
Angular Weekend
PDF
The Ring programming language version 1.7 book - Part 88 of 196
PDF
Open stack and k8s(v4)
PDF
The Ring programming language version 1.5.3 book - Part 92 of 184
PDF
Qt everywhere a c++ abstraction platform
Scripting Your Qt Application
Raffaele Rialdi
Cappuccino - A Javascript Application Framework
Petri Niemi Qt Web Kit
Petri Niemi Qt Advanced Part 1
QVariant, QObject — Qt's not just for GUI development
 
04 - Qt Data
The Ring programming language version 1.9 book - Part 111 of 210
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações Assíncronas no Android com Coroutines e Jetpack
Graal in GraalVM - A New JIT Compiler
06 - Qt Communication
The Ring programming language version 1.10 book - Part 104 of 212
Run-time of Node.js : V8 JavaScript Engine
Tips and tricks for building high performance android apps using native code
Angular Weekend
The Ring programming language version 1.7 book - Part 88 of 196
Open stack and k8s(v4)
The Ring programming language version 1.5.3 book - Part 92 of 184
Qt everywhere a c++ abstraction platform

More from ICS (20)

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

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
1. Introduction to Computer Programming.pptx
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPT
Teaching material agriculture food technology
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Machine learning based COVID-19 study performance prediction
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Spectroscopy.pptx food analysis technology
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
cuic standard and advanced reporting.pdf
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
Tartificialntelligence_presentation.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
1. Introduction to Computer Programming.pptx
NewMind AI Weekly Chronicles - August'25-Week II
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Teaching material agriculture food technology
Dropbox Q2 2025 Financial Results & Investor Presentation
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
The Rise and Fall of 3GPP – Time for a Sabbatical?
MIND Revenue Release Quarter 2 2025 Press Release
Group 1 Presentation -Planning and Decision Making .pptx
SOPHOS-XG Firewall Administrator PPT.pptx
Machine learning based COVID-19 study performance prediction
MYSQL Presentation for SQL database connectivity
Spectroscopy.pptx food analysis technology
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
cuic standard and advanced reporting.pdf
Assigned Numbers - 2025 - Bluetooth® Document
Tartificialntelligence_presentation.pptx

Best Practices in Qt Quick/QML - Part I

  • 1. Qt Quick Best Practices Part I Justin Noel Senior Consulting Engineer ICS, Inc.
  • 2. Agenda • Building Blocks of QML • Qt Properties • Declarative Code • Anchors
  • 4. 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. 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. 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. 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. 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. 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. 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. 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. 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
  • 14. 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. 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. Qt Property with Enum #include <QObject> class Car : public QObject { Q_OBJECT Q_ENUMS(KeyState) Q_PROPERTY(KeyState keyState READ keyState NOTIFY keyStateChanged) public: enum KeyState { KeyOff, KeyOn, KeyStart }; [...] };
  • 17. Getting and Setting Qt Properties 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. 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();
  • 20. 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. QtQuick Hello World import QtQuick 2.2 Rectangle{ id: toplevel color: “blue” Text { text: “Hello World” } MouseArea { anchors.fill: parent onClicked: Qt.quit() } }
  • 22. 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. QML Bindings • “:” is the binding operator • Right of the binding operator is JavaScript • Text { text: “Hello World ” + Math.rand() } • If the expression is simple • The full JavaScript interpreter may be skipped • More on this later in the webinar series
  • 24. 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. 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. Broken Bindings • Assignment operator breaks bindings • Binding works for awhile. Then doesn’t. • Solution: Use States • 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 } }
  • 28. 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. 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. Binding Recalculation • This example has ~40 items • If each item needs 2 bindings • 80 Recalculations on resize • Not including intermediate states
  • 31. 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. 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. Anchor Lines • There are 6 anchors lines all Items have • Text item has a 7th anchor called baseline • Bottom of text without descenders
  • 34. 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. 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. 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. Upcoming Webinars • Qt Quick Best Practices • Part 2 July 9th 1:00 PM EST • Creating New Items • States and Transitions • Part 3 July 23 1:00 PM EST • C++ Integration • Creating QML Modules • Part 4 August 6th 1:00 PM EST • Dynamic Item Creation • Keyboard Input Handling • Performance Tips Register Now: ics.com/webinars
  • 38. Thank You! Justin Noel Senior Consulting Engineer ICS, Inc.