SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
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.

Weitere ähnliche Inhalte

Was ist angesagt?

In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QMLICS
 
Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QMLAlan Uthoff
 
QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong? QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong? ICS
 
Qt Technical Presentation
Qt Technical PresentationQt Technical Presentation
Qt Technical PresentationDaniel Rocha
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google MockICS
 
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
 
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
 
Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4ICS
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIICS
 
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
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals ThreadsNeera Mital
 
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
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programmingICS
 

Was ist angesagt? (20)

In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QML
 
Qt programming-using-cpp
Qt programming-using-cppQt programming-using-cpp
Qt programming-using-cpp
 
Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QML
 
Hello, QML
Hello, QMLHello, QML
Hello, QML
 
Qt Workshop
Qt WorkshopQt Workshop
Qt Workshop
 
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
 
QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong? QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong?
 
Qt Technical Presentation
Qt Technical PresentationQt Technical Presentation
Qt Technical Presentation
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
 
QVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentQVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI development
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part II
 
Qt Qml
Qt QmlQt Qml
Qt Qml
 
Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4Best Practices in Qt Quick/QML - Part 1 of 4
Best Practices in Qt Quick/QML - Part 1 of 4
 
Best Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part IIIBest Practices in Qt Quick/QML - Part III
Best Practices in Qt Quick/QML - Part III
 
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
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
 
Qt for beginners
Qt for beginnersQt for beginners
Qt for beginners
 
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
 
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
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programming
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

"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
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
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
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
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
 
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
 
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
 
"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
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Kürzlich hochgeladen (20)

"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...
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
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
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
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
 
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
 
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!
 
"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
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

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