SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
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.

Contenu connexe

Tendances

In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QMLICS
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programmingICS
 
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 IICS
 
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 developmentICS
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals ThreadsNeera Mital
 
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 QuickICS
 
Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QMLAlan Uthoff
 
Meet Qt 6.0
Meet Qt 6.0 Meet Qt 6.0
Meet Qt 6.0 Qt
 
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 3ICS
 
Using Multi-Touch and Gestures with Qt
Using Multi-Touch and Gestures with QtUsing Multi-Touch and Gestures with Qt
Using Multi-Touch and Gestures with Qtaccount inactive
 
Best Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVBest Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVICS
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIICS
 
Practical QML - Key Navigation, Dynamic Language and Theme Change
Practical QML - Key Navigation, Dynamic Language and Theme ChangePractical QML - Key Navigation, Dynamic Language and Theme Change
Practical QML - Key Navigation, Dynamic Language and Theme ChangeBurkhard Stubert
 

Tendances (20)

Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2
 
Introduction to Qt programming
Introduction to Qt programmingIntroduction to Qt programming
Introduction to Qt programming
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QML
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programming
 
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 Application Programming with C++ - Part 1
Qt Application Programming with C++ - Part 1Qt Application Programming with C++ - Part 1
Qt Application Programming with C++ - Part 1
 
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
 
Introduction to Qt
Introduction to QtIntroduction to Qt
Introduction to Qt
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
 
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
 
Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QML
 
Meet Qt 6.0
Meet Qt 6.0 Meet Qt 6.0
Meet Qt 6.0
 
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
 
UI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QMLUI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QML
 
Using Multi-Touch and Gestures with Qt
Using Multi-Touch and Gestures with QtUsing Multi-Touch and Gestures with Qt
Using Multi-Touch and Gestures with Qt
 
Best Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IVBest Practices in Qt Quick/QML - Part IV
Best Practices in Qt Quick/QML - Part IV
 
Qt Qml
Qt QmlQt Qml
Qt Qml
 
Hello, QML
Hello, QMLHello, QML
Hello, QML
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part II
 
Practical QML - Key Navigation, Dynamic Language and Theme Change
Practical QML - Key Navigation, Dynamic Language and Theme ChangePractical QML - Key Navigation, Dynamic Language and Theme Change
Practical QML - Key Navigation, Dynamic Language and Theme Change
 

En vedette

Introducción a Qt
Introducción a QtIntroducción a Qt
Introducción a Qtdgalo88
 
Qt user interface
Qt user interfaceQt user interface
Qt user interfacemeriem sari
 
Cómo salir en Google el primero gracias a AdWords
Cómo salir en Google el primero gracias a AdWordsCómo salir en Google el primero gracias a AdWords
Cómo salir en Google el primero gracias a AdWordswebsa100
 
8 aspectos imprescindibles de un análisis SEO
8 aspectos imprescindibles de un análisis SEO8 aspectos imprescindibles de un análisis SEO
8 aspectos imprescindibles de un análisis SEOwebsa100
 
8 errores que están matando tu plan de contenidos
8 errores que están matando tu plan de contenidos 8 errores que están matando tu plan de contenidos
8 errores que están matando tu plan de contenidos websa100
 
Trucos LinkedIn para ser un crack en la red de los profesionales
Trucos LinkedIn para ser un crack en la red de los profesionalesTrucos LinkedIn para ser un crack en la red de los profesionales
Trucos LinkedIn para ser un crack en la red de los profesionaleswebsa100
 
Image Processing Basics
Image Processing BasicsImage Processing Basics
Image Processing BasicsNam Le
 

En vedette (8)

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

Similaire à 02 - Basics of Qt

A Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkA Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkZachary Blair
 
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...HostedbyConfluent
 
Lecture 2 verilog
Lecture 2   verilogLecture 2   verilog
Lecture 2 verilogvenravi10
 
Debugging, a step away from the console
Debugging, a step away from the consoleDebugging, a step away from the console
Debugging, a step away from the consoleAdam Weeks
 
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...Guozhang Wang
 
Learn basics of Clojure/script and Reagent
Learn basics of Clojure/script and ReagentLearn basics of Clojure/script and Reagent
Learn basics of Clojure/script and ReagentMaty Fedak
 
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...Positive Hack Days
 
Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.UA Mobile
 
03 - Qt UI Development
03 - Qt UI Development03 - Qt UI Development
03 - Qt UI DevelopmentAndreas Jakl
 
Petri Niemi Qt Advanced Part 2
Petri Niemi Qt Advanced Part 2Petri Niemi Qt Advanced Part 2
Petri Niemi Qt Advanced Part 2NokiaAppForum
 
Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part IAjit Nayak
 
[Ruxcon 2011] Post Memory Corruption Memory Analysis
[Ruxcon 2011] Post Memory Corruption Memory Analysis[Ruxcon 2011] Post Memory Corruption Memory Analysis
[Ruxcon 2011] Post Memory Corruption Memory AnalysisMoabi.com
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performanceDuoyi Wu
 

Similaire à 02 - Basics of Qt (20)

Treinamento Qt básico - aula II
Treinamento Qt básico - aula IITreinamento Qt básico - aula II
Treinamento Qt básico - aula II
 
A Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application FrameworkA Brief Introduction to the Qt Application Framework
A Brief Introduction to the Qt Application Framework
 
STORM
STORMSTORM
STORM
 
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
 
Lecture 2 verilog
Lecture 2   verilogLecture 2   verilog
Lecture 2 verilog
 
Debugging, a step away from the console
Debugging, a step away from the consoleDebugging, a step away from the console
Debugging, a step away from the console
 
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
Exactly-Once Made Easy: Transactional Messaging Improvement for Usability and...
 
Qt
QtQt
Qt
 
Learn basics of Clojure/script and Reagent
Learn basics of Clojure/script and ReagentLearn basics of Clojure/script and Reagent
Learn basics of Clojure/script and Reagent
 
Storm 0.8.2
Storm 0.8.2Storm 0.8.2
Storm 0.8.2
 
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
The System of Automatic Searching for Vulnerabilities or how to use Taint Ana...
 
Tierney bq207
Tierney bq207Tierney bq207
Tierney bq207
 
Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.
 
03 - Qt UI Development
03 - Qt UI Development03 - Qt UI Development
03 - Qt UI Development
 
Petri Niemi Qt Advanced Part 2
Petri Niemi Qt Advanced Part 2Petri Niemi Qt Advanced Part 2
Petri Niemi Qt Advanced Part 2
 
Rapport
RapportRapport
Rapport
 
Extreme dxt compression
Extreme dxt compressionExtreme dxt compression
Extreme dxt compression
 
Ns2: Introduction - Part I
Ns2: Introduction - Part INs2: Introduction - Part I
Ns2: Introduction - Part I
 
[Ruxcon 2011] Post Memory Corruption Memory Analysis
[Ruxcon 2011] Post Memory Corruption Memory Analysis[Ruxcon 2011] Post Memory Corruption Memory Analysis
[Ruxcon 2011] Post Memory Corruption Memory Analysis
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
 

Plus de Andreas Jakl

Create Engaging Healthcare Experiences with Augmented Reality
Create Engaging Healthcare Experiences with Augmented RealityCreate Engaging Healthcare Experiences with Augmented Reality
Create Engaging Healthcare Experiences with Augmented RealityAndreas Jakl
 
AR / VR Interaction Development with Unity
AR / VR Interaction Development with UnityAR / VR Interaction Development with Unity
AR / VR Interaction Development with UnityAndreas Jakl
 
Android Development with Kotlin, Part 3 - Code and App Management
Android Development with Kotlin, Part 3 - Code and App ManagementAndroid Development with Kotlin, Part 3 - Code and App Management
Android Development with Kotlin, Part 3 - Code and App ManagementAndreas Jakl
 
Android Development with Kotlin, Part 2 - Internet Services and JSON
Android Development with Kotlin, Part 2 - Internet Services and JSONAndroid Development with Kotlin, Part 2 - Internet Services and JSON
Android Development with Kotlin, Part 2 - Internet Services and JSONAndreas Jakl
 
Android Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - IntroductionAndroid Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - IntroductionAndreas Jakl
 
Android and NFC / NDEF (with Kotlin)
Android and NFC / NDEF (with Kotlin)Android and NFC / NDEF (with Kotlin)
Android and NFC / NDEF (with Kotlin)Andreas Jakl
 
Basics of Web Technologies
Basics of Web TechnologiesBasics of Web Technologies
Basics of Web TechnologiesAndreas Jakl
 
Bluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & More
Bluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & MoreBluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & More
Bluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & MoreAndreas Jakl
 
Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?
Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?
Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?Andreas Jakl
 
Mobile Test Automation
Mobile Test AutomationMobile Test Automation
Mobile Test AutomationAndreas Jakl
 
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...Andreas Jakl
 
WinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows Phone
WinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows PhoneWinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows Phone
WinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows PhoneAndreas Jakl
 
Nokia New Asha Platform Developer Training
Nokia New Asha Platform Developer TrainingNokia New Asha Platform Developer Training
Nokia New Asha Platform Developer TrainingAndreas Jakl
 
Windows Phone 8 NFC Quickstart
Windows Phone 8 NFC QuickstartWindows Phone 8 NFC Quickstart
Windows Phone 8 NFC QuickstartAndreas Jakl
 
Windows (Phone) 8 NFC App Scenarios
Windows (Phone) 8 NFC App ScenariosWindows (Phone) 8 NFC App Scenarios
Windows (Phone) 8 NFC App ScenariosAndreas Jakl
 
Windows 8 Platform NFC Development
Windows 8 Platform NFC DevelopmentWindows 8 Platform NFC Development
Windows 8 Platform NFC DevelopmentAndreas Jakl
 
NFC Development with Qt - v2.2.0 (5. November 2012)
NFC Development with Qt - v2.2.0 (5. November 2012)NFC Development with Qt - v2.2.0 (5. November 2012)
NFC Development with Qt - v2.2.0 (5. November 2012)Andreas Jakl
 
06 - Qt Communication
06 - Qt Communication06 - Qt Communication
06 - Qt CommunicationAndreas Jakl
 
05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics05 - Qt External Interaction and Graphics
05 - Qt External Interaction and GraphicsAndreas Jakl
 

Plus de Andreas Jakl (20)

Create Engaging Healthcare Experiences with Augmented Reality
Create Engaging Healthcare Experiences with Augmented RealityCreate Engaging Healthcare Experiences with Augmented Reality
Create Engaging Healthcare Experiences with Augmented Reality
 
AR / VR Interaction Development with Unity
AR / VR Interaction Development with UnityAR / VR Interaction Development with Unity
AR / VR Interaction Development with Unity
 
Android Development with Kotlin, Part 3 - Code and App Management
Android Development with Kotlin, Part 3 - Code and App ManagementAndroid Development with Kotlin, Part 3 - Code and App Management
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 2 - Internet Services and JSONAndroid Development with Kotlin, Part 2 - Internet Services and JSON
Android Development with Kotlin, Part 2 - Internet Services and JSON
 
Android Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - IntroductionAndroid Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - Introduction
 
Android and NFC / NDEF (with Kotlin)
Android and NFC / NDEF (with Kotlin)Android and NFC / NDEF (with Kotlin)
Android and NFC / NDEF (with Kotlin)
 
Basics of Web Technologies
Basics of Web TechnologiesBasics of Web Technologies
Basics of Web Technologies
 
Bluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & More
Bluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & MoreBluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & More
Bluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & More
 
Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?
Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?
Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?
 
Mobile Test Automation
Mobile Test AutomationMobile Test Automation
Mobile Test Automation
 
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...
 
WinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows Phone
WinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows PhoneWinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows Phone
WinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows Phone
 
Nokia New Asha Platform Developer Training
Nokia New Asha Platform Developer TrainingNokia New Asha Platform Developer Training
Nokia New Asha Platform Developer Training
 
Windows Phone 8 NFC Quickstart
Windows Phone 8 NFC QuickstartWindows Phone 8 NFC Quickstart
Windows Phone 8 NFC Quickstart
 
Windows (Phone) 8 NFC App Scenarios
Windows (Phone) 8 NFC App ScenariosWindows (Phone) 8 NFC App Scenarios
Windows (Phone) 8 NFC App Scenarios
 
Windows 8 Platform NFC Development
Windows 8 Platform NFC DevelopmentWindows 8 Platform NFC Development
Windows 8 Platform NFC Development
 
NFC Development with Qt - v2.2.0 (5. November 2012)
NFC Development with Qt - v2.2.0 (5. November 2012)NFC Development with Qt - v2.2.0 (5. November 2012)
NFC Development with Qt - v2.2.0 (5. November 2012)
 
06 - Qt Communication
06 - Qt Communication06 - Qt Communication
06 - Qt Communication
 
05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics05 - Qt External Interaction and Graphics
05 - Qt External Interaction and Graphics
 
04 - Qt Data
04 - Qt Data04 - Qt Data
04 - Qt Data
 

Dernier

Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 

Dernier (20)

Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 

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