SlideShare a Scribd company logo
1 of 38
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

What's hot

What's hot (20)

Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programming
 
Qt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt QuickQt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt Quick
 
Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QML
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
Lessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML DevicesLessons Learned from Building 100+ C++/Qt/QML Devices
Lessons Learned from Building 100+ C++/Qt/QML Devices
 
Introduction to the Qt State Machine Framework using Qt 6
Introduction to the Qt State Machine Framework using Qt 6Introduction to the Qt State Machine Framework using Qt 6
Introduction to the Qt State Machine Framework using Qt 6
 
Qt Application Programming with C++ - Part 1
Qt Application Programming with C++ - Part 1Qt Application Programming with C++ - Part 1
Qt Application Programming with C++ - Part 1
 
Qt Qml
Qt QmlQt Qml
Qt Qml
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong? QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong?
 
Qt 5 - C++ and Widgets
Qt 5 - C++ and WidgetsQt 5 - C++ and Widgets
Qt 5 - C++ and Widgets
 
Introduction to Qt
Introduction to QtIntroduction to Qt
Introduction to Qt
 
Introduction to Qt programming
Introduction to Qt programmingIntroduction to Qt programming
Introduction to Qt programming
 
Introduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene GraphIntroduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene Graph
 
Qt for beginners
Qt for beginnersQt for beginners
Qt for beginners
 
Hello, QML
Hello, QMLHello, QML
Hello, QML
 
Qt programming-using-cpp
Qt programming-using-cppQt programming-using-cpp
Qt programming-using-cpp
 
Qt and QML performance tips & tricks for Qt 4.7
Qt and QML performance tips & tricks for Qt 4.7Qt and QML performance tips & tricks for Qt 4.7
Qt and QML performance tips & tricks for Qt 4.7
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design Patterns
 

Viewers also liked

Qt Memory Management & Signal and Slots
Qt Memory Management & Signal and SlotsQt Memory Management & Signal and Slots
Qt Memory Management & Signal and Slots
Jussi Pohjolainen
 

Viewers also liked (16)

Qt for beginners part 2 widgets
Qt for beginners part 2   widgetsQt for beginners part 2   widgets
Qt for beginners part 2 widgets
 
[Webinar] 10 Keys to Ensuring Success for Your Next Qt Project
[Webinar] 10 Keys to Ensuring Success for Your Next Qt Project[Webinar] 10 Keys to Ensuring Success for Your Next Qt Project
[Webinar] 10 Keys to Ensuring Success for Your Next Qt Project
 
Qt for beginners part 4 doing more
Qt for beginners part 4   doing moreQt for beginners part 4   doing more
Qt for beginners part 4 doing more
 
Qt for beginners part 5 ask the experts
Qt for beginners part 5   ask the expertsQt for beginners part 5   ask the experts
Qt for beginners part 5 ask the experts
 
Qt for beginners part 1 overview and key concepts
Qt for beginners part 1   overview and key conceptsQt for beginners part 1   overview and key concepts
Qt for beginners part 1 overview and key concepts
 
Intro to QML / Declarative UI
Intro to QML / Declarative UIIntro to QML / Declarative UI
Intro to QML / Declarative UI
 
Practical QML - Key Navigation, Dynamic Language and Theme Change
Practical QML - Key Navigation, Dynamic Language and Theme ChangePractical QML - Key Navigation, Dynamic Language and Theme Change
Practical QML - Key Navigation, Dynamic Language and Theme Change
 
Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...
Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...
Build Cutting edge Mobile Apps using QML and JavaScript for MeeGo N9: Linux F...
 
[Webinar] QtSerialBus: Using Modbus and CAN bus with Qt
[Webinar] QtSerialBus: Using Modbus and CAN bus with Qt[Webinar] QtSerialBus: Using Modbus and CAN bus with Qt
[Webinar] QtSerialBus: Using Modbus and CAN bus with Qt
 
Optimizing Performance in Qt-Based Applications
Optimizing Performance in Qt-Based ApplicationsOptimizing Performance in Qt-Based Applications
Optimizing Performance in Qt-Based Applications
 
Airports can maximize capacity with minimal capital investment through effect...
Airports can maximize capacity with minimal capital investment through effect...Airports can maximize capacity with minimal capital investment through effect...
Airports can maximize capacity with minimal capital investment through effect...
 
Qt Memory Management & Signal and Slots
Qt Memory Management & Signal and SlotsQt Memory Management & Signal and Slots
Qt Memory Management & Signal and Slots
 
Serving QML applications over the network
Serving QML applications over the networkServing QML applications over the network
Serving QML applications over the network
 
GMock framework
GMock frameworkGMock framework
GMock framework
 
Test driving QML
Test driving QMLTest driving QML
Test driving QML
 
QML + Node.js
QML + Node.jsQML + Node.js
QML + Node.js
 

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

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

Scripting Your Qt Application
Scripting Your Qt ApplicationScripting Your Qt Application
Scripting Your Qt Application
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
 
Cappuccino - A Javascript Application Framework
Cappuccino - A Javascript Application FrameworkCappuccino - A Javascript Application Framework
Cappuccino - A Javascript Application Framework
 
Petri Niemi Qt Web Kit
Petri Niemi Qt Web KitPetri Niemi Qt Web Kit
Petri Niemi Qt Web Kit
 
Petri Niemi Qt Advanced Part 1
Petri Niemi Qt Advanced Part 1Petri Niemi Qt Advanced Part 1
Petri Niemi Qt Advanced Part 1
 
Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2
 
QVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentQVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI development
 
04 - Qt Data
04 - Qt Data04 - Qt Data
04 - Qt Data
 
The Ring programming language version 1.9 book - Part 111 of 210
The Ring programming language version 1.9 book - Part 111 of 210The Ring programming language version 1.9 book - Part 111 of 210
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 & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
 
Aplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e JetpackAplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e Jetpack
 
Graal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT CompilerGraal in GraalVM - A New JIT Compiler
Graal in GraalVM - A New JIT Compiler
 
06 - Qt Communication
06 - Qt Communication06 - Qt Communication
06 - Qt Communication
 
The Ring programming language version 1.10 book - Part 104 of 212
The Ring programming language version 1.10 book - Part 104 of 212The Ring programming language version 1.10 book - Part 104 of 212
The Ring programming language version 1.10 book - Part 104 of 212
 
Run-time of Node.js : V8 JavaScript Engine
Run-time of Node.js: V8 JavaScript EngineRun-time of Node.js: V8 JavaScript Engine
Run-time of Node.js : V8 JavaScript Engine
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native code
 
Angular Weekend
Angular WeekendAngular Weekend
Angular Weekend
 
The Ring programming language version 1.7 book - Part 88 of 196
The Ring programming language version 1.7 book - Part 88 of 196The Ring programming language version 1.7 book - Part 88 of 196
The Ring programming language version 1.7 book - Part 88 of 196
 
Open stack and k8s(v4)
Open stack and k8s(v4)Open stack and k8s(v4)
Open stack and k8s(v4)
 
The Ring programming language version 1.5.3 book - Part 92 of 184
The Ring programming language version 1.5.3 book - Part 92 of 184The Ring programming language version 1.5.3 book - Part 92 of 184
The Ring programming language version 1.5.3 book - Part 92 of 184
 

More from ICS

Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
ICS
 

More from ICS (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Practical Advice for FDA’s 510(k) Requirements.pdf
Practical Advice for FDA’s 510(k) Requirements.pdfPractical Advice for FDA’s 510(k) Requirements.pdf
Practical Advice for FDA’s 510(k) Requirements.pdf
 
Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...
Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...
Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...
 
Overcoming CMake Configuration Issues Webinar
Overcoming CMake Configuration Issues WebinarOvercoming CMake Configuration Issues Webinar
Overcoming CMake Configuration Issues Webinar
 
Enhancing Quality and Test in Medical Device Design - Part 2.pdf
Enhancing Quality and Test in Medical Device Design - Part 2.pdfEnhancing Quality and Test in Medical Device Design - Part 2.pdf
Enhancing Quality and Test in Medical Device Design - Part 2.pdf
 
Designing and Managing IoT Devices for Rapid Deployment - Webinar.pdf
Designing and Managing IoT Devices for Rapid Deployment - Webinar.pdfDesigning and Managing IoT Devices for Rapid Deployment - Webinar.pdf
Designing and Managing IoT Devices for Rapid Deployment - Webinar.pdf
 
Quality and Test in Medical Device Design - Part 1.pdf
Quality and Test in Medical Device Design - Part 1.pdfQuality and Test in Medical Device Design - Part 1.pdf
Quality and Test in Medical Device Design - Part 1.pdf
 
Creating Digital Twins Using Rapid Development Techniques.pdf
Creating Digital Twins Using Rapid Development Techniques.pdfCreating Digital Twins Using Rapid Development Techniques.pdf
Creating Digital Twins Using Rapid Development Techniques.pdf
 
Secure Your Medical Devices From the Ground Up
Secure Your Medical Devices From the Ground Up Secure Your Medical Devices From the Ground Up
Secure Your Medical Devices From the Ground Up
 
Cybersecurity and Software Updates in Medical Devices.pdf
Cybersecurity and Software Updates in Medical Devices.pdfCybersecurity and Software Updates in Medical Devices.pdf
Cybersecurity and Software Updates in Medical Devices.pdf
 
MDG Panel - Creating Expert Level GUIs for Complex Medical Devices
MDG Panel - Creating Expert Level GUIs for Complex Medical DevicesMDG Panel - Creating Expert Level GUIs for Complex Medical Devices
MDG Panel - Creating Expert Level GUIs for Complex Medical Devices
 
How to Craft a Winning IOT Device Management Solution
How to Craft a Winning IOT Device Management SolutionHow to Craft a Winning IOT Device Management Solution
How to Craft a Winning IOT Device Management Solution
 
Bridging the Gap Between Development and Regulatory Teams
Bridging the Gap Between Development and Regulatory TeamsBridging the Gap Between Development and Regulatory Teams
Bridging the Gap Between Development and Regulatory Teams
 
IoT Device Fleet Management: Create a Robust Solution with Azure
IoT Device Fleet Management: Create a Robust Solution with AzureIoT Device Fleet Management: Create a Robust Solution with Azure
IoT Device Fleet Management: Create a Robust Solution with Azure
 
Basic Cmake for Qt Users
Basic Cmake for Qt UsersBasic Cmake for Qt Users
Basic Cmake for Qt Users
 
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
Software Update Mechanisms: Selecting the Best Solutin for Your Embedded Linu...
 
Qt Installer Framework
Qt Installer FrameworkQt Installer Framework
Qt Installer Framework
 
Bridging the Gap Between Development and Regulatory Teams
Bridging the Gap Between Development and Regulatory TeamsBridging the Gap Between Development and Regulatory Teams
Bridging the Gap Between Development and Regulatory Teams
 
Overcome Hardware And Software Challenges - Medical Device Case Study
Overcome Hardware And Software Challenges - Medical Device Case StudyOvercome Hardware And Software Challenges - Medical Device Case Study
Overcome Hardware And Software Challenges - Medical Device Case Study
 
User Experience Design for IoT
User Experience Design for IoTUser Experience Design for IoT
User Experience Design for IoT
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

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.