SlideShare a Scribd company logo
Qt For Beginners - Part 1
Overview and Key Concepts
Sergio Shevchenko
eTuitus S.r.l.

1
Agenda
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
2
Agenda
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
3
Why Qt?
✓Write code once to target multiple platforms 

(“Write Once, Compile Anywhere”)
✓Produce compact, high-performance applications
✓Focus on innovation, not infrastructure coding
✓Count on professional services, support and training
✓Take part in an active Qt ecosystem
4
What is Qt?
5
Qt (/kjuːt/ "cute") is a cross-platform application framework that is widely used for developing
application software that can be run on various software and hardware platforms with little or
no change in the underlying codebase, while still being a native application with the capabilities
and speed thereof.
Widgets versus QML
Widgets:
Originally designed for desktop
Mouse and keyboard navigation
Can be used for embedded, incl. touchscreen
Stable
Qt Quick/QML:
Primarily designed for mobile/embedded
Touchscreen navigation
Declarative programming language QML backed by
JavaScript
Can be used for desktop too!
8
Agenda
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
9
How Much C++ Do You Need To Know?
Objects and classes
Declaring a class, inheritance, calling member functions
etc.
Polymorphism
Virtual methods
Operator overloading
Templates
Limited to the container and concurrent classes
No...
...RTTI
...Sophisticated templates
...Exceptions
...C++11/C++14
10
Agenda
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
11
Basic QML/Desktop Project
12
// Simple QML example

import QtQuick 2.6



Rectangle {

width: 200

height: 200

Text {

anchors.centerIn: parent

font.pixelSize: 18

text: "Hello, world!"

}

MouseArea {

anchors.fill: parent

onClicked: {

Qt.quit()

}

}

}
main.qml
13
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
main.cpp
14
Example testproject.pro
TEMPLATE = app # app is default - could be 'subdirs' or 'lib'
TARGET = testproject # executable or library name
QT += qml quick # Qt modules to use
CONFIG += debug c++11 # release is default
SOURCES += main.cpp # source files
RESOURCES += qml.qrc # resource files
15
Using qmake
qmake tool
Generates a Makefile or Visual Studio project
Build project using qmake
cd testProject
qmake testProject.pro # creates Makefile
make # compiles and links application
./testProject # executes application
Tip: qmake -project
Creates default project file based on directory content
You can run qmake from a different directory to
set up shadow build.
Qt Creator does it all for you
16
17
Qt Assistant
Standalone help browser
Reference Documentation
All classes documented
Contains tons of examples
Collection of Howtos and Overviews
18
Qt Creator IDE
19
Modules
20
Qt Modules
Qt Essentials: includes QtCore, QtGui, QtWidgets, QtQml, QtQuick, QtSql,
QtNetwork, QtTest, QtMultimedia, QtQuickControls, etc.
Add-on Modules included with Qt 5.6: QtBlueTooth, QtDbus, QtLocation,
QtPositioning, QtSvg, QtUiTools, QtWebEngineCore, QtWebSockets,
QtXml, QtXmlPatterns, etc.
Modules contain libraries, plugins, and documentation
Enable Qt Modules in qmake .pro file:

QT += widgets xml sql dbus multimedia network
Default: qmake projects use QtCore and QtGui
QWidget based projects require QtWidgets module
QtQuick2 projects require QtQuick and QtQml modules
Every Qt class has a header file.

#include <QApplication>

#include <QGuiApplication>

#include <QCoreApplication>

#include <QString>

#include <QColor>

#include <QWidget>

Every Qt Module has a header file.

#include <QtCore>

#include <QtGui>

#include <QtWidgets>

#include <QtMultimedia>

#include <QtSql>

#include <QtConcurrent>

Many modules have a corresponding Qt class.
Module headers include all of the classes in that module.
21
More Include Files
Agenda
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
22
Text Processing with QString
Strings can be created in a number of ways
Conversion constructor and assignment operators:
QString str("abc");
str = "def";
Create a numerical string using a static function:
QString n = QString::number(1234);
From a char pointer using the static functions:
QString text = QString::fromLatin1("Hello Qt");
QString text = QString::fromUtf8(inputText);
QString text = QString::fromLocal8Bit(cmdLineInput);
QString text = QStringLiteral("Literal string"); // UTF-8
From char pointer with translations:
QString text = tr("Hello Qt");
23
Text Processing with QString
QString str = str1 + str2;
fileName += ".txt";
simplified() // removes duplicate whitespace
left(), mid(), right() // part of a string
leftJustified(), rightJustified() // padded version
length(), endsWith(), startsWith()
contains(), count(), indexOf(), lastIndexOf()
toInt(), toDouble(), toLatin1(), toUtf8(), toLocal8Bit()
24
Formatted Output With QString::arg()
int i = ...;
int total = ...;
QString fileName = ...;
QString status = tr("Processing file %1 of %2: %3")
.arg(i).arg(total).arg(fileName);
double d = 12.34;
QString str = QString::fromLatin1("delta: %1").arg(d,0,'E',3)
// str == "delta: 1.234E+01";
Convenience: arg(QString,...,QString) (“multi-arg”).
Only works with all QString arguments.
25
Text Processing With QStringList
QString::split(), QStringList::join()
QStringList::replaceInStrings()
QStringList::filter()
26
Container Classes
General purpose template-based container classes
QList<QString> - Sequence Container
Other: QLinkedList, QVector, QStack, QQueue
QMap<int, QString> - Associative Container
Other: QHash, QSet, QMultiMap, QMultiHash
Qt's Container Classes compared to STL:
Lighter, safer, and easier to use than STL containers
If you prefer STL, feel free to... well.. whatever :-)
Methods exist that convert between Qt and STL
E.g. you need to pass std::list to a Qt method
27
Using Containers
Using QList
QList<QString> list;
list << "one" << "two" << "three";
QString item1 = list[1]; // "two"
for(int i = 0; i < list.count(); i++) {
const QString &item2 = list.at(i);
}
int index = list.indexOf("two"); // returns 1
Using QMap
QMap<QString, int> map;
map["Norway"] = 5; map["Italy"] = 48;
int val = map["France"]; // inserts key if not exists
if (map.contains("Norway")) {
int val2 = map.value("Norway"); // recommended lookup
}
28
Algorithm Complexity
Concern: How fast a function is as a container grows
Sequential Container











Associative Container
All complexities are amortized
29
Lookup Insert Append Prepend
QList O(1) O(n) O(1) O(1)
QVector O(1) O(n) O(1) O(n)
QLinkedList O(n) O(1) O(1) O(1)
Lookup Insert
QMap O(log(n)) O(log(n))
QHash O(1) O(1)
Iterators
Allow reading a container's content sequentially
Java-style iterators: simple and easy to use
QListIterator<...> for read
QMutableListIterator<...> for read-write
STL-style iterators slightly more efficient
QList::const_iterator for read
QList::iteratorfor read-write
Same works for QSet, QMap, QHash, ...
30
Iterators Java Style
Example QList iterator

QList<QString> list;

list << "A" << "B" << "C" << "D";

QListIterator<QString> it(list);

Forward iteration
while (it.hasNext()) {
qDebug() << it.next(); // A B C D
}

Backward iteration

it.toBack(); // position after the last item

while (it.hasPrevious()) {

qDebug() << it.previous(); // D C B A

}
31
STL-Style Iterators
Example QList iterator

QList<QString> list;

list << "A" << "B" << "C" << "D";

QList<QString>::iterator i;
Forward mutable iteration

for (i = list.begin(); i != list.end(); ++i) {

*i = (*i).toLower();

}
Backward mutable iteration

i = list.end();

while (i != list.begin()) {

--i;

*i = (*i).toLower();

}
QList<QString>::const_iterator for read-only
32
The foreach Keyword
It is a macro, feels like a keyword
foreach (const QString &str, list) {
if (str.isEmpty())
break;
qDebug() << str;
}
break and continue as normal
Modifying the container while iterating
Results in container being copied
Iteration continues in unmodified version
Not possible to modify item
Iterator variable is a const reference.
C++11 expands the for keyword for iteration over containers. C++11 auto feature
can also be useful for iterators to infer the appropriate type.
33
Implicit Sharing and Containers
Implicit Sharing
If an object is copied, then its data is copied only when the
data of one of the objects is changed ("copy on write")
Shared class has a pointer to shared data block
Shared data block = reference counter and actual data
Assignment is a shallow copy
Changing results into deep copy (detach)
QList<int> list1, list2;
list1 << 1 << 2;
list2 = list1; // shallow-copy: shares data with list1
list2 << 3; // deep-copy: change triggers detach
34
Agenda
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
35
Qt's C++ Object Model - QObject
QObject is the heart of Qt's object model
Include these features:
Memory management
Object properties
Introspection
Signals and Slots
QObject has no visual representation
36
Object Trees
QObjects organize themselves in object trees
Based on parent-child relationship
QObject(QObject *parent = 0)
Parent adds object to list of children
Parent owns children
Construction/Destruction
Trees can be constructed in any order
Trees can be destroyed in any order
If object has a parent: object is first removed from the parent
If object has children: deletes each child first
No object is deleted twice
Note: Parent-child relationship is not inheritance!
37
Creating Objects - General Guidelines
On Heap - QObject with parent
QTimer *timer = new QTimer(this);
On Stack - QObject without parent:
QFile, usually local to a function
QApplication (local to main())
QSettings, lightweight to create, local to a function
On Stack - value types
QString, QList, QHash, QMap, QColor, QImage,
QPixmap, QVariant
Stack or Heap - QDialog - depending on
lifetime
38
QVariant
QVariant
Union for common Qt "value types" (copyable, assignable)
Supports implicit sharing (fast copying)
Supports user types
A generic data object
Use cases:

QVariant property(const char *name) const;

void setProperty(const char *name, const QVariant &value);





class QAbstractItemModel {

virtual QVariant data(const QModelIndex &index, int role);

…

};
39
QVariant
For QtCore types
QVariant variant(42);

int value = variant.toInt(); // read back as integer

QString text = variant.toString(); // read back as string

qDebug() << variant.typeName(); // int
For non-core and custom types:

QVariant variant = QVariant::fromValue(QColor(Qt::red));

QColor color = variant.value<QColor>(); // read back

qDebug() << variant.typeName(); // "QColor"
40
Callbacks
General Problem: How do you get from "the user clicks a
button" to your business logic?
Possible solutions
Callbacks
Based on function pointers
Traditionally not type-safe
Observer Pattern (Listener)
Based on interface classes
Needs listener registration
Many interface classes
Qt uses
Signals and slots for high-level (semantic) callbacks
Virtual methods for low-level (syntactic) events.
41
Signal Slot diagram
42
QObject::connect(X, Signal1, Y, SlotA);
QObject::connect(Y, Signal1, X, SlotA);
QObject::connect(Z, Signal1, Y, SlotB);
QObject::connect(Z, Signal1, X, SlotA);
QObject::connect(Z, Signal2, X, SlotB);
Custom Slots
File: myclass.h
class MyClass : public QObject
{
Q_OBJECT // marker for moc
// …
public slots:
void setValue(int value); // a custom slot
};
File: myclass.cpp
void MyClass::setValue(int value) {
// slot implementation
}
43
Custom Signals
File: myclass.h
class MyClass : public QObject
{
Q_OBJECT // marker for moc
// …
signals:
void valueChanged(int value); // a custom signal
};
File: myclass.cpp
// No implementation for a signal!
Sending a signal
emit valueChanged(value);
44
// Slider.qml
Rectangle {
id: container
...
signal valueChanged(var v)
...
MouseArea {
anchors.fill: parent
...
onPositionChanged: {
currentValue = factor * slide.x
container.valueChanged(currentValue)
}
}
...
...
Signal Emitted
Connecting Signals to Slots
45
// Spinner.qml
signal valueChanged(var v)
...
function setValue(newValue) {
if (newValue !== view.currentIndex) {
view.currentIndex = newValue
}
}
...
Slot/Method Implemented
46
Connecting Signals to Slots
QObject::connect(sliderItem, SIGNAL(valueChanged(QVariant)),
pickerItem, SLOT(setValue(QVariant)));
In C++ Code: Signal/Slot Connection Established
Connecting Signals to Slots
47
Connections {
target: slider
onValueChanged: {
picker.setValue(slider.value)
}
}
In QML Code: Signal/Slot Connection Established
Connecting Signals to Slots
48
Connection Variants
Using macros (traditional method):

connect(slider, SIGNAL(valueChanged(int)),

spinbox, SLOT(setValue(int)));

Using member functions:

connect(slider, &QSlider::valueChanged,

spinbox, &QSpinBox::setValue);

Using non-member functions:
static void printValue(int value) {...}
connect(slider, &QSlider::valueChanged, &printValue);

Using C++11 lambda functions:
connect(slider, &QSlider::valueChanged,
[=] (int value) {...});
49
Variations of Signal/Slot Connections
Signal to Signal connection
connect(bt, SIGNAL(clicked()), this, SIGNAL(okSignal()));
Not allowed to name parameters
connect(m_slider,SIGNAL(valueChanged(int value)),

this, SLOT(setValue(int newValue)))
50
Agenda
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
51
A Look Ahead
Qt For Beginners Part 2 - QML and Qt Quick
Qt For Beginners Part 3 - Doing More with mobile
52
Agenda
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
53

More Related Content

PDF
02 - Basics of Qt
PDF
Best Practices in Qt Quick/QML - Part 1 of 4
 
PDF
In-Depth Model/View with QML
 
PPTX
Qt for beginners part 1 overview and key concepts
 
PDF
Best Practices in Qt Quick/QML - Part 3
 
PPTX
Introduction to Qt
PDF
Qt Application Programming with C++ - Part 1
PDF
Best Practices in Qt Quick/QML - Part 4
 
02 - Basics of Qt
Best Practices in Qt Quick/QML - Part 1 of 4
 
In-Depth Model/View with QML
 
Qt for beginners part 1 overview and key concepts
 
Best Practices in Qt Quick/QML - Part 3
 
Introduction to Qt
Qt Application Programming with C++ - Part 1
Best Practices in Qt Quick/QML - Part 4
 

What's hot (20)

PDF
Lessons Learned from Building 100+ C++/Qt/QML Devices
 
PDF
QVariant, QObject — Qt's not just for GUI development
 
PDF
Best Practices in Qt Quick/QML - Part III
 
PPTX
Best Practices in Qt Quick/QML - Part I
 
PDF
Best Practices in Qt Quick/QML - Part II
 
PPT
Qt Technical Presentation
ODP
Unit testing with Qt test
PDF
PyQGIS 개발자 쿡북(PyQGIS Developer Cookbook) 한국어 판
PDF
Introduction to Qt programming
PDF
Best Practices in Qt Quick/QML - Part IV
 
PPTX
UI Programming with Qt-Quick and QML
PPTX
Hello, QML
PDF
QThreads: Are You Using Them Wrong?
 
PPTX
Qt Framework Events Signals Threads
PDF
Qt Internationalization
 
PDF
Qt Design Patterns
PPTX
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
 
PDF
Introduction to the Qt Quick Scene Graph
 
PPTX
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
ODP
Qt Workshop
Lessons Learned from Building 100+ C++/Qt/QML Devices
 
QVariant, QObject — Qt's not just for GUI development
 
Best Practices in Qt Quick/QML - Part III
 
Best Practices in Qt Quick/QML - Part I
 
Best Practices in Qt Quick/QML - Part II
 
Qt Technical Presentation
Unit testing with Qt test
PyQGIS 개발자 쿡북(PyQGIS Developer Cookbook) 한국어 판
Introduction to Qt programming
Best Practices in Qt Quick/QML - Part IV
 
UI Programming with Qt-Quick and QML
Hello, QML
QThreads: Are You Using Them Wrong?
 
Qt Framework Events Signals Threads
Qt Internationalization
 
Qt Design Patterns
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
 
Introduction to the Qt Quick Scene Graph
 
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
Qt Workshop
Ad

Similar to Qt for beginners (20)

PDF
Qt everywhere a c++ abstraction platform
PPTX
Return of c++
PDF
Qt for beginners part 4 doing more
 
PPTX
Iron python
PPTX
Cross Platform App Development with C++
PPTX
Untitled presentation(4)
PPTX
Qt coin3d soqt
PPTX
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
PDF
Integrazione QML / C++
PDF
PGConf APAC 2018 - Patroni: Kubernetes-native PostgreSQL companion
DOC
1183 c-interview-questions-and-answers
PPTX
MattsonTutorialSC14.pptx
PDF
Use C++ and Intel® Threading Building Blocks (Intel® TBB) for Hardware Progra...
PDF
Scripting Your Qt Application
PDF
OpenCL programming using Python syntax
PDF
Open cl programming using python syntax
PPT
Qt for S60
PDF
OSDC 2016 | rkt and Kubernetes: What’s new with Container Runtimes and Orches...
PDF
OSDC 2016 - rkt and Kubernentes what's new with Container Runtimes and Orches...
Qt everywhere a c++ abstraction platform
Return of c++
Qt for beginners part 4 doing more
 
Iron python
Cross Platform App Development with C++
Untitled presentation(4)
Qt coin3d soqt
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
Integrazione QML / C++
PGConf APAC 2018 - Patroni: Kubernetes-native PostgreSQL companion
1183 c-interview-questions-and-answers
MattsonTutorialSC14.pptx
Use C++ and Intel® Threading Building Blocks (Intel® TBB) for Hardware Progra...
Scripting Your Qt Application
OpenCL programming using Python syntax
Open cl programming using python syntax
Qt for S60
OSDC 2016 | rkt and Kubernetes: What’s new with Container Runtimes and Orches...
OSDC 2016 - rkt and Kubernentes what's new with Container Runtimes and Orches...
Ad

More from Sergio Shevchenko (12)

PDF
Gestione dell'economia nelle reti di Self Sovereign Identity con Algorand Sm...
PDF
Kubernetes - from sketch to production
PDF
Meltdown & spectre
PDF
The Google file system
PDF
μ-Kernel Evolution
PDF
Burrows-Wheeler transform for terabases
PDF
Presentazione CERT-CHECK
PDF
Design patterns: Creational patterns
PDF
Bitcoin and blockchain
PDF
Qt Multiplatform development
PPTX
Continuous Integration
PPTX
Mobile Factor App
Gestione dell'economia nelle reti di Self Sovereign Identity con Algorand Sm...
Kubernetes - from sketch to production
Meltdown & spectre
The Google file system
μ-Kernel Evolution
Burrows-Wheeler transform for terabases
Presentazione CERT-CHECK
Design patterns: Creational patterns
Bitcoin and blockchain
Qt Multiplatform development
Continuous Integration
Mobile Factor App

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPT
Teaching material agriculture food technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
KodekX | Application Modernization Development
PPTX
Cloud computing and distributed systems.
PPTX
MYSQL Presentation for SQL database connectivity
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
NewMind AI Weekly Chronicles - August'25 Week I
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Understanding_Digital_Forensics_Presentation.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
sap open course for s4hana steps from ECC to s4
Reach Out and Touch Someone: Haptics and Empathic Computing
Dropbox Q2 2025 Financial Results & Investor Presentation
Review of recent advances in non-invasive hemoglobin estimation
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
Teaching material agriculture food technology
Network Security Unit 5.pdf for BCA BBA.
KodekX | Application Modernization Development
Cloud computing and distributed systems.
MYSQL Presentation for SQL database connectivity
The Rise and Fall of 3GPP – Time for a Sabbatical?
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

Qt for beginners

  • 1. Qt For Beginners - Part 1 Overview and Key Concepts Sergio Shevchenko eTuitus S.r.l.
 1
  • 2. Agenda Features of Qt C++ Refresher Hello World Application Core Classes Objects and Object Communication A Look Ahead Q&A 2
  • 3. Agenda Features of Qt C++ Refresher Hello World Application Core Classes Objects and Object Communication A Look Ahead Q&A 3
  • 4. Why Qt? ✓Write code once to target multiple platforms 
 (“Write Once, Compile Anywhere”) ✓Produce compact, high-performance applications ✓Focus on innovation, not infrastructure coding ✓Count on professional services, support and training ✓Take part in an active Qt ecosystem 4
  • 5. What is Qt? 5 Qt (/kjuːt/ "cute") is a cross-platform application framework that is widely used for developing application software that can be run on various software and hardware platforms with little or no change in the underlying codebase, while still being a native application with the capabilities and speed thereof.
  • 6. Widgets versus QML Widgets: Originally designed for desktop Mouse and keyboard navigation Can be used for embedded, incl. touchscreen Stable Qt Quick/QML: Primarily designed for mobile/embedded Touchscreen navigation Declarative programming language QML backed by JavaScript Can be used for desktop too! 8
  • 7. Agenda Features of Qt C++ Refresher Hello World Application Core Classes Objects and Object Communication A Look Ahead Q&A 9
  • 8. How Much C++ Do You Need To Know? Objects and classes Declaring a class, inheritance, calling member functions etc. Polymorphism Virtual methods Operator overloading Templates Limited to the container and concurrent classes No... ...RTTI ...Sophisticated templates ...Exceptions ...C++11/C++14 10
  • 9. Agenda Features of Qt C++ Refresher Hello World Application Core Classes Objects and Object Communication A Look Ahead Q&A 11
  • 11. // Simple QML example
 import QtQuick 2.6
 
 Rectangle {
 width: 200
 height: 200
 Text {
 anchors.centerIn: parent
 font.pixelSize: 18
 text: "Hello, world!"
 }
 MouseArea {
 anchors.fill: parent
 onClicked: {
 Qt.quit()
 }
 }
 } main.qml 13
  • 12. #include <QGuiApplication> #include <QQmlApplicationEngine> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); return app.exec(); } main.cpp 14
  • 13. Example testproject.pro TEMPLATE = app # app is default - could be 'subdirs' or 'lib' TARGET = testproject # executable or library name QT += qml quick # Qt modules to use CONFIG += debug c++11 # release is default SOURCES += main.cpp # source files RESOURCES += qml.qrc # resource files 15
  • 14. Using qmake qmake tool Generates a Makefile or Visual Studio project Build project using qmake cd testProject qmake testProject.pro # creates Makefile make # compiles and links application ./testProject # executes application Tip: qmake -project Creates default project file based on directory content You can run qmake from a different directory to set up shadow build. Qt Creator does it all for you 16
  • 15. 17
  • 16. Qt Assistant Standalone help browser Reference Documentation All classes documented Contains tons of examples Collection of Howtos and Overviews 18
  • 18. Modules 20 Qt Modules Qt Essentials: includes QtCore, QtGui, QtWidgets, QtQml, QtQuick, QtSql, QtNetwork, QtTest, QtMultimedia, QtQuickControls, etc. Add-on Modules included with Qt 5.6: QtBlueTooth, QtDbus, QtLocation, QtPositioning, QtSvg, QtUiTools, QtWebEngineCore, QtWebSockets, QtXml, QtXmlPatterns, etc. Modules contain libraries, plugins, and documentation Enable Qt Modules in qmake .pro file:
 QT += widgets xml sql dbus multimedia network Default: qmake projects use QtCore and QtGui QWidget based projects require QtWidgets module QtQuick2 projects require QtQuick and QtQml modules
  • 19. Every Qt class has a header file.
 #include <QApplication>
 #include <QGuiApplication>
 #include <QCoreApplication>
 #include <QString>
 #include <QColor>
 #include <QWidget>
 Every Qt Module has a header file.
 #include <QtCore>
 #include <QtGui>
 #include <QtWidgets>
 #include <QtMultimedia>
 #include <QtSql>
 #include <QtConcurrent>
 Many modules have a corresponding Qt class. Module headers include all of the classes in that module. 21 More Include Files
  • 20. Agenda Features of Qt C++ Refresher Hello World Application Core Classes Objects and Object Communication A Look Ahead Q&A 22
  • 21. Text Processing with QString Strings can be created in a number of ways Conversion constructor and assignment operators: QString str("abc"); str = "def"; Create a numerical string using a static function: QString n = QString::number(1234); From a char pointer using the static functions: QString text = QString::fromLatin1("Hello Qt"); QString text = QString::fromUtf8(inputText); QString text = QString::fromLocal8Bit(cmdLineInput); QString text = QStringLiteral("Literal string"); // UTF-8 From char pointer with translations: QString text = tr("Hello Qt"); 23
  • 22. Text Processing with QString QString str = str1 + str2; fileName += ".txt"; simplified() // removes duplicate whitespace left(), mid(), right() // part of a string leftJustified(), rightJustified() // padded version length(), endsWith(), startsWith() contains(), count(), indexOf(), lastIndexOf() toInt(), toDouble(), toLatin1(), toUtf8(), toLocal8Bit() 24
  • 23. Formatted Output With QString::arg() int i = ...; int total = ...; QString fileName = ...; QString status = tr("Processing file %1 of %2: %3") .arg(i).arg(total).arg(fileName); double d = 12.34; QString str = QString::fromLatin1("delta: %1").arg(d,0,'E',3) // str == "delta: 1.234E+01"; Convenience: arg(QString,...,QString) (“multi-arg”). Only works with all QString arguments. 25
  • 24. Text Processing With QStringList QString::split(), QStringList::join() QStringList::replaceInStrings() QStringList::filter() 26
  • 25. Container Classes General purpose template-based container classes QList<QString> - Sequence Container Other: QLinkedList, QVector, QStack, QQueue QMap<int, QString> - Associative Container Other: QHash, QSet, QMultiMap, QMultiHash Qt's Container Classes compared to STL: Lighter, safer, and easier to use than STL containers If you prefer STL, feel free to... well.. whatever :-) Methods exist that convert between Qt and STL E.g. you need to pass std::list to a Qt method 27
  • 26. Using Containers Using QList QList<QString> list; list << "one" << "two" << "three"; QString item1 = list[1]; // "two" for(int i = 0; i < list.count(); i++) { const QString &item2 = list.at(i); } int index = list.indexOf("two"); // returns 1 Using QMap QMap<QString, int> map; map["Norway"] = 5; map["Italy"] = 48; int val = map["France"]; // inserts key if not exists if (map.contains("Norway")) { int val2 = map.value("Norway"); // recommended lookup } 28
  • 27. Algorithm Complexity Concern: How fast a function is as a container grows Sequential Container
 
 
 
 
 
 Associative Container All complexities are amortized 29 Lookup Insert Append Prepend QList O(1) O(n) O(1) O(1) QVector O(1) O(n) O(1) O(n) QLinkedList O(n) O(1) O(1) O(1) Lookup Insert QMap O(log(n)) O(log(n)) QHash O(1) O(1)
  • 28. Iterators Allow reading a container's content sequentially Java-style iterators: simple and easy to use QListIterator<...> for read QMutableListIterator<...> for read-write STL-style iterators slightly more efficient QList::const_iterator for read QList::iteratorfor read-write Same works for QSet, QMap, QHash, ... 30
  • 29. Iterators Java Style Example QList iterator
 QList<QString> list;
 list << "A" << "B" << "C" << "D";
 QListIterator<QString> it(list);
 Forward iteration while (it.hasNext()) { qDebug() << it.next(); // A B C D }
 Backward iteration
 it.toBack(); // position after the last item
 while (it.hasPrevious()) {
 qDebug() << it.previous(); // D C B A
 } 31
  • 30. STL-Style Iterators Example QList iterator
 QList<QString> list;
 list << "A" << "B" << "C" << "D";
 QList<QString>::iterator i; Forward mutable iteration
 for (i = list.begin(); i != list.end(); ++i) {
 *i = (*i).toLower();
 } Backward mutable iteration
 i = list.end();
 while (i != list.begin()) {
 --i;
 *i = (*i).toLower();
 } QList<QString>::const_iterator for read-only 32
  • 31. The foreach Keyword It is a macro, feels like a keyword foreach (const QString &str, list) { if (str.isEmpty()) break; qDebug() << str; } break and continue as normal Modifying the container while iterating Results in container being copied Iteration continues in unmodified version Not possible to modify item Iterator variable is a const reference. C++11 expands the for keyword for iteration over containers. C++11 auto feature can also be useful for iterators to infer the appropriate type. 33
  • 32. Implicit Sharing and Containers Implicit Sharing If an object is copied, then its data is copied only when the data of one of the objects is changed ("copy on write") Shared class has a pointer to shared data block Shared data block = reference counter and actual data Assignment is a shallow copy Changing results into deep copy (detach) QList<int> list1, list2; list1 << 1 << 2; list2 = list1; // shallow-copy: shares data with list1 list2 << 3; // deep-copy: change triggers detach 34
  • 33. Agenda Features of Qt C++ Refresher Hello World Application Core Classes Objects and Object Communication A Look Ahead Q&A 35
  • 34. Qt's C++ Object Model - QObject QObject is the heart of Qt's object model Include these features: Memory management Object properties Introspection Signals and Slots QObject has no visual representation 36
  • 35. Object Trees QObjects organize themselves in object trees Based on parent-child relationship QObject(QObject *parent = 0) Parent adds object to list of children Parent owns children Construction/Destruction Trees can be constructed in any order Trees can be destroyed in any order If object has a parent: object is first removed from the parent If object has children: deletes each child first No object is deleted twice Note: Parent-child relationship is not inheritance! 37
  • 36. Creating Objects - General Guidelines On Heap - QObject with parent QTimer *timer = new QTimer(this); On Stack - QObject without parent: QFile, usually local to a function QApplication (local to main()) QSettings, lightweight to create, local to a function On Stack - value types QString, QList, QHash, QMap, QColor, QImage, QPixmap, QVariant Stack or Heap - QDialog - depending on lifetime 38
  • 37. QVariant QVariant Union for common Qt "value types" (copyable, assignable) Supports implicit sharing (fast copying) Supports user types A generic data object Use cases:
 QVariant property(const char *name) const;
 void setProperty(const char *name, const QVariant &value);
 
 
 class QAbstractItemModel {
 virtual QVariant data(const QModelIndex &index, int role);
 …
 }; 39
  • 38. QVariant For QtCore types QVariant variant(42);
 int value = variant.toInt(); // read back as integer
 QString text = variant.toString(); // read back as string
 qDebug() << variant.typeName(); // int For non-core and custom types:
 QVariant variant = QVariant::fromValue(QColor(Qt::red));
 QColor color = variant.value<QColor>(); // read back
 qDebug() << variant.typeName(); // "QColor" 40
  • 39. Callbacks General Problem: How do you get from "the user clicks a button" to your business logic? Possible solutions Callbacks Based on function pointers Traditionally not type-safe Observer Pattern (Listener) Based on interface classes Needs listener registration Many interface classes Qt uses Signals and slots for high-level (semantic) callbacks Virtual methods for low-level (syntactic) events. 41
  • 40. Signal Slot diagram 42 QObject::connect(X, Signal1, Y, SlotA); QObject::connect(Y, Signal1, X, SlotA); QObject::connect(Z, Signal1, Y, SlotB); QObject::connect(Z, Signal1, X, SlotA); QObject::connect(Z, Signal2, X, SlotB);
  • 41. Custom Slots File: myclass.h class MyClass : public QObject { Q_OBJECT // marker for moc // … public slots: void setValue(int value); // a custom slot }; File: myclass.cpp void MyClass::setValue(int value) { // slot implementation } 43
  • 42. Custom Signals File: myclass.h class MyClass : public QObject { Q_OBJECT // marker for moc // … signals: void valueChanged(int value); // a custom signal }; File: myclass.cpp // No implementation for a signal! Sending a signal emit valueChanged(value); 44
  • 43. // Slider.qml Rectangle { id: container ... signal valueChanged(var v) ... MouseArea { anchors.fill: parent ... onPositionChanged: { currentValue = factor * slide.x container.valueChanged(currentValue) } } ... ... Signal Emitted Connecting Signals to Slots 45
  • 44. // Spinner.qml signal valueChanged(var v) ... function setValue(newValue) { if (newValue !== view.currentIndex) { view.currentIndex = newValue } } ... Slot/Method Implemented 46 Connecting Signals to Slots
  • 45. QObject::connect(sliderItem, SIGNAL(valueChanged(QVariant)), pickerItem, SLOT(setValue(QVariant))); In C++ Code: Signal/Slot Connection Established Connecting Signals to Slots 47
  • 46. Connections { target: slider onValueChanged: { picker.setValue(slider.value) } } In QML Code: Signal/Slot Connection Established Connecting Signals to Slots 48
  • 47. Connection Variants Using macros (traditional method):
 connect(slider, SIGNAL(valueChanged(int)),
 spinbox, SLOT(setValue(int)));
 Using member functions:
 connect(slider, &QSlider::valueChanged,
 spinbox, &QSpinBox::setValue);
 Using non-member functions: static void printValue(int value) {...} connect(slider, &QSlider::valueChanged, &printValue);
 Using C++11 lambda functions: connect(slider, &QSlider::valueChanged, [=] (int value) {...}); 49
  • 48. Variations of Signal/Slot Connections Signal to Signal connection connect(bt, SIGNAL(clicked()), this, SIGNAL(okSignal())); Not allowed to name parameters connect(m_slider,SIGNAL(valueChanged(int value)),
 this, SLOT(setValue(int newValue))) 50
  • 49. Agenda Features of Qt C++ Refresher Hello World Application Core Classes Objects and Object Communication A Look Ahead Q&A 51
  • 50. A Look Ahead Qt For Beginners Part 2 - QML and Qt Quick Qt For Beginners Part 3 - Doing More with mobile 52
  • 51. Agenda Features of Qt C++ Refresher Hello World Application Core Classes Objects and Object Communication A Look Ahead Q&A 53