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

What's hot (20)

PDF
Meet Qt 6.0
Qt
 
PDF
Best Practices in Qt Quick/QML - Part 1 of 4
ICS
 
PPTX
Introduction to Qt
Puja Pramudya
 
PDF
In-Depth Model/View with QML
ICS
 
PPTX
Qt Qml
Steven Song
 
PDF
QThreads: Are You Using Them Wrong?
ICS
 
PDF
Introduction to Qt Creator
Qt
 
PDF
QVariant, QObject — Qt's not just for GUI development
ICS
 
PDF
Qt programming-using-cpp
Emertxe Information Technologies Pvt Ltd
 
PDF
Introduction to Qt programming
Dragos Tudor Acostachioaie
 
PDF
Introduction to QML
Alan Uthoff
 
PPTX
Best Practices in Qt Quick/QML - Part I
ICS
 
PPT
Qt Technical Presentation
Daniel Rocha
 
PPTX
Hello, QML
Jack Yang
 
PDF
Qt Application Programming with C++ - Part 2
Emertxe Information Technologies Pvt Ltd
 
PDF
Best Practices in Qt Quick/QML - Part IV
ICS
 
PDF
Lessons Learned from Building 100+ C++/Qt/QML Devices
ICS
 
PPTX
Android jetpack compose | Declarative UI
Ajinkya Saswade
 
PDF
Best Practices in Qt Quick/QML - Part 4
ICS
 
PDF
Best Practices in Qt Quick/QML - Part II
ICS
 
Meet Qt 6.0
Qt
 
Best Practices in Qt Quick/QML - Part 1 of 4
ICS
 
Introduction to Qt
Puja Pramudya
 
In-Depth Model/View with QML
ICS
 
Qt Qml
Steven Song
 
QThreads: Are You Using Them Wrong?
ICS
 
Introduction to Qt Creator
Qt
 
QVariant, QObject — Qt's not just for GUI development
ICS
 
Introduction to Qt programming
Dragos Tudor Acostachioaie
 
Introduction to QML
Alan Uthoff
 
Best Practices in Qt Quick/QML - Part I
ICS
 
Qt Technical Presentation
Daniel Rocha
 
Hello, QML
Jack Yang
 
Qt Application Programming with C++ - Part 2
Emertxe Information Technologies Pvt Ltd
 
Best Practices in Qt Quick/QML - Part IV
ICS
 
Lessons Learned from Building 100+ C++/Qt/QML Devices
ICS
 
Android jetpack compose | Declarative UI
Ajinkya Saswade
 
Best Practices in Qt Quick/QML - Part 4
ICS
 
Best Practices in Qt Quick/QML - Part II
ICS
 

Viewers also liked (9)

ODP
Qt 5 - C++ and Widgets
Juha Peltomäki
 
PDF
Introducción a Qt
dgalo88
 
PDF
Primeros Pasos en PyQt4
Jesse Padilla Agudelo
 
PPTX
Qt user interface
meriem sari
 
PDF
Cómo salir en Google el primero gracias a AdWords
websa100
 
PDF
8 aspectos imprescindibles de un análisis SEO
websa100
 
PDF
8 errores que están matando tu plan de contenidos
websa100
 
PDF
Trucos LinkedIn para ser un crack en la red de los profesionales
websa100
 
PPS
Image Processing Basics
Nam Le
 
Qt 5 - C++ and Widgets
Juha Peltomäki
 
Introducción a Qt
dgalo88
 
Primeros Pasos en PyQt4
Jesse Padilla Agudelo
 
Qt user interface
meriem sari
 
Cómo salir en Google el primero gracias a AdWords
websa100
 
8 aspectos imprescindibles de un análisis SEO
websa100
 
8 errores que están matando tu plan de contenidos
websa100
 
Trucos LinkedIn para ser un crack en la red de los profesionales
websa100
 
Image Processing Basics
Nam Le
 
Ad

Similar to 02 - Basics of Qt (20)

PDF
03 - Qt UI Development
Andreas Jakl
 
ODP
Treinamento Qt básico - aula III
Marcelo Barros de Almeida
 
PDF
The Ring programming language version 1.7 book - Part 70 of 196
Mahmoud Samir Fayed
 
ODP
Qt Workshop
Johan Thelin
 
PDF
Qt for beginners part 2 widgets
ICS
 
PDF
The Ring programming language version 1.8 book - Part 72 of 202
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.3 book - Part 46 of 88
Mahmoud Samir Fayed
 
PPTX
Qt Memory Management & Signal and Slots
Jussi Pohjolainen
 
PDF
The Ring programming language version 1.6 book - Part 65 of 189
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.5.1 book - Part 59 of 180
Mahmoud Samir Fayed
 
PDF
Qt Widget In-Depth
account inactive
 
PDF
Qt Widgets In Depth
Marius Bugge Monsen
 
PDF
The Ring programming language version 1.5.2 book - Part 60 of 181
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.9 book - Part 73 of 210
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.8 book - Part 69 of 202
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.7 book - Part 67 of 196
Mahmoud Samir Fayed
 
PDF
The Ring programming language version 1.5.4 book - Part 63 of 185
Mahmoud Samir Fayed
 
PDF
05 - Qt External Interaction and Graphics
Andreas Jakl
 
PDF
Qt & Webkit
QT-day
 
03 - Qt UI Development
Andreas Jakl
 
Treinamento Qt básico - aula III
Marcelo Barros de Almeida
 
The Ring programming language version 1.7 book - Part 70 of 196
Mahmoud Samir Fayed
 
Qt Workshop
Johan Thelin
 
Qt for beginners part 2 widgets
ICS
 
The Ring programming language version 1.8 book - Part 72 of 202
Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 46 of 88
Mahmoud Samir Fayed
 
Qt Memory Management & Signal and Slots
Jussi Pohjolainen
 
The Ring programming language version 1.6 book - Part 65 of 189
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 59 of 180
Mahmoud Samir Fayed
 
Qt Widget In-Depth
account inactive
 
Qt Widgets In Depth
Marius Bugge Monsen
 
The Ring programming language version 1.5.2 book - Part 60 of 181
Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 73 of 210
Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 69 of 202
Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 67 of 196
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 63 of 185
Mahmoud Samir Fayed
 
05 - Qt External Interaction and Graphics
Andreas Jakl
 
Qt & Webkit
QT-day
 
Ad

More from Andreas Jakl (20)

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

Recently uploaded (20)

PDF
July Patch Tuesday
Ivanti
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
July Patch Tuesday
Ivanti
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 

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