SlideShare a Scribd company logo
Integrated Computer Solutions Inc. www.ics.com
Qt Model / View with QML
July 25th Webinar With Chris Probst & Ryan Hampton
Visit us at http://www.ics.com
Produced by Integrated Computer Solutions
Material based on Qt 5.12
1
Integrated Computer Solutions Inc. www.ics.com
What is MVC?
- Stands for Model/View/Controller
- Architectural Design Pattern used for developing user interfaces
- Separates data interactions into three separate parts
- Allows for User Interface being independently developed from business logic.
In general terms:
- Model manages the data of the user interface
- View displays the model
- The controller responds to the user input and manages the model accordingly
2
Integrated Computer Solutions Inc. www.ics.com
Simple QML Example
- In Qt/QML, the controller is combined with the view
- A simple approach of leveraging Model/View in Qt/QML would be
- For every value displayed, create a Q_PROPERTY
- Provide a read, write and notify signal
- Export the properties to QML, using void QQmlContext::setContextProperty
3
class simpleModel : public QObject
{
Q_OBJECT
Q_PROPERTY(int speed READ speed WRITE setSpeed NOTIFY speedChanged)
Q_PROPERTY(int temperature READ temperature WRITE setTemperature NOTIFY temperatureChanged)
QQmlApplicationEngine engine;
simpleModel aSimpleModel;
engine.rootContext()->setContextProperty("asimplemodel",&asimpleModel);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
Integrated Computer Solutions Inc. www.ics.com
Model View Delegate
- Preserves Business-Logic/View separation
- Model provides data to the view
- View is the visual container displaying the data
- Delegates renders each of the instances of the
data
- Available for both Widgets and QML
4
Integrated Computer Solutions Inc. www.ics.com
Other Simple Approaches
- Creating the Model in QML
- Standard QML models
- ListModel - simple hierarchy of QML types
- ObjectModel - Visual items, no delegate needed
- XmlListModel - XML data source
- Integer - read only, the model has no data roles
- Object instances - properties of the object are the roles
- JavaScript array - read only, no need for dynamic model updates
5
ListModel {
id: fruitModel
ListElement {
name: "Apple"
cost: 2.45 }
ListElement {
name: "Orange"
cost: 3.25 }
… }
Integrated Computer Solutions Inc. www.ics.com
Example: Contact List
● Create a ListModel
○ Fill it with ListElement objects, each with:
■ A name property
■ A file property referring to an image
● Add a ListView and a Component
to use as a delegate
● Add header, footer and highlight
properties to the view
6
Integrated Computer Solutions Inc. www.ics.com
Examples of QML Views - ListView
7
- Based on a Flickable area
- It uses a model, instantiates a delegate and
between the delegates, there can be spacing
- Most commonly used
- Can be horizontal or vertical
ListView {
model: mymodel
delegate: numberDelegate
spacing: 5
}
}
Integrated Computer Solutions Inc. www.ics.com
Examples of QML Views - GridView
8
- Based on a Flickable area
- It uses a model, instantiates a delegate and
between the delegates, there can be spacing
- Places the data into a two-dimensional grid,
left-to-right or top-to-bottom
See $QTDIRExamplesQt-5.11.2quickviews
Integrated Computer Solutions Inc. www.ics.com
Examples of QML Views - PathView
9
- Lays out the data along an arbitrary path
- Most powerful, but also the most complex
- Requires the path property to be set
- Paths are specified using the Path QML
object
See $QTDIRExamplesQt-5.11.2quickviews
Integrated Computer Solutions Inc. www.ics.com
What about the Delegate?
10
- Appearance of each individual item
- Can be a Component or a QML file
See $QTDIRExamplesQt-5.11.2quickviews
Column {
spacing: 2
Repeater {
model: 10
delegate: BlueBox {
width: 100
height: 32
text: index
}
}
}
Integrated Computer Solutions Inc. www.ics.com
A Model in C++ : A Simple Approach
11
QStringList dataList;
dataList.append("Item 1");
dataList.append("Item 2");
dataList.append("Item 3");
dataList.append("Item 4");
QQmlApplicationEngine engine;
engine.rootContext()
QQmlContext *ctxt = view.rootContext();
ctxt->setContextProperty("myModel",
QVariant::fromValue(dataList));
ListView {
width: 100; height: 100
model: myModel
delegate: Rectangle {
height: 25
width: 100
Text { text: modelData }
}
}
● Model can be specified QStringList, QVariantList, QObjectList
Integrated Computer Solutions Inc. www.ics.com
QAbstractListModel - What to reimplement?
12
● provide implementations of the QAbstractListModel::rowCount() and
QAbstractListModel::data() functions.
QVariant Mp3ListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
Mp3Item *mp3Item = m_mp3Items.at(index.row());
switch (role) {
case DoneRole:
return QVariant(mp3Item->download.finished());
case UrlRole:
return QVariant(mp3Item->download.url().toString());
case ProgressRole:
return QVariant(mp3Item->download.progress());
case ErrorRole:
return QVariant(mp3Item->download.error());
return QVariant();
}
int Mp3ListModel::rowCount(const QModelIndex &parent)
const
{
if (parent.isValid())
return 0;
return m_mp3Items.size();
}
Integrated Computer Solutions Inc. www.ics.com
QAbstractListModel - If user can change data?
13
● Provide implementations of the QAbstractListModel::setData() functions.
bool Mp3ListModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (role == SelectedRole) {
if (index.row() < 0 || index.row() >= m_mp3Items.size())
return false;
if (m_mp3Items.at(index.row())->selected == value.toBool())
return false;
m_mp3Items.at(index.row())->selected = value.toBool();
dataChanged(index, index);
return true;
}
return false;
}
Integrated Computer Solutions Inc. www.ics.com
QAbstractListModel - A Note on Roles
14
● Along with the QModelIndex, a role is simply an additional selector to
access data in your model.
class Mp3ListModel : public QAbstractListModel
{
Q_OBJECT
public:
explicit Mp3ListModel(QObject *parent = nullptr)
noexcept;
enum {
SelectedRole = Qt::UserRole,
DoneRole,
UrlRole,
... };
QHash<int, QByteArray>
Mp3ListModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[SelectedRole] = "selected";
roles[DoneRole] = "done";
roles[ProgressRole] = "progress";
roles[UrlRole] = "url";
roles[ErrorRole] = "error";
return roles;
}
ListView {
….
delegate: RowLayout {
spacing: 10
CheckBox {
checked: model.selected
onClicked: model.selected = checked
}
Label {
Layout.fillWidth: true
text: model.error ? qsTr("Error on
Download") : model.url
elide: Text.ElideLeft
...
}
Integrated Computer Solutions Inc. www.ics.com
QAbstractListModel - Notifying the View of
Changes
15
● Emit the signal:
void QAbstractItemModel::dataChanged(const QModelIndex&topLeft,
const QModelIndex &bottomRight, const QVector<int> &roles = ...)
m_mp3Items.at(index.row())->selected = value.toBool();
emit dataChanged(index, index);
Integrated Computer Solutions Inc. www.ics.com
Hooking the Model up to the View
16
#include <mp3listmodel>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling);
QQmlApplicationEngine engine;
Mp3ListModel mp3ListModel(downloadDirUrl);
engine.rootContext()->setContextProperty("mp3ListModel"), &mp3ListModel);
qmlRegisterUncreatableType<Mp3ListModel>("DownloadManager", 1, 0,
"Mp3ListModel", "Mp3ListModel should not be created in QML");
engine.load("qrc:/main.qml"); // Load blocks
return app.exec();
}
ListView {
anchors.fill: parent
model: mp3ListModel
delegate: Mp3Item {
width: parent.width
}
}
Integrated Computer Solutions Inc. www.ics.com
Example: Download Manager
17
Integrated Computer Solutions Inc. www.ics.com
Summary: Model / View
Qt Model / View in a nutshell
● A model provides data for a view
● A view displays the data from the model
● Similar to the Model / View / Controller design pattern
○ But combine the controller with the view
Why Model / View?
● Isolate business logic from UI logic
● Create UI components that are independent
○ Easier Development
○ Easier Testing
○ Easier Maintenance
● More Reuse
○ Reuse your UI logic across multiple views
○ Models can be reused for different views
18
Integrated Computer Solutions Inc. www.ics.com
Summary: Model / View Components
Model:
● Interface to business logic data
● Emits signals when data changes or is appended
● Many common model types are provided by Qt
● C++: QStringList, QVariantList, QAbstractItemModel subclass
● QML: an integer, JavaScript array, ListModel, XmlListModel
View:
● Displays the data structure
● Handles the user interaction with the data
● Qt provides many view types with model support
● QML: ListView, GridView, PathView, TableView (new)
Delegate:
● Items in a view are rendered and edited by delegates
● The view expects a Component for its delegate property
● Model items are accessible through the index property
19
Integrated Computer Solutions Inc. www.ics.com
Summary: QML Views
20
ListView GridView TableViewPathView
Integrated Computer Solutions Inc. www.ics.com
Summary: Model Types
21
● Standard QML models
○ ListModel - simple hierarchy of QML types
○ ObjectModel - Visual items, no delegate needed
○ XmlListModel - XML data source
○ Integer - read only, the model has no data roles
○ Object instances - properties of the object are the roles
○ JavaScript array - read only, no need for dynamic model updates
● C++ models (must be implemented in C++ before use)
○ More complex but more fine-tuned control over data access
○ QStringList, QVariantList, QObjectList, QAbstractItemModel (and subclasses)
○ Subclass QAbstractItemModel for complex data-sets
Integrated Computer Solutions Inc. www.ics.com
References
● Qt 5 E-book
● See https://qmlbook.github.io/ch07-modelview/modelview.html
● C++ GUI Programming with Qt 4 (see Model/View chapter)
● Examples: https://gitlab.com/RyanHampton/qml-model-view-framework
Don’t know where to start? Go read the docs!
● Hint - start here: https://doc.qt.io/qt-5/qabstractlistmodel.html
22
Integrated Computer Solutions Inc. www.ics.comIntegrated Computer Solutions Inc.
Thank You!
● https://www.ics.com/blog/exploring-model-view-design-qt-quick
● ICS provides QML training for more in-depth learning
23
Model / View with QML Webinar: The End

More Related Content

What's hot

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
Burkhard Stubert
 
Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4
ICS
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design Patterns
Ynon Perek
 
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
ICS
 
UI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QMLUI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QML
Emertxe Information Technologies Pvt Ltd
 
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
ICS
 
Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QML
Alan Uthoff
 
QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong? QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong?
ICS
 
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
ICS
 
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
Emertxe Information Technologies Pvt Ltd
 
[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
ICS
 
Qt Internationalization
Qt InternationalizationQt Internationalization
Qt Internationalization
ICS
 
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
Emertxe Information Technologies Pvt Ltd
 
02 - Basics of Qt
02 - Basics of Qt02 - Basics of Qt
02 - Basics of Qt
Andreas Jakl
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
Ynon Perek
 
Qt 5 - C++ and Widgets
Qt 5 - C++ and WidgetsQt 5 - C++ and Widgets
Qt 5 - C++ and Widgets
Juha Peltomäki
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
ICS
 
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
ICS
 
Qt programming-using-cpp
Qt programming-using-cppQt programming-using-cpp

What's hot (20)

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
 
Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4Best Practices in Qt Quick/QML - Part 4
Best Practices in Qt Quick/QML - Part 4
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design Patterns
 
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
 
UI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QMLUI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QML
 
Qt Qml
Qt QmlQt Qml
Qt Qml
 
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
 
Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QML
 
QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong? QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong?
 
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 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
 
[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 Internationalization
Qt InternationalizationQt Internationalization
Qt Internationalization
 
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
 
02 - Basics of Qt
02 - Basics of Qt02 - Basics of Qt
02 - Basics of Qt
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
Qt 5 - C++ and Widgets
Qt 5 - C++ and WidgetsQt 5 - C++ and Widgets
Qt 5 - C++ and Widgets
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
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
 
Qt programming-using-cpp
Qt programming-using-cppQt programming-using-cpp
Qt programming-using-cpp
 

Similar to In-Depth Model/View with QML

Qt Quick in depth
Qt Quick in depthQt Quick in depth
Qt Quick in depth
Develer S.r.l.
 
Practical Model View Programming (Roadshow Version)
Practical Model View Programming (Roadshow Version)Practical Model View Programming (Roadshow Version)
Practical Model View Programming (Roadshow Version)
Marius Bugge Monsen
 
Thinking in Components
Thinking in ComponentsThinking in Components
Thinking in Components
Anton Ivanov
 
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
ICS
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
Omnia Helmi
 
AngularJS Best Practices
AngularJS Best PracticesAngularJS Best Practices
AngularJS Best Practices
Betclic Everest Group Tech Team
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
Antônio Roberto Silva
 
Alteryx SDK
Alteryx SDKAlteryx SDK
Alteryx SDK
James Dunkerley
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_HourDilip Patel
 
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Sparkhound Inc.
 
Model view-delegates-whitepaper
Model view-delegates-whitepaperModel view-delegates-whitepaper
Model view-delegates-whitepapernilus
 
PyData Berlin 2023 - Mythical ML Pipeline.pdf
PyData Berlin 2023 - Mythical ML Pipeline.pdfPyData Berlin 2023 - Mythical ML Pipeline.pdf
PyData Berlin 2023 - Mythical ML Pipeline.pdf
Jim Dowling
 
Samsung WebCL Prototype API
Samsung WebCL Prototype APISamsung WebCL Prototype API
Samsung WebCL Prototype APIRyo Jin
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
Ran Wahle
 
Meetup - Getting Started with MVVM Light for WPF - 11 may 2019
Meetup  - Getting Started with MVVM Light for WPF - 11 may 2019Meetup  - Getting Started with MVVM Light for WPF - 11 may 2019
Meetup - Getting Started with MVVM Light for WPF - 11 may 2019
iFour Technolab Pvt. Ltd.
 
AngularJS Workshop
AngularJS WorkshopAngularJS Workshop
AngularJS Workshop
Gianluca Cacace
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
zeeshanhanif
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
Ran Wahle
 
Zotonic tutorial EUC 2013
Zotonic tutorial EUC 2013Zotonic tutorial EUC 2013
Zotonic tutorial EUC 2013
Arjan
 
Qlikview online training
Qlikview online trainingQlikview online training
Qlikview online training
Glory IT Technologies Pvt. Ltd.
 

Similar to In-Depth Model/View with QML (20)

Qt Quick in depth
Qt Quick in depthQt Quick in depth
Qt Quick in depth
 
Practical Model View Programming (Roadshow Version)
Practical Model View Programming (Roadshow Version)Practical Model View Programming (Roadshow Version)
Practical Model View Programming (Roadshow Version)
 
Thinking in Components
Thinking in ComponentsThinking in Components
Thinking in Components
 
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
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
AngularJS Best Practices
AngularJS Best PracticesAngularJS Best Practices
AngularJS Best Practices
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
 
Alteryx SDK
Alteryx SDKAlteryx SDK
Alteryx SDK
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
 
Model view-delegates-whitepaper
Model view-delegates-whitepaperModel view-delegates-whitepaper
Model view-delegates-whitepaper
 
PyData Berlin 2023 - Mythical ML Pipeline.pdf
PyData Berlin 2023 - Mythical ML Pipeline.pdfPyData Berlin 2023 - Mythical ML Pipeline.pdf
PyData Berlin 2023 - Mythical ML Pipeline.pdf
 
Samsung WebCL Prototype API
Samsung WebCL Prototype APISamsung WebCL Prototype API
Samsung WebCL Prototype API
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
 
Meetup - Getting Started with MVVM Light for WPF - 11 may 2019
Meetup  - Getting Started with MVVM Light for WPF - 11 may 2019Meetup  - Getting Started with MVVM Light for WPF - 11 may 2019
Meetup - Getting Started with MVVM Light for WPF - 11 may 2019
 
AngularJS Workshop
AngularJS WorkshopAngularJS Workshop
AngularJS Workshop
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
 
Zotonic tutorial EUC 2013
Zotonic tutorial EUC 2013Zotonic tutorial EUC 2013
Zotonic tutorial EUC 2013
 
Qlikview online training
Qlikview online trainingQlikview online training
Qlikview online training
 

More from ICS

A Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdfA Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdf
ICS
 
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...
ICS
 
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
ICS
 
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...
ICS
 
Overcoming CMake Configuration Issues Webinar
Overcoming CMake Configuration Issues WebinarOvercoming CMake Configuration Issues Webinar
Overcoming CMake Configuration Issues Webinar
ICS
 
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
ICS
 
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
ICS
 
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
ICS
 
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
ICS
 
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
ICS
 
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
ICS
 
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
ICS
 
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
ICS
 
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
ICS
 
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
ICS
 
Basic Cmake for Qt Users
Basic Cmake for Qt UsersBasic Cmake for Qt Users
Basic Cmake for Qt Users
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
 
Qt Installer Framework
Qt Installer FrameworkQt Installer Framework
Qt Installer Framework
ICS
 
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
ICS
 
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
ICS
 

More from ICS (20)

A Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdfA Deep Dive into Secure Product Development Frameworks.pdf
A Deep Dive into Secure Product Development Frameworks.pdf
 
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
 

Recently uploaded

BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
Jelle | Nordend
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 

Recently uploaded (20)

BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 

In-Depth Model/View with QML

  • 1. Integrated Computer Solutions Inc. www.ics.com Qt Model / View with QML July 25th Webinar With Chris Probst & Ryan Hampton Visit us at http://www.ics.com Produced by Integrated Computer Solutions Material based on Qt 5.12 1
  • 2. Integrated Computer Solutions Inc. www.ics.com What is MVC? - Stands for Model/View/Controller - Architectural Design Pattern used for developing user interfaces - Separates data interactions into three separate parts - Allows for User Interface being independently developed from business logic. In general terms: - Model manages the data of the user interface - View displays the model - The controller responds to the user input and manages the model accordingly 2
  • 3. Integrated Computer Solutions Inc. www.ics.com Simple QML Example - In Qt/QML, the controller is combined with the view - A simple approach of leveraging Model/View in Qt/QML would be - For every value displayed, create a Q_PROPERTY - Provide a read, write and notify signal - Export the properties to QML, using void QQmlContext::setContextProperty 3 class simpleModel : public QObject { Q_OBJECT Q_PROPERTY(int speed READ speed WRITE setSpeed NOTIFY speedChanged) Q_PROPERTY(int temperature READ temperature WRITE setTemperature NOTIFY temperatureChanged) QQmlApplicationEngine engine; simpleModel aSimpleModel; engine.rootContext()->setContextProperty("asimplemodel",&asimpleModel); engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
  • 4. Integrated Computer Solutions Inc. www.ics.com Model View Delegate - Preserves Business-Logic/View separation - Model provides data to the view - View is the visual container displaying the data - Delegates renders each of the instances of the data - Available for both Widgets and QML 4
  • 5. Integrated Computer Solutions Inc. www.ics.com Other Simple Approaches - Creating the Model in QML - Standard QML models - ListModel - simple hierarchy of QML types - ObjectModel - Visual items, no delegate needed - XmlListModel - XML data source - Integer - read only, the model has no data roles - Object instances - properties of the object are the roles - JavaScript array - read only, no need for dynamic model updates 5 ListModel { id: fruitModel ListElement { name: "Apple" cost: 2.45 } ListElement { name: "Orange" cost: 3.25 } … }
  • 6. Integrated Computer Solutions Inc. www.ics.com Example: Contact List ● Create a ListModel ○ Fill it with ListElement objects, each with: ■ A name property ■ A file property referring to an image ● Add a ListView and a Component to use as a delegate ● Add header, footer and highlight properties to the view 6
  • 7. Integrated Computer Solutions Inc. www.ics.com Examples of QML Views - ListView 7 - Based on a Flickable area - It uses a model, instantiates a delegate and between the delegates, there can be spacing - Most commonly used - Can be horizontal or vertical ListView { model: mymodel delegate: numberDelegate spacing: 5 } }
  • 8. Integrated Computer Solutions Inc. www.ics.com Examples of QML Views - GridView 8 - Based on a Flickable area - It uses a model, instantiates a delegate and between the delegates, there can be spacing - Places the data into a two-dimensional grid, left-to-right or top-to-bottom See $QTDIRExamplesQt-5.11.2quickviews
  • 9. Integrated Computer Solutions Inc. www.ics.com Examples of QML Views - PathView 9 - Lays out the data along an arbitrary path - Most powerful, but also the most complex - Requires the path property to be set - Paths are specified using the Path QML object See $QTDIRExamplesQt-5.11.2quickviews
  • 10. Integrated Computer Solutions Inc. www.ics.com What about the Delegate? 10 - Appearance of each individual item - Can be a Component or a QML file See $QTDIRExamplesQt-5.11.2quickviews Column { spacing: 2 Repeater { model: 10 delegate: BlueBox { width: 100 height: 32 text: index } } }
  • 11. Integrated Computer Solutions Inc. www.ics.com A Model in C++ : A Simple Approach 11 QStringList dataList; dataList.append("Item 1"); dataList.append("Item 2"); dataList.append("Item 3"); dataList.append("Item 4"); QQmlApplicationEngine engine; engine.rootContext() QQmlContext *ctxt = view.rootContext(); ctxt->setContextProperty("myModel", QVariant::fromValue(dataList)); ListView { width: 100; height: 100 model: myModel delegate: Rectangle { height: 25 width: 100 Text { text: modelData } } } ● Model can be specified QStringList, QVariantList, QObjectList
  • 12. Integrated Computer Solutions Inc. www.ics.com QAbstractListModel - What to reimplement? 12 ● provide implementations of the QAbstractListModel::rowCount() and QAbstractListModel::data() functions. QVariant Mp3ListModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); Mp3Item *mp3Item = m_mp3Items.at(index.row()); switch (role) { case DoneRole: return QVariant(mp3Item->download.finished()); case UrlRole: return QVariant(mp3Item->download.url().toString()); case ProgressRole: return QVariant(mp3Item->download.progress()); case ErrorRole: return QVariant(mp3Item->download.error()); return QVariant(); } int Mp3ListModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return m_mp3Items.size(); }
  • 13. Integrated Computer Solutions Inc. www.ics.com QAbstractListModel - If user can change data? 13 ● Provide implementations of the QAbstractListModel::setData() functions. bool Mp3ListModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (role == SelectedRole) { if (index.row() < 0 || index.row() >= m_mp3Items.size()) return false; if (m_mp3Items.at(index.row())->selected == value.toBool()) return false; m_mp3Items.at(index.row())->selected = value.toBool(); dataChanged(index, index); return true; } return false; }
  • 14. Integrated Computer Solutions Inc. www.ics.com QAbstractListModel - A Note on Roles 14 ● Along with the QModelIndex, a role is simply an additional selector to access data in your model. class Mp3ListModel : public QAbstractListModel { Q_OBJECT public: explicit Mp3ListModel(QObject *parent = nullptr) noexcept; enum { SelectedRole = Qt::UserRole, DoneRole, UrlRole, ... }; QHash<int, QByteArray> Mp3ListModel::roleNames() const { QHash<int, QByteArray> roles; roles[SelectedRole] = "selected"; roles[DoneRole] = "done"; roles[ProgressRole] = "progress"; roles[UrlRole] = "url"; roles[ErrorRole] = "error"; return roles; } ListView { …. delegate: RowLayout { spacing: 10 CheckBox { checked: model.selected onClicked: model.selected = checked } Label { Layout.fillWidth: true text: model.error ? qsTr("Error on Download") : model.url elide: Text.ElideLeft ... }
  • 15. Integrated Computer Solutions Inc. www.ics.com QAbstractListModel - Notifying the View of Changes 15 ● Emit the signal: void QAbstractItemModel::dataChanged(const QModelIndex&topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = ...) m_mp3Items.at(index.row())->selected = value.toBool(); emit dataChanged(index, index);
  • 16. Integrated Computer Solutions Inc. www.ics.com Hooking the Model up to the View 16 #include <mp3listmodel> int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling); QQmlApplicationEngine engine; Mp3ListModel mp3ListModel(downloadDirUrl); engine.rootContext()->setContextProperty("mp3ListModel"), &mp3ListModel); qmlRegisterUncreatableType<Mp3ListModel>("DownloadManager", 1, 0, "Mp3ListModel", "Mp3ListModel should not be created in QML"); engine.load("qrc:/main.qml"); // Load blocks return app.exec(); } ListView { anchors.fill: parent model: mp3ListModel delegate: Mp3Item { width: parent.width } }
  • 17. Integrated Computer Solutions Inc. www.ics.com Example: Download Manager 17
  • 18. Integrated Computer Solutions Inc. www.ics.com Summary: Model / View Qt Model / View in a nutshell ● A model provides data for a view ● A view displays the data from the model ● Similar to the Model / View / Controller design pattern ○ But combine the controller with the view Why Model / View? ● Isolate business logic from UI logic ● Create UI components that are independent ○ Easier Development ○ Easier Testing ○ Easier Maintenance ● More Reuse ○ Reuse your UI logic across multiple views ○ Models can be reused for different views 18
  • 19. Integrated Computer Solutions Inc. www.ics.com Summary: Model / View Components Model: ● Interface to business logic data ● Emits signals when data changes or is appended ● Many common model types are provided by Qt ● C++: QStringList, QVariantList, QAbstractItemModel subclass ● QML: an integer, JavaScript array, ListModel, XmlListModel View: ● Displays the data structure ● Handles the user interaction with the data ● Qt provides many view types with model support ● QML: ListView, GridView, PathView, TableView (new) Delegate: ● Items in a view are rendered and edited by delegates ● The view expects a Component for its delegate property ● Model items are accessible through the index property 19
  • 20. Integrated Computer Solutions Inc. www.ics.com Summary: QML Views 20 ListView GridView TableViewPathView
  • 21. Integrated Computer Solutions Inc. www.ics.com Summary: Model Types 21 ● Standard QML models ○ ListModel - simple hierarchy of QML types ○ ObjectModel - Visual items, no delegate needed ○ XmlListModel - XML data source ○ Integer - read only, the model has no data roles ○ Object instances - properties of the object are the roles ○ JavaScript array - read only, no need for dynamic model updates ● C++ models (must be implemented in C++ before use) ○ More complex but more fine-tuned control over data access ○ QStringList, QVariantList, QObjectList, QAbstractItemModel (and subclasses) ○ Subclass QAbstractItemModel for complex data-sets
  • 22. Integrated Computer Solutions Inc. www.ics.com References ● Qt 5 E-book ● See https://qmlbook.github.io/ch07-modelview/modelview.html ● C++ GUI Programming with Qt 4 (see Model/View chapter) ● Examples: https://gitlab.com/RyanHampton/qml-model-view-framework Don’t know where to start? Go read the docs! ● Hint - start here: https://doc.qt.io/qt-5/qabstractlistmodel.html 22
  • 23. Integrated Computer Solutions Inc. www.ics.comIntegrated Computer Solutions Inc. Thank You! ● https://www.ics.com/blog/exploring-model-view-design-qt-quick ● ICS provides QML training for more in-depth learning 23 Model / View with QML Webinar: The End