SlideShare a Scribd company logo
1 of 15
Download to read offline
© Integrated Computer Solutions, Inc. All Rights Reserved
Basics of Model/View Qt
Programming
August 16, 2018
Qt for Beginners Summer Webinar Series
Part V
Copyright 2018, Integrated Computers Solutions, Inc.
This work may not be reproduced in whole or in part without the express written consent of Integrated
Computer Solutions, Inc.
© Integrated Computer Solutions, Inc. All Rights Reserved
Business Logic/UI Paradigm
-
Business Logic
C++
UI in C++
© Integrated Computer Solutions, Inc. All Rights Reserved
An Example
• An Example using Widgets
• Same Example using QML
3
© Integrated Computer Solutions, Inc. All Rights Reserved
The Model
• The model communicates to the view a source of data (e.g. text, icons,
font)
• All item models are based on the QAbstractItemModel class
• All models inherit from QAbstractItemModel
• QAbstractItemModel
- If structure of model is a tree
• QAbstractListModel
- If structure of model is a one-dimensional list
• QAbstractTableModel
- If structure of model is a table
4
© Integrated Computer Solutions, Inc. All Rights Reserved
The Data Function
- All abstract models must re-implement this function:
QVariant QAbstractItemModel::data(const QModelIndex &index, int role) const
5
QVariant MyModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole)
{
return QString("Row%1, Column%2")
.arg(index.row() + 1)
.arg(index.column() +1);
}
return QVariant();
}
© Integrated Computer Solutions, Inc. All Rights Reserved
What is QModelIndex?
• The QModelIndex class is used to locate data in a data model
• Temporary model indexes are provided by the QModelIndex class,
and persistent model indexes are provided by the
QPersistentModelIndex
• int QModelIndex::row() const
• int QModelIndex::column() const
• QModelIndex QModelIndex::parent() const
6
© Integrated Computer Solutions, Inc. All Rights Reserved
QModelIndex in Table/Tree Structures
• Rows and columns
• Item location in table model
• Item has no parent (parent.isValid() == false)
indexA = model->index(0, 0, QModelIndex());
indexB = model->index(1, 1, QModelIndex());
indexC = model->index(2, 1, QModelIndex());
• Parents, rows, and columns
• Item location in tree model
indexA = model->index(0, 0, QModelIndex());
indexC = model->index(2, 1, QModelIndex());
indexB = model->index(1, 0, indexA);
7
© Integrated Computer Solutions, Inc. All Rights Reserved
And What about Roles?
• Item performs various roles
• for other components (delegate, view, ...)
• Supplies different data
• for different situations
• Example:
• Qt::DisplayRoleused displayed string in view
• Asking for data
QVariant value = model->data(index, role);
// Asking for display text
QString text = model->data(index, Qt::DisplayRole).toString()
• Standard roles
• Defined by Qt::ItemDataRole
8
See enum Qt::ItemDataRole Documentation
© Integrated Computer Solutions, Inc. All Rights Reserved
When Data Changes
9
void DownloadModel::onUpdateProgress(qint64, qint64)
{
Downloads* download = qobject_cast<Downloads*>(sender());
if( download != Q_NULLPTR )
{
int row = this->downloads.indexOf(download);
QModelIndex index = this->index(row,1);
emit dataChanged(index, index); // refresh download column
}
}
© Integrated Computer Solutions, Inc. All Rights Reserved
When Data is Inserted/Removed
10
/ insert count rows into model before row
bool MyModel::insertRows(int row, int count, parent) {
beginInsertRows(parent, first, last);
// insert data into your backend
// ... endInsertRows();
}
// removes count rows from parent starting with row
bool MyModel::removeRows(int row, int count, parent) {
beginRemoveRows(parent, first, last);
// remove data from your backend
// ... endRemoveRows();
}
© Integrated Computer Solutions, Inc. All Rights Reserved
The View Classes in Widgets
QListView QTreeView QTableView
11
© Integrated Computer Solutions, Inc. All Rights Reserved
The View Classes in QML
ListView TreeView TableView
12
© Integrated Computer Solutions, Inc. All Rights Reserved
How it looks in C++ Code
13
model = new DownloadModel(this);
ui->tableView->setModel(model);
ProgressBarDelegate* delegate = new ProgressBarDelegate(this);
ui->tableView->setItemDelegateForColumn(1, delegate);
© Integrated Computer Solutions, Inc. All Rights Reserved 14
I
A Word on the Delegate
class BarGraphDelegate : public QAbstractItemDelegate {
public:
void paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const;
};
void BarGraphDelegate::paint(painter, option, index) const {
if (index.data(Qt::EditRole).userType() == QVariant::Int)
{
int value = index.data(Qt::EditRole).toInt();
// prepare rect with a width proportional to value
QRect rect(option.rect.adjusted(4,4,-4,-4));
rect.setWidth(rect.width()*value/MAX_VALUE);
// draw the value bar
painter->fillRect(rect, QColor("steelblue").lighter(value));
painter->drawText(option.rect, index.data().toString());
}
}
© 2018 Integrated Computer Solutions, Inc., The Qt Company
All Rights Reserved
Further Reading
- Model/View Programming
http://doc.qt.io/qt-5/model-view-programming.html
- Model/View Programming Tutorial
http://doc.qt.io/qt-5/modelview.html
15

More Related Content

What's hot

Meet Qt 6.0
Meet Qt 6.0 Meet Qt 6.0
Meet Qt 6.0
Qt
 

What's hot (20)

Hello, QML
Hello, QMLHello, QML
Hello, QML
 
Qt Internationalization
Qt InternationalizationQt Internationalization
Qt Internationalization
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
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 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
 
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
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part III
 
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
 
Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QML
 
02 - Basics of Qt
02 - Basics of Qt02 - Basics of Qt
02 - Basics of Qt
 
Qt Qml
Qt QmlQt Qml
Qt 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?
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
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
 
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
 
Qt 5 - C++ and Widgets
Qt 5 - C++ and WidgetsQt 5 - C++ and Widgets
Qt 5 - C++ and Widgets
 
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
 
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
 
Meet Qt 6.0
Meet Qt 6.0 Meet Qt 6.0
Meet Qt 6.0
 

Similar to Basics of Model/View Qt programming

Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8
Ovadiah Myrgorod
 
Model view-delegates-whitepaper
Model view-delegates-whitepaperModel view-delegates-whitepaper
Model view-delegates-whitepaper
nilus
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
Dilip Patel
 
Session 3 - Object oriented programming with Objective-C (part 1)
Session 3 - Object oriented programming with Objective-C (part 1)Session 3 - Object oriented programming with Objective-C (part 1)
Session 3 - Object oriented programming with Objective-C (part 1)
Vu Tran Lam
 

Similar to Basics of Model/View Qt programming (20)

Practical Model View Programming (Roadshow Version)
Practical Model View Programming (Roadshow Version)Practical Model View Programming (Roadshow Version)
Practical Model View Programming (Roadshow Version)
 
Java n-plus-1-incl-demo-slides
Java n-plus-1-incl-demo-slidesJava n-plus-1-incl-demo-slides
Java n-plus-1-incl-demo-slides
 
OOP.pptx
OOP.pptxOOP.pptx
OOP.pptx
 
Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8Using Backbone.js with Drupal 7 and 8
Using Backbone.js with Drupal 7 and 8
 
Backbone js-slides
Backbone js-slidesBackbone js-slides
Backbone js-slides
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
Model view-delegates-whitepaper
Model view-delegates-whitepaperModel view-delegates-whitepaper
Model view-delegates-whitepaper
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
Go Faster With Native Compilation
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native Compilation
 
Go Faster With Native Compilation
Go Faster With Native CompilationGo Faster With Native Compilation
Go Faster With Native Compilation
 
Go faster with_native_compilation Part-2
Go faster with_native_compilation Part-2Go faster with_native_compilation Part-2
Go faster with_native_compilation Part-2
 
Data Exploration in R.pptx
Data Exploration in R.pptxData Exploration in R.pptx
Data Exploration in R.pptx
 
Session 3 - Object oriented programming with Objective-C (part 1)
Session 3 - Object oriented programming with Objective-C (part 1)Session 3 - Object oriented programming with Objective-C (part 1)
Session 3 - Object oriented programming with Objective-C (part 1)
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Angular
AngularAngular
Angular
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 
Data herding
Data herdingData herding
Data herding
 
Data herding
Data herdingData herding
Data herding
 

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

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Recently uploaded (20)

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

Basics of Model/View Qt programming

  • 1. © Integrated Computer Solutions, Inc. All Rights Reserved Basics of Model/View Qt Programming August 16, 2018 Qt for Beginners Summer Webinar Series Part V Copyright 2018, Integrated Computers Solutions, Inc. This work may not be reproduced in whole or in part without the express written consent of Integrated Computer Solutions, Inc.
  • 2. © Integrated Computer Solutions, Inc. All Rights Reserved Business Logic/UI Paradigm - Business Logic C++ UI in C++
  • 3. © Integrated Computer Solutions, Inc. All Rights Reserved An Example • An Example using Widgets • Same Example using QML 3
  • 4. © Integrated Computer Solutions, Inc. All Rights Reserved The Model • The model communicates to the view a source of data (e.g. text, icons, font) • All item models are based on the QAbstractItemModel class • All models inherit from QAbstractItemModel • QAbstractItemModel - If structure of model is a tree • QAbstractListModel - If structure of model is a one-dimensional list • QAbstractTableModel - If structure of model is a table 4
  • 5. © Integrated Computer Solutions, Inc. All Rights Reserved The Data Function - All abstract models must re-implement this function: QVariant QAbstractItemModel::data(const QModelIndex &index, int role) const 5 QVariant MyModel::data(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { return QString("Row%1, Column%2") .arg(index.row() + 1) .arg(index.column() +1); } return QVariant(); }
  • 6. © Integrated Computer Solutions, Inc. All Rights Reserved What is QModelIndex? • The QModelIndex class is used to locate data in a data model • Temporary model indexes are provided by the QModelIndex class, and persistent model indexes are provided by the QPersistentModelIndex • int QModelIndex::row() const • int QModelIndex::column() const • QModelIndex QModelIndex::parent() const 6
  • 7. © Integrated Computer Solutions, Inc. All Rights Reserved QModelIndex in Table/Tree Structures • Rows and columns • Item location in table model • Item has no parent (parent.isValid() == false) indexA = model->index(0, 0, QModelIndex()); indexB = model->index(1, 1, QModelIndex()); indexC = model->index(2, 1, QModelIndex()); • Parents, rows, and columns • Item location in tree model indexA = model->index(0, 0, QModelIndex()); indexC = model->index(2, 1, QModelIndex()); indexB = model->index(1, 0, indexA); 7
  • 8. © Integrated Computer Solutions, Inc. All Rights Reserved And What about Roles? • Item performs various roles • for other components (delegate, view, ...) • Supplies different data • for different situations • Example: • Qt::DisplayRoleused displayed string in view • Asking for data QVariant value = model->data(index, role); // Asking for display text QString text = model->data(index, Qt::DisplayRole).toString() • Standard roles • Defined by Qt::ItemDataRole 8 See enum Qt::ItemDataRole Documentation
  • 9. © Integrated Computer Solutions, Inc. All Rights Reserved When Data Changes 9 void DownloadModel::onUpdateProgress(qint64, qint64) { Downloads* download = qobject_cast<Downloads*>(sender()); if( download != Q_NULLPTR ) { int row = this->downloads.indexOf(download); QModelIndex index = this->index(row,1); emit dataChanged(index, index); // refresh download column } }
  • 10. © Integrated Computer Solutions, Inc. All Rights Reserved When Data is Inserted/Removed 10 / insert count rows into model before row bool MyModel::insertRows(int row, int count, parent) { beginInsertRows(parent, first, last); // insert data into your backend // ... endInsertRows(); } // removes count rows from parent starting with row bool MyModel::removeRows(int row, int count, parent) { beginRemoveRows(parent, first, last); // remove data from your backend // ... endRemoveRows(); }
  • 11. © Integrated Computer Solutions, Inc. All Rights Reserved The View Classes in Widgets QListView QTreeView QTableView 11
  • 12. © Integrated Computer Solutions, Inc. All Rights Reserved The View Classes in QML ListView TreeView TableView 12
  • 13. © Integrated Computer Solutions, Inc. All Rights Reserved How it looks in C++ Code 13 model = new DownloadModel(this); ui->tableView->setModel(model); ProgressBarDelegate* delegate = new ProgressBarDelegate(this); ui->tableView->setItemDelegateForColumn(1, delegate);
  • 14. © Integrated Computer Solutions, Inc. All Rights Reserved 14 I A Word on the Delegate class BarGraphDelegate : public QAbstractItemDelegate { public: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; }; void BarGraphDelegate::paint(painter, option, index) const { if (index.data(Qt::EditRole).userType() == QVariant::Int) { int value = index.data(Qt::EditRole).toInt(); // prepare rect with a width proportional to value QRect rect(option.rect.adjusted(4,4,-4,-4)); rect.setWidth(rect.width()*value/MAX_VALUE); // draw the value bar painter->fillRect(rect, QColor("steelblue").lighter(value)); painter->drawText(option.rect, index.data().toString()); } }
  • 15. © 2018 Integrated Computer Solutions, Inc., The Qt Company All Rights Reserved Further Reading - Model/View Programming http://doc.qt.io/qt-5/model-view-programming.html - Model/View Programming Tutorial http://doc.qt.io/qt-5/modelview.html 15