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

What's hot

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
ICS
 
Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4
ICS
 
Qt Internationalization
Qt InternationalizationQt Internationalization
Qt Internationalization
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
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programming
ICS
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QML
ICS
 
Best Practices in Qt Quick/QML - Part 3
Best Practices in Qt Quick/QML - Part 3Best Practices in Qt Quick/QML - Part 3
Best Practices in Qt Quick/QML - Part 3
ICS
 
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 programming-using-cpp
Qt programming-using-cppQt programming-using-cpp
Best Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVBest Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IV
ICS
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
Neera Mital
 
Hello, QML
Hello, QMLHello, QML
Hello, QML
Jack Yang
 
05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics
Andreas Jakl
 
Python GUI
Python GUIPython GUI
Python GUI
LusciousLarryDas
 
Qt Technical Presentation
Qt Technical PresentationQt Technical Presentation
Qt Technical Presentation
Daniel Rocha
 
[Webinar] QtSerialBus: Using Modbus and CAN bus with Qt
[Webinar] QtSerialBus: Using Modbus and CAN bus with Qt[Webinar] QtSerialBus: Using Modbus and CAN bus with Qt
[Webinar] QtSerialBus: Using Modbus and CAN bus with Qt
ICS
 
Qt State Machine Framework
Qt State Machine FrameworkQt State Machine Framework
Qt State Machine Framework
account inactive
 
Qt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt QuickQt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt Quick
ICS
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#Doncho Minkov
 

What's hot (20)

Qt Qml
Qt QmlQt Qml
Qt Qml
 
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
 
Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4
 
Qt Internationalization
Qt InternationalizationQt Internationalization
Qt Internationalization
 
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
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programming
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QML
 
Best Practices in Qt Quick/QML - Part 3
Best Practices in Qt Quick/QML - Part 3Best Practices in Qt Quick/QML - Part 3
Best Practices in Qt Quick/QML - Part 3
 
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 programming-using-cpp
Qt programming-using-cppQt programming-using-cpp
Qt programming-using-cpp
 
Best Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVBest Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IV
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
 
Hello, QML
Hello, QMLHello, QML
Hello, QML
 
05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics
 
Python GUI
Python GUIPython GUI
Python GUI
 
Qt Technical Presentation
Qt Technical PresentationQt Technical Presentation
Qt Technical Presentation
 
[Webinar] QtSerialBus: Using Modbus and CAN bus with Qt
[Webinar] QtSerialBus: Using Modbus and CAN bus with Qt[Webinar] QtSerialBus: Using Modbus and CAN bus with Qt
[Webinar] QtSerialBus: Using Modbus and CAN bus with Qt
 
Qt State Machine Framework
Qt State Machine FrameworkQt State Machine Framework
Qt State Machine Framework
 
Qt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt QuickQt for Beginners Part 3 - QML and Qt Quick
Qt for Beginners Part 3 - QML and Qt Quick
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 

Similar to Qt for beginners

Qt everywhere a c++ abstraction platform
Qt everywhere   a c++ abstraction platformQt everywhere   a c++ abstraction platform
Qt everywhere a c++ abstraction platformDeveler S.r.l.
 
Return of c++
Return of c++Return of c++
Return of c++
Yongwei Wu
 
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
 
Cross Platform App Development with C++
Cross Platform App Development with C++Cross Platform App Development with C++
Cross Platform App Development with C++
Joan Puig Sanz
 
Untitled presentation(4)
Untitled presentation(4)Untitled presentation(4)
Untitled presentation(4)chan20kaur
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
PROIDEA
 
Integrazione QML / C++
Integrazione QML / C++Integrazione QML / C++
Integrazione QML / C++
Paolo Sereno
 
PGConf APAC 2018 - Patroni: Kubernetes-native PostgreSQL companion
PGConf APAC 2018 - Patroni: Kubernetes-native PostgreSQL companionPGConf APAC 2018 - Patroni: Kubernetes-native PostgreSQL companion
PGConf APAC 2018 - Patroni: Kubernetes-native PostgreSQL companion
PGConf APAC
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
Akash Gawali
 
MattsonTutorialSC14.pptx
MattsonTutorialSC14.pptxMattsonTutorialSC14.pptx
MattsonTutorialSC14.pptx
gopikahari7
 
Use C++ and Intel® Threading Building Blocks (Intel® TBB) for Hardware Progra...
Use C++ and Intel® Threading Building Blocks (Intel® TBB) for Hardware Progra...Use C++ and Intel® Threading Building Blocks (Intel® TBB) for Hardware Progra...
Use C++ and Intel® Threading Building Blocks (Intel® TBB) for Hardware Progra...
Intel® Software
 
Scripting Your Qt Application
Scripting Your Qt ApplicationScripting Your Qt Application
Scripting Your Qt Application
account inactive
 
Open cl programming using python syntax
Open cl programming using python syntaxOpen cl programming using python syntax
Open cl programming using python syntax
csandit
 
OpenCL programming using Python syntax
OpenCL programming using Python syntax OpenCL programming using Python syntax
OpenCL programming using Python syntax
cscpconf
 
Qt for S60
Qt for S60Qt for S60
Qt for S60
Mark Wilcox
 
OSDC 2016 - rkt and Kubernentes what's new with Container Runtimes and Orches...
OSDC 2016 - rkt and Kubernentes what's new with Container Runtimes and Orches...OSDC 2016 - rkt and Kubernentes what's new with Container Runtimes and Orches...
OSDC 2016 - rkt and Kubernentes what's new with Container Runtimes and Orches...
NETWAYS
 
OSDC 2016 | rkt and Kubernetes: What’s new with Container Runtimes and Orches...
OSDC 2016 | rkt and Kubernetes: What’s new with Container Runtimes and Orches...OSDC 2016 | rkt and Kubernetes: What’s new with Container Runtimes and Orches...
OSDC 2016 | rkt and Kubernetes: What’s new with Container Runtimes and Orches...
NETWAYS
 

Similar to Qt for beginners (20)

Qt
QtQt
Qt
 
Qt everywhere a c++ abstraction platform
Qt everywhere   a c++ abstraction platformQt everywhere   a c++ abstraction platform
Qt everywhere a c++ abstraction platform
 
Return of c++
Return of c++Return of c++
Return of c++
 
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
 
Iron python
Iron pythonIron python
Iron python
 
Cross Platform App Development with C++
Cross Platform App Development with C++Cross Platform App Development with C++
Cross Platform App Development with C++
 
Qt coin3d soqt
Qt coin3d soqtQt coin3d soqt
Qt coin3d soqt
 
Untitled presentation(4)
Untitled presentation(4)Untitled presentation(4)
Untitled presentation(4)
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
 
Integrazione QML / C++
Integrazione QML / C++Integrazione QML / C++
Integrazione QML / C++
 
PGConf APAC 2018 - Patroni: Kubernetes-native PostgreSQL companion
PGConf APAC 2018 - Patroni: Kubernetes-native PostgreSQL companionPGConf APAC 2018 - Patroni: Kubernetes-native PostgreSQL companion
PGConf APAC 2018 - Patroni: Kubernetes-native PostgreSQL companion
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
MattsonTutorialSC14.pptx
MattsonTutorialSC14.pptxMattsonTutorialSC14.pptx
MattsonTutorialSC14.pptx
 
Use C++ and Intel® Threading Building Blocks (Intel® TBB) for Hardware Progra...
Use C++ and Intel® Threading Building Blocks (Intel® TBB) for Hardware Progra...Use C++ and Intel® Threading Building Blocks (Intel® TBB) for Hardware Progra...
Use C++ and Intel® Threading Building Blocks (Intel® TBB) for Hardware Progra...
 
Scripting Your Qt Application
Scripting Your Qt ApplicationScripting Your Qt Application
Scripting Your Qt Application
 
Open cl programming using python syntax
Open cl programming using python syntaxOpen cl programming using python syntax
Open cl programming using python syntax
 
OpenCL programming using Python syntax
OpenCL programming using Python syntax OpenCL programming using Python syntax
OpenCL programming using Python syntax
 
Qt for S60
Qt for S60Qt for S60
Qt for S60
 
OSDC 2016 - rkt and Kubernentes what's new with Container Runtimes and Orches...
OSDC 2016 - rkt and Kubernentes what's new with Container Runtimes and Orches...OSDC 2016 - rkt and Kubernentes what's new with Container Runtimes and Orches...
OSDC 2016 - rkt and Kubernentes what's new with Container Runtimes and Orches...
 
OSDC 2016 | rkt and Kubernetes: What’s new with Container Runtimes and Orches...
OSDC 2016 | rkt and Kubernetes: What’s new with Container Runtimes and Orches...OSDC 2016 | rkt and Kubernetes: What’s new with Container Runtimes and Orches...
OSDC 2016 | rkt and Kubernetes: What’s new with Container Runtimes and Orches...
 

More from Sergio Shevchenko

Gestione dell'economia nelle reti di Self Sovereign Identity con Algorand Sm...
Gestione dell'economia nelle reti di  Self Sovereign Identity con Algorand Sm...Gestione dell'economia nelle reti di  Self Sovereign Identity con Algorand Sm...
Gestione dell'economia nelle reti di Self Sovereign Identity con Algorand Sm...
Sergio Shevchenko
 
Kubernetes - from sketch to production
Kubernetes - from sketch to productionKubernetes - from sketch to production
Kubernetes - from sketch to production
Sergio Shevchenko
 
Meltdown & spectre
Meltdown & spectreMeltdown & spectre
Meltdown & spectre
Sergio Shevchenko
 
The Google file system
The Google file systemThe Google file system
The Google file system
Sergio Shevchenko
 
μ-Kernel Evolution
μ-Kernel Evolutionμ-Kernel Evolution
μ-Kernel Evolution
Sergio Shevchenko
 
Burrows-Wheeler transform for terabases
Burrows-Wheeler transform for terabasesBurrows-Wheeler transform for terabases
Burrows-Wheeler transform for terabases
Sergio Shevchenko
 
Presentazione CERT-CHECK
Presentazione CERT-CHECKPresentazione CERT-CHECK
Presentazione CERT-CHECK
Sergio Shevchenko
 
Design patterns: Creational patterns
Design patterns: Creational patternsDesign patterns: Creational patterns
Design patterns: Creational patterns
Sergio Shevchenko
 
Bitcoin and blockchain
Bitcoin and blockchainBitcoin and blockchain
Bitcoin and blockchain
Sergio Shevchenko
 
Qt Multiplatform development
Qt Multiplatform developmentQt Multiplatform development
Qt Multiplatform development
Sergio Shevchenko
 
Continuous Integration
Continuous IntegrationContinuous Integration
Continuous Integration
Sergio Shevchenko
 
Mobile Factor App
Mobile Factor AppMobile Factor App
Mobile Factor App
Sergio Shevchenko
 

More from Sergio Shevchenko (12)

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

Recently uploaded

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 

Recently uploaded (20)

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 

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