Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Qt for beginners part 1 overview and key concepts
1. Qt For Beginners - Part 1
Overview and Key Concepts
Watch the Full Video here: http://bit.ly/qt-for-
beginners
Jeff Tranter, Qt Consulting Manager
Integrated Computer Solutions
Visit us at http://www.ics.com
Copyright 2016, 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.
1
2. Agenda
History of Qt
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
2
3. Agenda
History of Qt
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
3
4. History of Qt
Trolltech founded in 1994 (up to Qt 4.3)
Acquired by Nokia in 2008 (Qt 4.4 - 4.7)
Qt Development Frameworks founded in 2009
Under open governance
Digia acquired Qt division in 2012 (Qt 4.8+)
The Qt Company, subsidiary of Digia, founded
in 2014
4
See http://www.qt.io
See http://qt-project.org
5. About ICS
Founded in 1987
Trolltech/Nokia/Digia's Qt Training Partner since 2002
Provider of integrated custom software development, training,
and user experience (UX) design
For embedded, touchscreen, mobile and desktop
applications
Headquartered in Bedford, Massachusetts
Offices/staff in USA, Canada, Europe
120+ employees worldwide
5
See http://www.ics.com/
6. Qt Is Used Everywhere
Software: KDE, Qt Creator, Google Earth, Skype (for Linux),
VirtualBox, Spotify, VLC Media Player, AutoDesk Maya,
AutoDesk MotionBuilder, 3D Studio Max
Games: EA Origin System
Mobile UX: Sharp Zaurus (Qtopia), Nokia N8 (Symbian),
Nokia N9 (Meego), Blackberry 10 Cascades, Jolla
(Meego), Ubuntu Touch, Kobo (e-reader)
Ported to Mobile Platforms: Android, iOS, Tizen, Windows RT
Ported to Real Time Operating Systems (QNX, VXWorks,
Green Hills Integrity)
Robots: Suitable Beam
Companies: Disney Animation Studios
See Software that uses Qt or
6
See http://qt-apps.org
7. Agenda
History of Qt
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
7
8. Why Qt?
Write code once to target multiple platforms (“Write Once,
Compile Anywhere”)
Produce compact, high-performance applications
Focus on innovation, not infrastructure coding
Choose the license that fits you: commercial, LGPL or GPL
Count on professional services, support and training
Take part in an active Qt ecosystem
8
14. Using the Right Qt for You
Dual-Licensing Model
Community/Open Source:
GPL or LGPL license options
Commercial:
Qt For Device Creation
Qt For Application Development
Contact your legal team/advisor to interpret and
comply with licensing requirements
14
15. Giving Back - Contributing to Qt
Qt developed by a community under Open Governance
Anyone can report bugs, request enhancements, contribute
code
Need to accept the Contribution Agreement
Agreements for corporate and personal contributors
15
16. Agenda
History of Qt
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
16
17. 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
17
18. Agenda
History of Qt
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
18
19. Widgets - Hello World Example
// Simple C++ widgets example
#include <QApplication>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QPushButton hello("Hello, world!");
app.connect(&hello, SIGNAL(clicked()), &app,
SLOT(quit()));
hello.show();
return app.exec();
}
19
20. // 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()
}
}
}
QML - Hello World Example
20
21. Using qmake
qmake tool
Generates a Makefile or Visual Studio project
Build project using qmake
cd helloworld
qmake helloworld.pro # creates Makefile
make # compiles and
links application
./helloworld # 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
21
22. Example helloworld.pro
TEMPLATE = app # app is default - could be 'subdirs' or 'lib'
TARGET = hello # executable or library name
QT += widgets # Qt modules to use
CONFIG += debug # release is default
SOURCES += main.cpp # source files
22
23. Qt Assistant
Standalone help browser
Reference Documentation
All classes documented
Contains tons of examples
Collection of Howtos and Overviews
23
25. Finding the Answers
Documentation in Qt Assistant or Qt Creator
Qt's examples: $QTSRC/examples
Qt Project: http://www.qt.io/developers/
Qt Centre Forum: http://www.qtcentre.org/
Mailing lists: http://lists.qt-project.org
IRC: irc.freenode.org channel: #qt
Use the source! Qt's source code is easy to
read, and can answer questions the reference
docs cannot answer.
25
26. Modules
26
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
27. 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.
27
More Include Files
28. Agenda
History of Qt
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
28
29. 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");
29
30. 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()
30
31. 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.
31
32. Text Processing With QStringList
QString::split(), QStringList::join()
QStringList::replaceInStrings()
QStringList::filter()
32
33. 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
33
34. 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
}
34
35. Algorithm Complexity
Concern: How fast a function is as a container grows
Sequential Container
Associative Container
All complexities are amortized
35
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)
36. 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, ...
36
37. 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
}
37
38. 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
38
39. 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.
39
40. Agenda
History of Qt
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
40
41. 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
41
42. 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
Event handling
QObject has no visual representation
42
43. 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!
43
44. 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
44
45. 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);
…
};
45
46. 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"
46
47. Q_OBJECT - flag for MOC
Meta Object Compiler (MOC)
Q_OBJECT
Enhances QObject with QMetaObject information
Required for Q_PROPERTY, QObject::metaObject(), qobject_cast, etc.
Required for signals, slots, and QMetaObject::invokeMethod()
moc creates generates the QMetaObject code for each
Q_OBJECT
moc -o moc_myclass.cpp myclass.h
c++ -c myclass.cpp
c++ -c moc_myclass.cpp
c++ -o myapp moc_myclass.o myclass.o
Makefiles generated by qmake take care of making the
Q_OBJECT-marked classes automatically for you.
47
48. Properties
Qt Quick example
import QtQuick 2.0
Rectangle {
width: 400; height: 400
color: "lightblue"
}
Generic property access:
QObject *root = view->rootObject();
if (root != NULL) {
QString color = root->property("color").toString();
int width = root->property("width").toInt();
}
48
49. Properties
Q_PROPERTY is a macro:
Q_PROPERTY(type name READ getFunction
[WRITE setFunction] [RESET resetFunction]
[NOTIFY notifySignal] [DESIGNABLE bool]
[SCRIPTABLE bool] [STORED bool])
Property access methods:
QVariant property(const char* name) const;
void setProperty(const char* name,const QVariant& value);
If setProperty() is used to set a property name that has not
been declared as a Q_PROPERTY
Stored as a dynamic property in QObject not in QMetaObject
Hence not accessible from Qt Quick
Note:
Q_OBJECT macro is required for Q_PROPERTY to work
49
51. 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.
51
56. 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) {...});
56
57. 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
}
57
58. 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);
58
59. 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)))
59
60. Event Processing
Qt is an event-driven UI toolkit
Starting Event Loops
QApplication::exec() - main event loop
QDialog::exec() - modal dialogs
QThread::exec()- other threads
Generating Events
QInputEvent from GUI: keyboard, mouse, touch,
hover, etc.
By Qt itself (e.g. QTimerEvent)
Dispatching Events
by QApplicationto receiver: QObject
Key events sent to item/widget with focus
Mouse events sent to item/widget under cursor
60
61. More Event Processing
Processing Events
QApplication::processEvents()
Keeps the GUI responsive during long calculations
Sending Events
QApplication::sendEvent() block while event is processed
QApplication::postEvent() asynchronous, queued in event loop
Handling Events
Override QObject event handler methods
Allows you to change default behavior of Qt Widgets/Objects
Filtering Events
1. Extend QObject and define a custom event filter class
2. Override QObject::eventFilter()
3. Instantiate it, and pass it to QObject::installEventFilter()
61
62. Agenda
History of Qt
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
62
63. A Look Ahead
Qt For Beginners Part 2 - Widgets (May 5)
Qt For Beginners Part 3 - QML and Qt Quick (May 19)
Qt For Beginners Part 4 - Doing More (June 9)
63
64. 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!
64
65. Thanks For Attending!
Slides will be published on SlideShare at
http://www.slideshare.net/ICSinc/presentations
Can now take some questions
65
66. Agenda
History of Qt
Features of Qt
C++ Refresher
Hello World Application
Core Classes
Objects and Object Communication
A Look Ahead
Q&A
66