SlideShare a Scribd company logo
1 of 43
Download to read offline
August 8, 2011
PROGRAMMING WITH QT
   Introduction
   Container Classes and Strings
   Widgets and GUIs
   Resources
   Cross-platform C++ application development
    framework

   Effectively adds a few new C++ keywords (signal,
    slot, emit, etc)
   Provides facilities for:
    ◦   GUIs
    ◦   Internationalization
    ◦   XML serialization
    ◦   Media
    ◦   More
   “Write once, compile anywhere”




   GUIs look native (or pretty close to it) with just a
    recompile
   Commercial, GPL and LGPL licences
   European Space Agency
   Google Earth
   K Desktop Environment (KDE)
   Adobe Photoshop Album
   VLC Player
   Autodesk Maya
   …
C++ class library for writing GUIs,
database access, XML parsing, etc
Development tools (you generally don‟t
have to use them if you prefer your own)
qmake enables you to write one project file (with
 the extension “.pro”) and generate platform-
   specific project files from that as needed
#include <QApplication>
#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QLabel label("Hello world!");
    label.show();
    return a.exec();
}
#include <QApplication>    Headers named after
#include <QLabel>          the class they define


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QLabel label("Hello world!");
    label.show();
    return a.exec();
}
#include <QApplication>
    #include <QLabel>
All Qt apps have a
 QApplication or
       int main(int
QCoreApplication
                      argc, char *argv[])
       {
     instance
         QApplication a(argc, argv);

         QLabel label("Hello world!");
         label.show();
         return a.exec();
    }
#include <QApplication>
#include <QLabel>

int main(int argc, char *argv[])
                             The label widget
{                          becomes our window
    QApplication a(argc, argv); it has no
                            because
                                    parent

     QLabel label("Hello world!");
     label.show();
     return a.exec();
}
#include <QApplication>
#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QLabel label("Hello world!");
                        QApplication::exec()
    label.show();         runs the message
    return a.exec();    loop and exits when
                              the user closes the
}                                  window
PROGRAMMING WITH QT
   Introduction
   Container Classes and Strings
   Widgets and GUIs
   Resources
   QList
   QMap
   QStack
   QQueue
   QSet
   QVector
   Others…
QList is the most frequently used
   QList     container, and can be used for storing an
                         ordered list of items
   QMap
   QStack
   QQueue
   QSet
   QVector
   Others…
   QList
                QMap is frequently used when one needs to
   QMap      store key-value pairs and perform fast lookups
                             on the key value
   QStack
   QQueue
   QSet
   QVector
   Others…
   Grow as needed
    QList<QString> list;
    list << “Item1” << “Item2”;
    list.append(“Item3”);
    list.push_back(“Item4”);


   Iteration using various methods
    for (int i = 0; i < list.size(); i++)
        qDebug() << list[i];
   Grow as needed     Multiple methods for appending (<<,
                       append, push_back) are all equivalent.
    QList<QString> list;
    list << “Item1” << “Item2”;
    list.append(“Item3”);
    list.push_back(“Item4”);


   Iteration using various methods
    for (int i = 0; i < list.size(); i++)
        qDebug() << list[i];
   Implicitly shared
    QList<QString> list1;
    list1 << “Item1” << “Item2”;

    QList<QString> list2 = list1;


   Easy constructs for iteration: foreach!!!
    QList<QString> list;

    foreach (const QString &str, list)
         qDebug() << str;
   Implicitly shared
    QList<QString> list1;
    list1 << “Item1” << “Item2”;

    QList<QString> list2 = list1;


   Easy constructs for list1 is made foreach!!! or list2 isof
                        iteration: here. If list1
                      Only a quick, constant-time, shallow copy

    QList<QString>modified later, a deep copy will be made at that
                      list;
                         time. This is called Implicit Sharing and is a core
                                             Qt concept.
    foreach (const QString &str, list)
         qDebug() << str;
   QString!
   Built-in Unicode support
   Useful methods (trimmed(),
    split())

   Cheap copying (implicit sharing)


   Believe it or not, they can
    actually contain embedded „0‟
    characters…
   Concatenation and formatting
    QString first = “James”;
    QString last = “Kirk”;

    QString fullName = first + “ “ + last;

    QString fullName2 =
      QString(“%1 %2”).arg(first).arg(last);


   Translation
    QString translatedSend = tr(“Send”);
Both fullName and fullName2 end up
                                the same: “James Kirk”


   Concatenation and formatting
    QString first = “James”;
    QString last = “Kirk”;

    QString fullName = first + “ “ + last;

    QString fullName2 =
      QString(“%1 %2”).arg(first).arg(last);


   Translation
    QString translatedHello = tr(“Hello”);
   Concatenation and formatting
    QString first = “James”;
    QString last = “Kirk”;

                        If a translation for “Hello” is available at
    QString fullName = first + “ “ + last;
                                    runtime, tr(“Hello”) will return that
                                   translated string instead of “Hello”.
    QString fullName2 =
      QString(“%1 %2”).arg(first).arg(last);


   Translation
    QString translatedHello = tr(“Hello”);
   Splitting/joining on a delimiter character
    QString numbers = "1,2,54,23,7";
    QStringList nums = numbers.split(',');
    int sum = 0;
    foreach (QString num, numbersList)
         sum += num.toInt();



   Removing leading or trailing whitespace
    QString name = “ William Shatnern“;
    QString trimmedName = name.trimmed();
   Splitting/joining on a delimiter character
                            Also available: QString::toLong(),
                                   QString::toDouble(),
    QString numbers =             QString::toLower(), etc
                            "1,2,54,23,7";
    QStringList nums = numbers.split(',');
    int sum = 0;
    foreach (QString num, numbersList)
         sum += num.toInt();



   Removing leading or trailing whitespace
    QString name = “ William Shatnern“;
    QString trimmedName = name.trimmed();
   Splitting/joining on a delimiter character
    QString numbers = "1,2,54,23,7";
    QStringList nums = numbers.split(',');
    int sum = 0;
    foreach (QString num, numbersList)
         sum += num.toInt();
                          Afterwards, trimmedName equals
                                     “William Shatner”



   Removing leading or trailing whitespace
    QString name = “ William Shatnern“;
    QString trimmedName = name.trimmed();
PROGRAMMING WITH QT
   Introduction
   Container Classes and Strings
   Widgets and GUIs
   Resources
   Most objects inherit from
    QObject:
    ◦ QWidget
    ◦ QThread
    ◦ Etc..
   Together with the moc
    precompiler, enables many Qt
    features…
   Signals and slots
   Memory management (parents kill their children)
   Properties
   Introspection (QObject::className(),   QObject::inherits())




BUT:
   QObjects cannot be copied (they have “identity”)
   General-purpose way for Qt objects to notify
    one-another when something changes.
   Simple Observer pattern:

QPushButton *button = new
QPushButton(“About", this);

QObject::connect(
    button, SIGNAL(clicked()),
    qApp, SLOT(aboutQt()));
   General-purpose way for Qt objects to notify
    one-another when something changes.
   Simple Observer pattern:
                           When the button emits the “clicked()”
                             signal, the global application‟s
QPushButton *button =     new
                            “aboutQt()” slot will be executed.
QPushButton(“About", this);

QObject::connect(
    button, SIGNAL(clicked()),
    qApp, SLOT(aboutQt()));
   Parents destroy their children… A good thing!?

void showAbout()
{
     QDialog aboutDialog(NULL);
     QLabel* label = new QLabel(
         "About this..", &aboutDialog);
     aboutDialog.exec();
}

   No memory leak! aboutDialog‟s destructor deletes
    label.
   Parents destroy their children… A good thing!?

void showAbout()
{
     QDialog aboutDialog(NULL);
     QLabel* label = new QLabel(
         "About this..", &aboutDialog);
     aboutDialog.exec();     label is freed when its
                           parent, aboutDialog, goes
}                                 out of scope.


   No memory leak! aboutDialog‟s destructor deletes
    label.
   So what happens if the child is on the stack?


void showAbout()
{
     QDialog* about = new QDialog(NULL);
     QLabel label(
         "About this..", aboutDialog);
     about->exec();
     delete about;
}
   So what happens if the child is on the stack?
    ◦ Crash!! Qt tries to free the stack-allocated child!

void showAbout()
{
     QDialog* about = new QDialog(NULL);
     QLabel label(
         "About this..", aboutDialog);
     about->exec();
     delete about; // CRASH!
}
                                         about‟s destructor tries to
                                         free label, but label is on
                                           the stack, not the heap!
PROGRAMMING WITH QT
   Introduction
   Container Classes and Strings
   Widgets and GUIs
   Resources
Available as a free PDF from author at:

http://www.qtrac.eu/marksummerfield.html
http://www.ics.com/learning/icsnetwork/
http://doc.qt.nokia.com
A Brief Introduction to the Qt Application Framework

More Related Content

What's hot

What's hot (20)

Cross Platform Qt
Cross Platform QtCross Platform Qt
Cross Platform Qt
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
 
Qt for beginners part 1 overview and key concepts
Qt for beginners part 1   overview and key conceptsQt for beginners part 1   overview and key concepts
Qt for beginners part 1 overview and key concepts
 
QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong? QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong?
 
Qt 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
 
QVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentQVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI development
 
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
 
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
OpenGL Fixed Function to Shaders - Porting a fixed function application to “m...
 
Qt for Python
Qt for PythonQt for Python
Qt for Python
 
Lockless Producer Consumer Threads: Asynchronous Communications Made Easy
Lockless Producer Consumer Threads: Asynchronous Communications Made EasyLockless Producer Consumer Threads: Asynchronous Communications Made Easy
Lockless Producer Consumer Threads: Asynchronous Communications Made Easy
 
Treinamento Qt básico - aula II
Treinamento Qt básico - aula IITreinamento Qt básico - aula II
Treinamento Qt básico - aula II
 
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
 
The Future of Qt Widgets
The Future of Qt WidgetsThe Future of Qt Widgets
The Future of Qt Widgets
 
06 - Qt Communication
06 - Qt Communication06 - Qt Communication
06 - Qt Communication
 
Building the QML Run-time
Building the QML Run-timeBuilding the QML Run-time
Building the QML Run-time
 
Best Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IBest Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part I
 
Qt for beginners
Qt for beginnersQt for beginners
Qt for beginners
 
Translating Qt Applications
Translating Qt ApplicationsTranslating Qt Applications
Translating Qt Applications
 
State of the Art OpenGL and Qt
State of the Art OpenGL and QtState of the Art OpenGL and Qt
State of the Art OpenGL and Qt
 
Scripting Your Qt Application
Scripting Your Qt ApplicationScripting Your Qt Application
Scripting Your Qt Application
 

Viewers also liked

Qt Tutorial - Part 1
Qt Tutorial - Part 1Qt Tutorial - Part 1
Qt Tutorial - Part 1
rmitc
 
Cross platform development
Cross platform developmentCross platform development
Cross platform development
dftaiwo
 
Cross platform solutions for Mobile App Development
Cross platform solutions for Mobile App Development Cross platform solutions for Mobile App Development
Cross platform solutions for Mobile App Development
USAID CEED II Project Moldova
 
"How to Develop with Qt for Multiple Screen Resolutions and Increase Your Use...
"How to Develop with Qt for Multiple Screen Resolutions and Increase Your Use..."How to Develop with Qt for Multiple Screen Resolutions and Increase Your Use...
"How to Develop with Qt for Multiple Screen Resolutions and Increase Your Use...
FELGO SDK
 

Viewers also liked (20)

Introduction to Qt
Introduction to QtIntroduction to Qt
Introduction to Qt
 
Qt Technical Presentation
Qt Technical PresentationQt Technical Presentation
Qt Technical Presentation
 
Qt Tutorial - Part 1
Qt Tutorial - Part 1Qt Tutorial - Part 1
Qt Tutorial - Part 1
 
Qt in depth - presentation for Symbian expo 2009
Qt in depth - presentation for Symbian expo 2009Qt in depth - presentation for Symbian expo 2009
Qt in depth - presentation for Symbian expo 2009
 
A Quick Preview of What You'll See at Qt World Summit 2016
A Quick Preview of What You'll See at Qt World Summit 2016A Quick Preview of What You'll See at Qt World Summit 2016
A Quick Preview of What You'll See at Qt World Summit 2016
 
Qt Application Development on Harmattan
Qt Application Development on HarmattanQt Application Development on Harmattan
Qt Application Development on Harmattan
 
Cross platform development
Cross platform developmentCross platform development
Cross platform development
 
Cross platform solutions for Mobile App Development
Cross platform solutions for Mobile App Development Cross platform solutions for Mobile App Development
Cross platform solutions for Mobile App Development
 
The Mobile Market and Qt
The Mobile Market and QtThe Mobile Market and Qt
The Mobile Market and Qt
 
Building Cross-Platform Apps using Qt and Qyoto
Building Cross-Platform Apps using Qt and QyotoBuilding Cross-Platform Apps using Qt and Qyoto
Building Cross-Platform Apps using Qt and Qyoto
 
Company Credentials
Company CredentialsCompany Credentials
Company Credentials
 
Cross platform mobile app development tools review
Cross platform mobile app development tools reviewCross platform mobile app development tools review
Cross platform mobile app development tools review
 
Introduction to Qt programming
Introduction to Qt programmingIntroduction to Qt programming
Introduction to Qt programming
 
Qt Application Development
Qt Application DevelopmentQt Application Development
Qt Application Development
 
"How to Develop with Qt for Multiple Screen Resolutions and Increase Your Use...
"How to Develop with Qt for Multiple Screen Resolutions and Increase Your Use..."How to Develop with Qt for Multiple Screen Resolutions and Increase Your Use...
"How to Develop with Qt for Multiple Screen Resolutions and Increase Your Use...
 
Company Credentials - 2014
Company Credentials - 2014Company Credentials - 2014
Company Credentials - 2014
 
How to Make Your Qt App Look Native
How to Make Your Qt App Look NativeHow to Make Your Qt App Look Native
How to Make Your Qt App Look Native
 
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
 
Credentials Presentation
Credentials PresentationCredentials Presentation
Credentials Presentation
 
C++ vs C#
C++ vs C#C++ vs C#
C++ vs C#
 

Similar to A Brief Introduction to the Qt Application Framework

JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
Kiyotaka Oku
 
Code as data as code.
Code as data as code.Code as data as code.
Code as data as code.
Mike Fogus
 

Similar to A Brief Introduction to the Qt Application Framework (20)

Groovy
GroovyGroovy
Groovy
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Apache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheelApache Commons - Don\'t re-invent the wheel
Apache Commons - Don\'t re-invent the wheel
 
Pg py-and-squid-pypgday
Pg py-and-squid-pypgdayPg py-and-squid-pypgday
Pg py-and-squid-pypgday
 
Scala 3camp 2011
Scala   3camp 2011Scala   3camp 2011
Scala 3camp 2011
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88
 
Scala en
Scala enScala en
Scala en
 
Scala @ TomTom
Scala @ TomTomScala @ TomTom
Scala @ TomTom
 
Code as data as code.
Code as data as code.Code as data as code.
Code as data as code.
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
 
The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31The Ring programming language version 1.5 book - Part 8 of 31
The Ring programming language version 1.5 book - Part 8 of 31
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
04 - Qt Data
04 - Qt Data04 - Qt Data
04 - Qt Data
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 

A Brief Introduction to the Qt Application Framework

  • 2. PROGRAMMING WITH QT  Introduction  Container Classes and Strings  Widgets and GUIs  Resources
  • 3. Cross-platform C++ application development framework  Effectively adds a few new C++ keywords (signal, slot, emit, etc)  Provides facilities for: ◦ GUIs ◦ Internationalization ◦ XML serialization ◦ Media ◦ More
  • 4. “Write once, compile anywhere”  GUIs look native (or pretty close to it) with just a recompile  Commercial, GPL and LGPL licences
  • 5. European Space Agency  Google Earth  K Desktop Environment (KDE)  Adobe Photoshop Album  VLC Player  Autodesk Maya  …
  • 6.
  • 7. C++ class library for writing GUIs, database access, XML parsing, etc
  • 8. Development tools (you generally don‟t have to use them if you prefer your own)
  • 9. qmake enables you to write one project file (with the extension “.pro”) and generate platform- specific project files from that as needed
  • 10. #include <QApplication> #include <QLabel> int main(int argc, char *argv[]) { QApplication a(argc, argv); QLabel label("Hello world!"); label.show(); return a.exec(); }
  • 11. #include <QApplication> Headers named after #include <QLabel> the class they define int main(int argc, char *argv[]) { QApplication a(argc, argv); QLabel label("Hello world!"); label.show(); return a.exec(); }
  • 12. #include <QApplication> #include <QLabel> All Qt apps have a QApplication or int main(int QCoreApplication argc, char *argv[]) { instance QApplication a(argc, argv); QLabel label("Hello world!"); label.show(); return a.exec(); }
  • 13. #include <QApplication> #include <QLabel> int main(int argc, char *argv[]) The label widget { becomes our window QApplication a(argc, argv); it has no because parent QLabel label("Hello world!"); label.show(); return a.exec(); }
  • 14. #include <QApplication> #include <QLabel> int main(int argc, char *argv[]) { QApplication a(argc, argv); QLabel label("Hello world!"); QApplication::exec() label.show(); runs the message return a.exec(); loop and exits when the user closes the } window
  • 15. PROGRAMMING WITH QT  Introduction  Container Classes and Strings  Widgets and GUIs  Resources
  • 16. QList  QMap  QStack  QQueue  QSet  QVector  Others…
  • 17. QList is the most frequently used  QList container, and can be used for storing an ordered list of items  QMap  QStack  QQueue  QSet  QVector  Others…
  • 18. QList QMap is frequently used when one needs to  QMap store key-value pairs and perform fast lookups on the key value  QStack  QQueue  QSet  QVector  Others…
  • 19. Grow as needed QList<QString> list; list << “Item1” << “Item2”; list.append(“Item3”); list.push_back(“Item4”);  Iteration using various methods for (int i = 0; i < list.size(); i++) qDebug() << list[i];
  • 20. Grow as needed Multiple methods for appending (<<, append, push_back) are all equivalent. QList<QString> list; list << “Item1” << “Item2”; list.append(“Item3”); list.push_back(“Item4”);  Iteration using various methods for (int i = 0; i < list.size(); i++) qDebug() << list[i];
  • 21. Implicitly shared QList<QString> list1; list1 << “Item1” << “Item2”; QList<QString> list2 = list1;  Easy constructs for iteration: foreach!!! QList<QString> list; foreach (const QString &str, list) qDebug() << str;
  • 22. Implicitly shared QList<QString> list1; list1 << “Item1” << “Item2”; QList<QString> list2 = list1;  Easy constructs for list1 is made foreach!!! or list2 isof iteration: here. If list1 Only a quick, constant-time, shallow copy QList<QString>modified later, a deep copy will be made at that list; time. This is called Implicit Sharing and is a core Qt concept. foreach (const QString &str, list) qDebug() << str;
  • 23. QString!  Built-in Unicode support  Useful methods (trimmed(), split())  Cheap copying (implicit sharing)  Believe it or not, they can actually contain embedded „0‟ characters…
  • 24. Concatenation and formatting QString first = “James”; QString last = “Kirk”; QString fullName = first + “ “ + last; QString fullName2 = QString(“%1 %2”).arg(first).arg(last);  Translation QString translatedSend = tr(“Send”);
  • 25. Both fullName and fullName2 end up the same: “James Kirk”  Concatenation and formatting QString first = “James”; QString last = “Kirk”; QString fullName = first + “ “ + last; QString fullName2 = QString(“%1 %2”).arg(first).arg(last);  Translation QString translatedHello = tr(“Hello”);
  • 26. Concatenation and formatting QString first = “James”; QString last = “Kirk”; If a translation for “Hello” is available at QString fullName = first + “ “ + last; runtime, tr(“Hello”) will return that translated string instead of “Hello”. QString fullName2 = QString(“%1 %2”).arg(first).arg(last);  Translation QString translatedHello = tr(“Hello”);
  • 27. Splitting/joining on a delimiter character QString numbers = "1,2,54,23,7"; QStringList nums = numbers.split(','); int sum = 0; foreach (QString num, numbersList) sum += num.toInt();  Removing leading or trailing whitespace QString name = “ William Shatnern“; QString trimmedName = name.trimmed();
  • 28. Splitting/joining on a delimiter character Also available: QString::toLong(), QString::toDouble(), QString numbers = QString::toLower(), etc "1,2,54,23,7"; QStringList nums = numbers.split(','); int sum = 0; foreach (QString num, numbersList) sum += num.toInt();  Removing leading or trailing whitespace QString name = “ William Shatnern“; QString trimmedName = name.trimmed();
  • 29. Splitting/joining on a delimiter character QString numbers = "1,2,54,23,7"; QStringList nums = numbers.split(','); int sum = 0; foreach (QString num, numbersList) sum += num.toInt(); Afterwards, trimmedName equals “William Shatner”  Removing leading or trailing whitespace QString name = “ William Shatnern“; QString trimmedName = name.trimmed();
  • 30. PROGRAMMING WITH QT  Introduction  Container Classes and Strings  Widgets and GUIs  Resources
  • 31. Most objects inherit from QObject: ◦ QWidget ◦ QThread ◦ Etc..  Together with the moc precompiler, enables many Qt features…
  • 32. Signals and slots  Memory management (parents kill their children)  Properties  Introspection (QObject::className(), QObject::inherits()) BUT:  QObjects cannot be copied (they have “identity”)
  • 33. General-purpose way for Qt objects to notify one-another when something changes.  Simple Observer pattern: QPushButton *button = new QPushButton(“About", this); QObject::connect( button, SIGNAL(clicked()), qApp, SLOT(aboutQt()));
  • 34. General-purpose way for Qt objects to notify one-another when something changes.  Simple Observer pattern: When the button emits the “clicked()” signal, the global application‟s QPushButton *button = new “aboutQt()” slot will be executed. QPushButton(“About", this); QObject::connect( button, SIGNAL(clicked()), qApp, SLOT(aboutQt()));
  • 35. Parents destroy their children… A good thing!? void showAbout() { QDialog aboutDialog(NULL); QLabel* label = new QLabel( "About this..", &aboutDialog); aboutDialog.exec(); }  No memory leak! aboutDialog‟s destructor deletes label.
  • 36. Parents destroy their children… A good thing!? void showAbout() { QDialog aboutDialog(NULL); QLabel* label = new QLabel( "About this..", &aboutDialog); aboutDialog.exec(); label is freed when its parent, aboutDialog, goes } out of scope.  No memory leak! aboutDialog‟s destructor deletes label.
  • 37. So what happens if the child is on the stack? void showAbout() { QDialog* about = new QDialog(NULL); QLabel label( "About this..", aboutDialog); about->exec(); delete about; }
  • 38. So what happens if the child is on the stack? ◦ Crash!! Qt tries to free the stack-allocated child! void showAbout() { QDialog* about = new QDialog(NULL); QLabel label( "About this..", aboutDialog); about->exec(); delete about; // CRASH! } about‟s destructor tries to free label, but label is on the stack, not the heap!
  • 39. PROGRAMMING WITH QT  Introduction  Container Classes and Strings  Widgets and GUIs  Resources
  • 40. Available as a free PDF from author at: http://www.qtrac.eu/marksummerfield.html