SlideShare a Scribd company logo
Basics of Qt



Andreas Jakl
Senior Technical Consultant
Forum Nokia

                              20 September, 2010
                                          v3.0.0
Contents
  – Signals and Slots
  – Widgets, Layouts and Styles
  – Meta-Objects and Memory Management
Signals and Slots
Callbacks?
• Traditional callbacks
    – Callback is pointer to a function
    – Called when appropriate (event notification, ...)
• Problems
    – Not type-safe: does the caller use the correct arguments?
    – Less generic: callback strongly coupled to processing function.
      Processing function must know which callback to call.
Signals & Slots
• Signal
    – Emitted when a particular event occurs (e.g., clicked())
    – Qt widgets: predefined signals
    – Also create your own signals
• Slot
    – Function called in response to a signal
    – Qt widgets: predefined slots (e.g., quit())
    – Also create your own slots
• Connection signals  slots established by developer,
  handled by Qt framework
Connections
                                                                                              Signals
    Signals     connect( Object1, signal1, Object2, slot1 )                                     signal1
                connect( Object1, signal1, Object2, slot2 )
      signal1
      signal2                                                                                    Slots




                                                                                                          connect( Object2, signal1, Object4, slot3 )
                connect( Object1, signal2, Object4, slot1 )
                                                                                                  slot1
    Slots                                                                                         slot2
     slot1
     slot2
     slot3


                  Signals
                    signal1                                                             Signals

                  Slots
                   slot1                                                                Slots
                                                                                         slot1
                                                                                         slot2
                                                                                         slot3
                                          connect( Object3, signal1, Object4, slot3 )
Find Signals and Slots
• Look up signals and slots of Qt
  classes in the documentation
Example: Multiple Signal-Slot Connections
                          Restore window to
                          normal size


                          Show an about dialog
                          and then maximize the
                          window



                          Exit the application
Example: Connections                   QApplication
                                          app

                                     Signals
                       QPushButton
                          but1
                     Signals
                                     Slots
                      clicked
                                      aboutQt()
                     Slots            quit()
       QPushButton
          but2
     Signals
      clicked                            QWidget
                                          win
     Slots
                                     Signals
                       QPushButton
                          but3        clicked
                     Signals
                      clicked         Slots
                                     showNormal()
                     Slots           showMaximized()
#include <QApplication>
#include <QPushButton>
#include <QVBoxLayout>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QWidget* win = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(win);

    QPushButton* but1 = new QPushButton("Normal size");
    but1->resize(150, 30);
    layout->addWidget(but1);

    QPushButton* but2 = new QPushButton("About and Maximize");
    but2->resize(150, 30);
    layout->addWidget(but2);

    QPushButton* but3 = new QPushButton("Exit");
    but3->resize(150, 30);
    layout->addWidget(but3);
                                                                                 aboutQt() and
    QObject::connect(but1,   SIGNAL(clicked()),   win, SLOT(showNormal()));      showMaximized()
    QObject::connect(but2,   SIGNAL(clicked()),   &app, SLOT(aboutQt()));
                                                                                 executed one after
    QObject::connect(but2,   SIGNAL(clicked()),   win, SLOT(showMaximized()));
    QObject::connect(but3,   SIGNAL(clicked()),   &app, SLOT(quit()));           another
    win->show();

    return app.exec();
}
Layouts
    Most common layouts
     –   QHBoxLayout: horizontal, from left to right
         (right to left for some cultures)
     –   QVBoxLayout: vertical, top to bottom
     –   QGridLayout: grid
     –   QFormLayout: manages input widgets and associated labels
     –   QStackedLayout: widgets on top of each other, switch index
         of currently visible widget
•   Layouts can be nested
     –   Add new layout to existing layout like a widget:
         l->addLayout(l2)
Styles                                       Style can be set using
                                          -style <name> command-
                                                  line option.

                                             Windows XP/Vista/7 and
       plastique   cleanlooks
                                            Macintosh styles are only
                                          available on native platforms
                                           (relies on platform’s theme
                                                     engines)

                                           It’s possible to create own
   windowsvista    windowsxp    windows               styles.




     macintosh         motif        cde
Example 2
• Synchronize two widgets
   – Changing the value in one automatically changes the other




                  Signals                   Signals
                  valueChanged(int)         valueChanged(int)

                   Slots                     Slots
                  setValue(int)             setValue(int)
#include   <QApplication>
#include   <QHBoxLayout>
#include   <QSpinBox>
#include   <QSlider>

int main(int argc, char *argv[]) {
   QApplication app(argc, argv);
   QWidget* win = new QWidget();
   win->setWindowTitle("Synchronized Widgets");

    QHBoxLayout* layout = new QHBoxLayout(win);

    QSpinBox* spin = new QSpinBox();
    spin->setMinimum(0);
    spin->setMaximum(100);
    layout->addWidget(spin);

    QSlider* slider = new QSlider(Qt::Horizontal);
    slider->setMinimum(0);
    slider->setMaximum(100);
    layout->addWidget(slider);

    QObject::connect( spin, SIGNAL( valueChanged(int) ),
                      slider, SLOT( setValue(int) ) );
    QObject::connect( slider, SIGNAL( valueChanged(int) ),
                      spin, SLOT( setValue(int) ) );

    spin->setValue(50);

    win->show();
    return app.exec();
}
Signal Parameters
 Transmit additional information
  QObject::connect( spin, SIGNAL( valueChanged(int) ),
                       slider, SLOT( setValue(int) ) );

  – Specify type of argument(s)
  – Signal has to be compatible to the slot
     (same parameter type(s))
Signal Parameters
•   Types not automatically casted by Qt
     – Signals & slots with exactly the specified parameters have to exist
     – Otherwise: no compilation error / warning
     – But: warning at runtime when executing connect():
          QObject::connect: Incompatible sender/receiver arguments
          QSpinBox::valueChanged(QString) --> QSlider::setValue(int)

•   → Signals & slots are type safe
     – No connection if either sender or receiver doesn’t exist
     – Or if signatures of signal and slot do not match
•   connect() returns boolean value indicating success
Signal & Slot Processing
   setValue(50) is called in the source code




              QSpinBox emits valueChanged(int) signal with int argument of 50

                                signal  slot
                          Argument is passed to QSlider’s setValue(int) slot, sets slider value to 50




                          QSlider emits valueChanged(int) signal with int argument of 50

                                          signal  slot
                                 Argument is passed to QSpinbox’s setValue(int) slot, but value is already set to 50.
                                  doesn’t emit any further signal to prevent infinite recursion.
Signals & Slots
• Type safe
   – Signal signature must match signature of receiving slot
   – (Slot might also have shorter signature and ignore rest of the arguments)
• Loosely coupled
   – Emitter doesn’t know or care which slots receive signal
   – Information encapsulation
• Integrated, independent components
   – Slots are normal C++ member functions
   – Don’t know if signals are connected to them
Manual Signal & Slots
counter.h                                    counter.cpp
 #ifndef COUNTER_H                            #include "counter.h"
 #define COUNTER_H
                                              void Counter::setValue(int value)
 #include <QObject>                           {
                                                  if (value != m_value)
 class Counter : public QObject                   {
 {                                                    m_value = value;
     Q_OBJECT                                         emit valueChanged(value);
                                                  }
 public:                                      }
     Counter() { m_value = 0; }
     int value() const { return m_value; }

 public slots:
     void setValue(int value);

 signals:                                                  Own Class that represents
     void valueChanged(int newValue);                       behaviour of Example 2
 private:
     int m_value;
 };

 #endif // COUNTER_H
main.cpp
#include <QtGui/QApplication>
#include <QMessageBox>
#include "counter.h"

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

    Counter a, b;
    QObject::connect(&a, SIGNAL(valueChanged(int)),
                     &b, SLOT(setValue(int)));

    a.setValue(12);    // a.value() == 12, b.value() == 12

    QMessageBox msgBox;
    msgBox.setText("a = " + QString::number(a.value()) + ", b = " + QString::number(b.value()));
    msgBox.exec();

    b.setValue(48);    // a.value() == 12, b.value() == 48

    msgBox.setText("a = " + QString::number(a.value()) + ", b = " + QString::number(b.value()));
    msgBox.exec();

    app.quit();
    return 1;
}
Meta Objects
Qt Meta-Object System
• C++ extended with meta-object mechanism:
  Introspection
   – Obtain meta-information about QObject
      subclasses at runtime
   – Used for: getting list of signals & slots,
      properties and text translation
QObject
• Meta information not supported by standard C++
    – QObject class
        •   Base class for objects that use meta-object system     #include <QObject>
                                                                   class Counter : public QObject
    – Q_OBJECT macro                                               {
        •   Enables meta-object features                               Q_OBJECT
        •   Without ;                                              [...]
                                                                   };
    – “moc” tool
        •   Parses Q_OBJECT macro
        •   Extends source code with additional functions (extra files)
        •   Removes the signals, slots and emit keywords so compiler sees standard C++
• Advantage: works with any C++ compiler
Meta-Object Features
• Features provided by meta-object code:
    – Signals and slots
    – metaObject() – returns associated meta-object for the class
    – QMetaObject::className() – returns class name as a string,
      without requiring native run-time type information (RTTI) support
      through the C++ compiler
    – inherits() – returns whether this instance inherits the specified QObject class
    – tr() – translate strings
    – setProperty() and property() – dynamically set and get properties by name
Casting
• Meta-object information can be used for casting:
   if (widget->inherits("QAbstractButton")) {
       QAbstractButton *button = static_cast<QAbstractButton*>(widget);
       button->toggle();
   }




• Similar, but less error-prone:
   if (QAbstractButton *button = qobject_cast<QAbstractButton*>(widget))
       button->toggle();
More on... Signals
•   Emitted signal
      –   Slot usually executed immediately
          (like normal function call)
      –   Code after emit keyword executed after
          all slots returned
      –   Queued connections: slots executed later
                                                                 #include <QObject>
•   1 signal  n slots                                           class Counter : public QObject {
      –   Slots executed one after another (arbitrary order)         Q_OBJECT
                                                                     [...]
•   Implementation                                               signals:
      –   Automatically generated by moc                             void valueChanged(int newValue);
                                                                     [...]
      –   Define in .h, do not implement in .cpp file            };
      –   Can never have return values ( use void)
      –   Good style: arguments should not use special types (reusability)
More on... Slots                                                    #include <QObject>
                                                                    class Counter : public QObject {
                                                                        Q_OBJECT
•   C++ function                                                        [...]
                                                                    public slots:
      –   Can be called directly/normally                               void setValue(int value);
      –   If connected to and invoked by signal: works                  [...]
                                                                    };
          regardless of access level. Arbitrary class can
          invoke private slot of an unrelated class instance.
      –   Slots can be virtual, but not static
•   Overhead compared to direct call
      –   Does not matter in practice
      –   Around 10x slower than direct, non-virtual call
      –   Sounds a lot, but isn’t compared to for example new/delete operations
      –   i586-500: emit per second
          2,000,000 signals  1 slot.
          1,200,000 signals  2 slots.
Qt Class Hierarchy
  QLayoutItem             QObject                   QPaintDevice             QString




                QLayout                   QWidget                  QImage



                            ...
   ...                                                     ...             Many objects
            QBoxLayout                    QDialog
                                                                        (and all widgets)
                                                                      derived from QObject
                                                                      (directly or indirectly)
                  ...               ...     ...      ...
Memory Management
• Parent-child hierarchy implemented in QObject
    – Initialization with pointer to parent QObject 
      parent adds new object to list of its children
    – Delete parent: automatically deletes all its children (recursively)
    – Delete child: automatically removed from parent’s child list
    –  Some memory management handled by Qt, only delete objects created
      with new without parent
• Widgets
    – Parent has additional meaning: child widgets shown within parent’s area
Example: Parent-Child                                                 QWidget


    QWidget* win = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(win);         QVBoxLayout             QPushButton
    QPushButton* but = new QPushButton("Label");
    layout->addWidget(but);
    win->show();

     – Layout is a child of parent widget
     – Push button added to layout, but widget takes ownership
    QWidget* win = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(win);
    QPushButton* but = new QPushButton("Label", win);
    win->show();

•   Directly adding push button to the parent widget:
     – Also displays push button, but not managed by layout manager
Example: Parent-Child II
• Helpful: print parent-child relationship
    QWidget* win = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(win);
    QPushButton* but = new QPushButton("Label");
    layout->addWidget(but);
    win->dumpObjectTree();


                              Console
                                QWidget::
                                    QVBoxLayout::
                                    QPushButton::
Creating Objects
•   Objects inheriting from QObject are allocated on the heap using new
     – If a parent object is assigned, it takes ownership of the newly created object – and
       eventually calls delete
          QLabel *label = new QLabel("Some Text", parent);
•   Objects not inheriting QObject are allocated on the stack, not the heap
          QStringList list;
          QColor color;

•   Exceptions
     – QFile and QApplication (inheriting QObject) are usually allocated on the stack
     – Modal dialogs are often allocated on the stack, too
Thank You.

More Related Content

PPTX
Qt for beginners part 1 overview and key concepts
 
PDF
Best Practices in Qt Quick/QML - Part 1 of 4
 
PDF
Qt Application Programming with C++ - Part 1
PDF
Introduction to Qt programming
PDF
Introduction to QML
PPTX
Qt Framework Events Signals Threads
PPTX
Best Practices in Qt Quick/QML - Part I
 
PDF
QThreads: Are You Using Them Wrong?
 
Qt for beginners part 1 overview and key concepts
 
Best Practices in Qt Quick/QML - Part 1 of 4
 
Qt Application Programming with C++ - Part 1
Introduction to Qt programming
Introduction to QML
Qt Framework Events Signals Threads
Best Practices in Qt Quick/QML - Part I
 
QThreads: Are You Using Them Wrong?
 

What's hot (20)

PDF
In-Depth Model/View with QML
 
PDF
Qt for beginners
PDF
Best Practices in Qt Quick/QML - Part II
 
PDF
Qt multi threads
PPTX
Introduction to Qt
ODP
Qt Workshop
ODP
Qt 5 - C++ and Widgets
PDF
Lessons Learned from Building 100+ C++/Qt/QML Devices
 
PPTX
Qt Qml
PDF
Qt Application Programming with C++ - Part 2
PDF
Best Practices in Qt Quick/QML - Part IV
 
PPT
Qt Technical Presentation
PPTX
UI Programming with Qt-Quick and QML
PDF
Basics of Model/View Qt programming
 
PDF
Best Practices in Qt Quick/QML - Part 4
 
PPTX
Hello, QML
PDF
Qt Internationalization
 
PDF
Best Practices in Qt Quick/QML - Part 3
 
PDF
PDF
Introduction to Qt Creator
 
In-Depth Model/View with QML
 
Qt for beginners
Best Practices in Qt Quick/QML - Part II
 
Qt multi threads
Introduction to Qt
Qt Workshop
Qt 5 - C++ and Widgets
Lessons Learned from Building 100+ C++/Qt/QML Devices
 
Qt Qml
Qt Application Programming with C++ - Part 2
Best Practices in Qt Quick/QML - Part IV
 
Qt Technical Presentation
UI Programming with Qt-Quick and QML
Basics of Model/View Qt programming
 
Best Practices in Qt Quick/QML - Part 4
 
Hello, QML
Qt Internationalization
 
Best Practices in Qt Quick/QML - Part 3
 
Introduction to Qt Creator
 
Ad

Viewers also liked (8)

PDF
Introducción a Qt
PDF
Primeros Pasos en PyQt4
PPTX
Qt user interface
PDF
Cómo salir en Google el primero gracias a AdWords
PDF
8 aspectos imprescindibles de un análisis SEO
PDF
8 errores que están matando tu plan de contenidos
PDF
Trucos LinkedIn para ser un crack en la red de los profesionales
PPS
Image Processing Basics
Introducción a Qt
Primeros Pasos en PyQt4
Qt user interface
Cómo salir en Google el primero gracias a AdWords
8 aspectos imprescindibles de un análisis SEO
8 errores que están matando tu plan de contenidos
Trucos LinkedIn para ser un crack en la red de los profesionales
Image Processing Basics
Ad

Similar to 02 - Basics of Qt (20)

PDF
03 - Qt UI Development
ODP
Treinamento Qt básico - aula III
PDF
The Ring programming language version 1.7 book - Part 70 of 196
PDF
Qt for beginners part 2 widgets
 
PDF
The Ring programming language version 1.8 book - Part 72 of 202
PDF
The Ring programming language version 1.3 book - Part 46 of 88
PPTX
Qt Memory Management & Signal and Slots
PDF
The Ring programming language version 1.6 book - Part 65 of 189
PDF
The Ring programming language version 1.5.1 book - Part 59 of 180
PDF
Qt Widget In-Depth
PDF
Qt Widgets In Depth
PDF
The Ring programming language version 1.5.2 book - Part 60 of 181
PDF
The Ring programming language version 1.9 book - Part 73 of 210
PDF
The Ring programming language version 1.8 book - Part 69 of 202
PDF
The Ring programming language version 1.7 book - Part 67 of 196
PDF
The Ring programming language version 1.5.4 book - Part 63 of 185
PDF
05 - Qt External Interaction and Graphics
PDF
Qt & Webkit
ODP
Treinamento Qt básico - aula II
03 - Qt UI Development
Treinamento Qt básico - aula III
The Ring programming language version 1.7 book - Part 70 of 196
Qt for beginners part 2 widgets
 
The Ring programming language version 1.8 book - Part 72 of 202
The Ring programming language version 1.3 book - Part 46 of 88
Qt Memory Management & Signal and Slots
The Ring programming language version 1.6 book - Part 65 of 189
The Ring programming language version 1.5.1 book - Part 59 of 180
Qt Widget In-Depth
Qt Widgets In Depth
The Ring programming language version 1.5.2 book - Part 60 of 181
The Ring programming language version 1.9 book - Part 73 of 210
The Ring programming language version 1.8 book - Part 69 of 202
The Ring programming language version 1.7 book - Part 67 of 196
The Ring programming language version 1.5.4 book - Part 63 of 185
05 - Qt External Interaction and Graphics
Qt & Webkit
Treinamento Qt básico - aula II

More from Andreas Jakl (20)

PDF
Create Engaging Healthcare Experiences with Augmented Reality
PDF
AR / VR Interaction Development with Unity
PDF
Android Development with Kotlin, Part 3 - Code and App Management
PDF
Android Development with Kotlin, Part 2 - Internet Services and JSON
PDF
Android Development with Kotlin, Part 1 - Introduction
PDF
Android and NFC / NDEF (with Kotlin)
PDF
Basics of Web Technologies
PDF
Bluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & More
PDF
Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?
PDF
Mobile Test Automation
PDF
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
PDF
WinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows Phone
PDF
Nokia New Asha Platform Developer Training
PDF
Windows Phone 8 NFC Quickstart
PDF
Windows (Phone) 8 NFC App Scenarios
PDF
Windows 8 Platform NFC Development
PDF
NFC Development with Qt - v2.2.0 (5. November 2012)
PDF
06 - Qt Communication
PDF
04 - Qt Data
PDF
Basics of WRT (Web Runtime)
Create Engaging Healthcare Experiences with Augmented Reality
AR / VR Interaction Development with Unity
Android Development with Kotlin, Part 3 - Code and App Management
Android Development with Kotlin, Part 2 - Internet Services and JSON
Android Development with Kotlin, Part 1 - Introduction
Android and NFC / NDEF (with Kotlin)
Basics of Web Technologies
Bluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & More
Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?
Mobile Test Automation
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
WinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows Phone
Nokia New Asha Platform Developer Training
Windows Phone 8 NFC Quickstart
Windows (Phone) 8 NFC App Scenarios
Windows 8 Platform NFC Development
NFC Development with Qt - v2.2.0 (5. November 2012)
06 - Qt Communication
04 - Qt Data
Basics of WRT (Web Runtime)

Recently uploaded (20)

PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Spectroscopy.pptx food analysis technology
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
KodekX | Application Modernization Development
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Machine learning based COVID-19 study performance prediction
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Cloud computing and distributed systems.
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Spectroscopy.pptx food analysis technology
Chapter 3 Spatial Domain Image Processing.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
The AUB Centre for AI in Media Proposal.docx
KodekX | Application Modernization Development
Per capita expenditure prediction using model stacking based on satellite ima...
Network Security Unit 5.pdf for BCA BBA.
Machine learning based COVID-19 study performance prediction
Dropbox Q2 2025 Financial Results & Investor Presentation
Spectral efficient network and resource selection model in 5G networks
20250228 LYD VKU AI Blended-Learning.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Empathic Computing: Creating Shared Understanding
Understanding_Digital_Forensics_Presentation.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Cloud computing and distributed systems.
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm

02 - Basics of Qt

  • 1. Basics of Qt Andreas Jakl Senior Technical Consultant Forum Nokia 20 September, 2010 v3.0.0
  • 2. Contents – Signals and Slots – Widgets, Layouts and Styles – Meta-Objects and Memory Management
  • 4. Callbacks? • Traditional callbacks – Callback is pointer to a function – Called when appropriate (event notification, ...) • Problems – Not type-safe: does the caller use the correct arguments? – Less generic: callback strongly coupled to processing function. Processing function must know which callback to call.
  • 5. Signals & Slots • Signal – Emitted when a particular event occurs (e.g., clicked()) – Qt widgets: predefined signals – Also create your own signals • Slot – Function called in response to a signal – Qt widgets: predefined slots (e.g., quit()) – Also create your own slots • Connection signals  slots established by developer, handled by Qt framework
  • 6. Connections Signals Signals connect( Object1, signal1, Object2, slot1 ) signal1 connect( Object1, signal1, Object2, slot2 ) signal1 signal2 Slots connect( Object2, signal1, Object4, slot3 ) connect( Object1, signal2, Object4, slot1 ) slot1 Slots slot2 slot1 slot2 slot3 Signals signal1 Signals Slots slot1 Slots slot1 slot2 slot3 connect( Object3, signal1, Object4, slot3 )
  • 7. Find Signals and Slots • Look up signals and slots of Qt classes in the documentation
  • 8. Example: Multiple Signal-Slot Connections Restore window to normal size Show an about dialog and then maximize the window Exit the application
  • 9. Example: Connections QApplication app Signals QPushButton but1 Signals Slots clicked aboutQt() Slots quit() QPushButton but2 Signals clicked QWidget win Slots Signals QPushButton but3 clicked Signals clicked Slots showNormal() Slots showMaximized()
  • 10. #include <QApplication> #include <QPushButton> #include <QVBoxLayout> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget* win = new QWidget(); QVBoxLayout* layout = new QVBoxLayout(win); QPushButton* but1 = new QPushButton("Normal size"); but1->resize(150, 30); layout->addWidget(but1); QPushButton* but2 = new QPushButton("About and Maximize"); but2->resize(150, 30); layout->addWidget(but2); QPushButton* but3 = new QPushButton("Exit"); but3->resize(150, 30); layout->addWidget(but3); aboutQt() and QObject::connect(but1, SIGNAL(clicked()), win, SLOT(showNormal())); showMaximized() QObject::connect(but2, SIGNAL(clicked()), &app, SLOT(aboutQt())); executed one after QObject::connect(but2, SIGNAL(clicked()), win, SLOT(showMaximized())); QObject::connect(but3, SIGNAL(clicked()), &app, SLOT(quit())); another win->show(); return app.exec(); }
  • 11. Layouts Most common layouts – QHBoxLayout: horizontal, from left to right (right to left for some cultures) – QVBoxLayout: vertical, top to bottom – QGridLayout: grid – QFormLayout: manages input widgets and associated labels – QStackedLayout: widgets on top of each other, switch index of currently visible widget • Layouts can be nested – Add new layout to existing layout like a widget: l->addLayout(l2)
  • 12. Styles Style can be set using -style <name> command- line option. Windows XP/Vista/7 and plastique cleanlooks Macintosh styles are only available on native platforms (relies on platform’s theme engines) It’s possible to create own windowsvista windowsxp windows styles. macintosh motif cde
  • 13. Example 2 • Synchronize two widgets – Changing the value in one automatically changes the other Signals Signals valueChanged(int) valueChanged(int) Slots Slots setValue(int) setValue(int)
  • 14. #include <QApplication> #include <QHBoxLayout> #include <QSpinBox> #include <QSlider> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget* win = new QWidget(); win->setWindowTitle("Synchronized Widgets"); QHBoxLayout* layout = new QHBoxLayout(win); QSpinBox* spin = new QSpinBox(); spin->setMinimum(0); spin->setMaximum(100); layout->addWidget(spin); QSlider* slider = new QSlider(Qt::Horizontal); slider->setMinimum(0); slider->setMaximum(100); layout->addWidget(slider); QObject::connect( spin, SIGNAL( valueChanged(int) ), slider, SLOT( setValue(int) ) ); QObject::connect( slider, SIGNAL( valueChanged(int) ), spin, SLOT( setValue(int) ) ); spin->setValue(50); win->show(); return app.exec(); }
  • 15. Signal Parameters Transmit additional information QObject::connect( spin, SIGNAL( valueChanged(int) ), slider, SLOT( setValue(int) ) ); – Specify type of argument(s) – Signal has to be compatible to the slot (same parameter type(s))
  • 16. Signal Parameters • Types not automatically casted by Qt – Signals & slots with exactly the specified parameters have to exist – Otherwise: no compilation error / warning – But: warning at runtime when executing connect(): QObject::connect: Incompatible sender/receiver arguments QSpinBox::valueChanged(QString) --> QSlider::setValue(int) • → Signals & slots are type safe – No connection if either sender or receiver doesn’t exist – Or if signatures of signal and slot do not match • connect() returns boolean value indicating success
  • 17. Signal & Slot Processing setValue(50) is called in the source code QSpinBox emits valueChanged(int) signal with int argument of 50 signal  slot Argument is passed to QSlider’s setValue(int) slot, sets slider value to 50 QSlider emits valueChanged(int) signal with int argument of 50 signal  slot Argument is passed to QSpinbox’s setValue(int) slot, but value is already set to 50.  doesn’t emit any further signal to prevent infinite recursion.
  • 18. Signals & Slots • Type safe – Signal signature must match signature of receiving slot – (Slot might also have shorter signature and ignore rest of the arguments) • Loosely coupled – Emitter doesn’t know or care which slots receive signal – Information encapsulation • Integrated, independent components – Slots are normal C++ member functions – Don’t know if signals are connected to them
  • 19. Manual Signal & Slots counter.h counter.cpp #ifndef COUNTER_H #include "counter.h" #define COUNTER_H void Counter::setValue(int value) #include <QObject> { if (value != m_value) class Counter : public QObject { { m_value = value; Q_OBJECT emit valueChanged(value); } public: } Counter() { m_value = 0; } int value() const { return m_value; } public slots: void setValue(int value); signals: Own Class that represents void valueChanged(int newValue); behaviour of Example 2 private: int m_value; }; #endif // COUNTER_H
  • 20. main.cpp #include <QtGui/QApplication> #include <QMessageBox> #include "counter.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); Counter a, b; QObject::connect(&a, SIGNAL(valueChanged(int)), &b, SLOT(setValue(int))); a.setValue(12); // a.value() == 12, b.value() == 12 QMessageBox msgBox; msgBox.setText("a = " + QString::number(a.value()) + ", b = " + QString::number(b.value())); msgBox.exec(); b.setValue(48); // a.value() == 12, b.value() == 48 msgBox.setText("a = " + QString::number(a.value()) + ", b = " + QString::number(b.value())); msgBox.exec(); app.quit(); return 1; }
  • 22. Qt Meta-Object System • C++ extended with meta-object mechanism: Introspection – Obtain meta-information about QObject subclasses at runtime – Used for: getting list of signals & slots, properties and text translation
  • 23. QObject • Meta information not supported by standard C++ – QObject class • Base class for objects that use meta-object system #include <QObject> class Counter : public QObject – Q_OBJECT macro { • Enables meta-object features Q_OBJECT • Without ; [...] }; – “moc” tool • Parses Q_OBJECT macro • Extends source code with additional functions (extra files) • Removes the signals, slots and emit keywords so compiler sees standard C++ • Advantage: works with any C++ compiler
  • 24. Meta-Object Features • Features provided by meta-object code: – Signals and slots – metaObject() – returns associated meta-object for the class – QMetaObject::className() – returns class name as a string, without requiring native run-time type information (RTTI) support through the C++ compiler – inherits() – returns whether this instance inherits the specified QObject class – tr() – translate strings – setProperty() and property() – dynamically set and get properties by name
  • 25. Casting • Meta-object information can be used for casting: if (widget->inherits("QAbstractButton")) { QAbstractButton *button = static_cast<QAbstractButton*>(widget); button->toggle(); } • Similar, but less error-prone: if (QAbstractButton *button = qobject_cast<QAbstractButton*>(widget)) button->toggle();
  • 26. More on... Signals • Emitted signal – Slot usually executed immediately (like normal function call) – Code after emit keyword executed after all slots returned – Queued connections: slots executed later #include <QObject> • 1 signal  n slots class Counter : public QObject { – Slots executed one after another (arbitrary order) Q_OBJECT [...] • Implementation signals: – Automatically generated by moc void valueChanged(int newValue); [...] – Define in .h, do not implement in .cpp file }; – Can never have return values ( use void) – Good style: arguments should not use special types (reusability)
  • 27. More on... Slots #include <QObject> class Counter : public QObject { Q_OBJECT • C++ function [...] public slots: – Can be called directly/normally void setValue(int value); – If connected to and invoked by signal: works [...] }; regardless of access level. Arbitrary class can invoke private slot of an unrelated class instance. – Slots can be virtual, but not static • Overhead compared to direct call – Does not matter in practice – Around 10x slower than direct, non-virtual call – Sounds a lot, but isn’t compared to for example new/delete operations – i586-500: emit per second 2,000,000 signals  1 slot. 1,200,000 signals  2 slots.
  • 28. Qt Class Hierarchy QLayoutItem QObject QPaintDevice QString QLayout QWidget QImage ... ... ... Many objects QBoxLayout QDialog (and all widgets) derived from QObject (directly or indirectly) ... ... ... ...
  • 29. Memory Management • Parent-child hierarchy implemented in QObject – Initialization with pointer to parent QObject  parent adds new object to list of its children – Delete parent: automatically deletes all its children (recursively) – Delete child: automatically removed from parent’s child list –  Some memory management handled by Qt, only delete objects created with new without parent • Widgets – Parent has additional meaning: child widgets shown within parent’s area
  • 30. Example: Parent-Child QWidget QWidget* win = new QWidget(); QVBoxLayout* layout = new QVBoxLayout(win); QVBoxLayout QPushButton QPushButton* but = new QPushButton("Label"); layout->addWidget(but); win->show(); – Layout is a child of parent widget – Push button added to layout, but widget takes ownership QWidget* win = new QWidget(); QVBoxLayout* layout = new QVBoxLayout(win); QPushButton* but = new QPushButton("Label", win); win->show(); • Directly adding push button to the parent widget: – Also displays push button, but not managed by layout manager
  • 31. Example: Parent-Child II • Helpful: print parent-child relationship QWidget* win = new QWidget(); QVBoxLayout* layout = new QVBoxLayout(win); QPushButton* but = new QPushButton("Label"); layout->addWidget(but); win->dumpObjectTree(); Console QWidget:: QVBoxLayout:: QPushButton::
  • 32. Creating Objects • Objects inheriting from QObject are allocated on the heap using new – If a parent object is assigned, it takes ownership of the newly created object – and eventually calls delete QLabel *label = new QLabel("Some Text", parent); • Objects not inheriting QObject are allocated on the stack, not the heap QStringList list; QColor color; • Exceptions – QFile and QApplication (inheriting QObject) are usually allocated on the stack – Modal dialogs are often allocated on the stack, too