qt for beginners part 1 overview and key concepts
TRANSCRIPT
Qt For Beginners - Part 1Overview and Key Concepts
Watch the Full Video here: http://bit.ly/qt-for-beginners
Jeff Tranter, Qt Consulting ManagerIntegrated Computer SolutionsVisit 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
AgendaHistory of QtFeatures of QtC++ RefresherHello World ApplicationCore ClassesObjects and Object CommunicationA Look AheadQ&A
2
AgendaHistory of QtFeatures of QtC++ RefresherHello World ApplicationCore ClassesObjects and Object CommunicationA Look AheadQ&A
3
History of QtTrolltech founded in 1994 (up to Qt 4.3)Acquired by Nokia in 2008 (Qt 4.4 - 4.7)Qt Development Frameworks founded in 2009Under open governanceDigia 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
About ICSFounded in 1987Trolltech/Nokia/Digia's Qt Training Partner since 2002Provider of integrated custom software development, training,
and user experience (UX) designFor embedded, touchscreen, mobile and desktop
applicationsHeadquartered in Bedford, MassachusettsOffices/staff in USA, Canada, Europe120+ employees worldwide
5
See http://www.ics.com/
Qt Is Used EverywhereSoftware: KDE, Qt Creator, Google Earth, Skype (for Linux),
VirtualBox, Spotify, VLC Media Player, AutoDesk Maya, AutoDesk MotionBuilder, 3D Studio Max
Games: EA Origin SystemMobile 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 RTPorted to Real Time Operating Systems (QNX, VXWorks,
Green Hills Integrity)Robots: Suitable BeamCompanies: Disney Animation StudiosSee Software that uses Qt or
6
See http://qt-apps.org
AgendaHistory of QtFeatures of QtC++ RefresherHello World ApplicationCore ClassesObjects and Object CommunicationA Look AheadQ&A
7
Why Qt?Write code once to target multiple platforms (“Write Once,
Compile Anywhere”)Produce compact, high-performance applicationsFocus on innovation, not infrastructure codingChoose the license that fits you: commercial, LGPL or GPLCount on professional services, support and trainingTake part in an active Qt ecosystem
8
Qt Architecture
9
The Qt Quick World
10
The OpenGL World
11
The Widget World
12
The Graphics View World
13
Using the Right Qt for YouDual-Licensing Model
Community/Open Source:GPL or LGPL license options
Commercial:Qt For Device CreationQt For Application Development
Contact your legal team/advisor to interpret and comply with licensing requirements
14
Giving Back - Contributing to QtQt developed by a community under Open GovernanceAnyone can report bugs, request enhancements, contribute
codeNeed to accept the Contribution AgreementAgreements for corporate and personal contributors
15
AgendaHistory of QtFeatures of QtC++ RefresherHello World ApplicationCore ClassesObjects and Object CommunicationA Look AheadQ&A
16
How Much C++ Do You Need To Know?
Objects and classesDeclaring a class, inheritance, calling member functions
etc.Polymorphism
Virtual methodsOperator overloadingTemplates
Limited to the container and concurrent classesNo...
...RTTI
...Sophisticated templates
...Exceptions
...C++11/C++14
17
AgendaHistory of QtFeatures of QtC++ RefresherHello World ApplicationCore ClassesObjects and Object CommunicationA Look AheadQ&A
18
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
// Simple QML exampleimport 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
Using qmakeqmake tool
Generates a Makefile or Visual Studio projectBuild project using qmakecd helloworldqmake helloworld.pro # creates Makefilemake # compiles and links application./helloworld # executes application
Tip: qmake -projectCreates 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
Example helloworld.proTEMPLATE = app # app is default - could be 'subdirs' or 'lib'TARGET = hello # executable or library nameQT += widgets # Qt modules to useCONFIG += debug # release is defaultSOURCES += main.cpp # source files
22
Qt AssistantStandalone help browserReference Documentation
All classes documentedContains tons of examples
Collection of Howtos and Overviews
23
Qt Creator IDE
24
Finding the AnswersDocumentation in Qt Assistant or Qt CreatorQt's examples: $QTSRC/examplesQt Project: http://www.qt.io/developers/Qt Centre Forum: http://www.qtcentre.org/Mailing lists: http://lists.qt-project.orgIRC: irc.freenode.org channel: #qtUse the source! Qt's source code is easy to
read, and can answer questions the reference docs cannot answer.
25
Modules
26
Qt ModulesQt 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 documentationEnable Qt Modules in qmake .pro file:QT += widgets xml sql dbus multimedia network
Default: qmake projects use QtCore and QtGuiQWidget based projects require QtWidgets moduleQtQuick2 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.
27
More Include Files
AgendaHistory of QtFeatures of QtC++ RefresherHello World ApplicationCore ClassesObjects and Object CommunicationA Look AheadQ&A
28
Text Processing with QStringStrings can be created in a number of waysConversion 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-8From char pointer with translations:QString text = tr("Hello Qt");
29
Text Processing with QStringQString str = str1 + str2;
fileName += ".txt";
simplified() // removes duplicate whitespaceleft(), mid(), right() // part of a stringleftJustified(), rightJustified() // padded versionlength(), endsWith(), startsWith()contains(), count(), indexOf(), lastIndexOf()toInt(), toDouble(), toLatin1(), toUtf8(), toLocal8Bit()
30
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
Text Processing With QStringListQString::split(), QStringList::join()
QStringList::replaceInStrings()
QStringList::filter()
32
Container ClassesGeneral purpose template-based container classesQList<QString> - Sequence Container
Other: QLinkedList, QVector, QStack, QQueueQMap<int, QString> - Associative Container
Other: QHash, QSet, QMultiMap, QMultiHashQt's Container Classes compared to STL:
Lighter, safer, and easier to use than STL containersIf you prefer STL, feel free to... well.. whatever :-)
Methods exist that convert between Qt and STLE.g. you need to pass std::list to a Qt method
33
Using ContainersUsing QListQList<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 QMapQMap<QString, int> map;map["Norway"] = 5; map["Italy"] = 48;
int val = map["France"]; // inserts key if not existsif (map.contains("Norway")) {int val2 = map.value("Norway"); // recommended lookup}
34
Algorithm ComplexityConcern: How fast a function is as a container growsSequential 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)
IteratorsAllow reading a container's content sequentiallyJava-style iterators: simple and easy to use
QListIterator<...> for readQMutableListIterator<...> for read-write
STL-style iterators slightly more efficientQList::const_iterator for readQList::iterator for read-write
Same works for QSet, QMap, QHash, ...
36
Iterators Java StyleExample QList iterator
QList<QString> list;list << "A" << "B" << "C" << "D";QListIterator<QString> it(list);
Forward iterationwhile (it.hasNext()) {
qDebug() << it.next(); // A B C D}
Backward iterationit.toBack(); // position after the last itemwhile (it.hasPrevious()) {
qDebug() << it.previous(); // D C B A}
37
STL-Style IteratorsExample QList iteratorQList<QString> list;list << "A" << "B" << "C" << "D";QList<QString>::iterator i;
Forward mutable iterationfor (i = list.begin(); i != list.end(); ++i) { *i = (*i).toLower();}
Backward mutable iterationi = list.end();while (i != list.begin()) {
--i;*i = (*i).toLower();
}QList<QString>::const_iterator for read-only
38
The foreach KeywordIt is a macro, feels like a keyword
foreach (const QString &str, list) {if (str.isEmpty())
break;qDebug() << str;}
break and continue as normalModifying the container while iterating
Results in container being copiedIteration continues in unmodified version
Not possible to modify itemIterator 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
AgendaHistory of QtFeatures of QtC++ RefresherHello World ApplicationCore ClassesObjects and Object CommunicationA Look AheadQ&A
40
Implicit Sharing and ContainersImplicit SharingIf 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 blockShared data block = reference counter and actual data
Assignment is a shallow copyChanging results into deep copy (detach)QList<int> list1, list2;list1 << 1 << 2;
list2 = list1; // shallow-copy: shares data with list1list2 << 3; // deep-copy: change triggers detach
41
Qt's C++ Object Model - QObjectQObject is the heart of Qt's object modelInclude these features:
Memory managementObject propertiesIntrospectionSignals and SlotsEvent handling
QObject has no visual representation
42
Object TreesQObjects organize themselves in object trees
Based on parent-child relationshipQObject(QObject *parent = 0)
Parent adds object to list of childrenParent owns children
Construction/DestructionTrees can be constructed in any orderTrees can be destroyed in any order
If object has a parent: object is first removed from the parentIf object has children: deletes each child firstNo object is deleted twice
Note: Parent-child relationship is not inheritance!
43
Creating Objects - General Guidelines
On Heap - QObject with parentQTimer *timer = new QTimer(this);
On Stack - QObject without parent:QFile, usually local to a functionQApplication (local to main())QSettings, lightweight to create, local to a function
On Stack - value typesQString, QList, QHash, QMap, QColor, QImage, QPixmap, QVariant
Stack or Heap - QDialog - depending on lifetime
44
QVariantQVariant
Union for common Qt "value types" (copyable, assignable)Supports implicit sharing (fast copying)Supports user types
A generic data objectUse 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
QVariantFor QtCore typesQVariant variant(42);int value = variant.toInt(); // read back as integerQString text = variant.toString(); // read back as stringqDebug() << variant.typeName(); // int
For non-core and custom types:QVariant variant = QVariant::fromValue(QColor(Qt::red));QColor color = variant.value<QColor>(); // read backqDebug() << variant.typeName(); // "QColor"
46
Q_OBJECT - flag for MOCMeta Object Compiler (MOC)Q_OBJECT
Enhances QObject with QMetaObject informationRequired for Q_PROPERTY, QObject::metaObject(), qobject_cast, etc.Required for signals, slots, and QMetaObject::invokeMethod()
moc creates generates the QMetaObject code for each Q_OBJECTmoc -o moc_myclass.cpp myclass.hc++ -c myclass.cppc++ -c moc_myclass.cppc++ -o myapp moc_myclass.o myclass.o
Makefiles generated by qmake take care of making the Q_OBJECT-marked classes automatically for you.
47
PropertiesQt Quick exampleimport QtQuick 2.0Rectangle {
width: 400; height: 400color: "lightblue"
}
Generic property access:QObject *root = view->rootObject();if (root != NULL) {
QString color = root->property("color").toString();int width = root->property("width").toInt();
}
48
PropertiesQ_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_PROPERTYStored as a dynamic property in QObject not in QMetaObjectHence not accessible from Qt Quick
Note:Q_OBJECT macro is required for Q_PROPERTY to work
49
Providing Properties from QObject
class Customer : public QObject{
Q_OBJECTQ_PROPERTY(QString custId READ getId WRITE setId NOTIFY
idChanged);
public:QString getId() const;void setId(const QString& id);
signals:void idChanged();
...};
50
CallbacksGeneral Problem: How do you get from "the user clicks a button" to your business logic?
Possible solutionsCallbacks
Based on function pointersTraditionally not type-safe
Observer Pattern (Listener)Based on interface classesNeeds listener registrationMany interface classes
Qt usesSignals and slots for high-level (semantic) callbacksVirtual methods for low-level (syntactic) events.
51
// Slider.qmlRectangle { id: container ... signal valueChanged(var v) ... MouseArea { anchors.fill: parent ... onPositionChanged: { currentValue = factor * slide.x container.valueChanged(currentValue) } } ... ...
Signal Emitted
Connecting Signals to Slots
52
// Spinner.qmlsignal valueChanged(var v)...function setValue(newValue) { if (newValue !== view.currentIndex) { view.currentIndex = newValue }}...
Slot/Method Implemented
53
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
54
Connections { target: slider onValueChanged: { picker.setValue(slider.value) } }
In QML Code: Signal/Slot Connection Established
Connecting Signals to Slots
55
Connection VariantsUsing 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
Custom SlotsFile: myclass.hclass MyClass : public QObject
{Q_OBJECT // marker for moc// …public slots:void setValue(int value); // a custom slot};
File: myclass.cppvoid MyClass::setValue(int value) {
// slot implementation}
57
Custom SignalsFile: myclass.hclass 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 signalemit valueChanged(value);
58
Variations of Signal/Slot Connections
Signal to Signal connectionconnect(bt, SIGNAL(clicked()), this, SIGNAL(okSignal()));
Not allowed to name parametersconnect(m_slider,SIGNAL(valueChanged(int value)),
this, SLOT(setValue(int newValue)))
59
Event ProcessingQt is an event-driven UI toolkitStarting Event Loops
QApplication::exec() - main event loopQDialog::exec() - modal dialogsQThread::exec() - other threads
Generating EventsQInputEvent from GUI: keyboard, mouse, touch,
hover, etc.By Qt itself (e.g. QTimerEvent)
Dispatching Eventsby QApplication to receiver: QObject
Key events sent to item/widget with focusMouse events sent to item/widget under cursor
60
More Event ProcessingProcessing Events
QApplication::processEvents()Keeps the GUI responsive during long calculations
Sending EventsQApplication::sendEvent() block while event is processedQApplication::postEvent() asynchronous, queued in event loop
Handling EventsOverride QObject event handler methodsAllows you to change default behavior of Qt Widgets/Objects
Filtering Events1. Extend QObject and define a custom event filter class2. Override QObject::eventFilter()3. Instantiate it, and pass it to QObject::installEventFilter()
61
AgendaHistory of QtFeatures of QtC++ RefresherHello World ApplicationCore ClassesObjects and Object CommunicationA Look AheadQ&A
62
A Look AheadQt 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
Widgets versus QMLWidgets:Originally designed for desktopMouse and keyboard navigationCan be used for embedded, incl. touchscreenStableQt Quick/QML:Primarily designed for mobile/embeddedTouchscreen navigationDeclarative programming language QML backed by
JavaScriptCan be used for desktop too!
64
Thanks For Attending!Slides will be published on SlideShare at
http://www.slideshare.net/ICSinc/presentationsCan now take some questions
65
AgendaHistory of QtFeatures of QtC++ RefresherHello World ApplicationCore ClassesObjects and Object CommunicationA Look AheadQ&A
66