SlideShare a Scribd company logo
1 of 33
Download to read offline
Basics of Qt



Andreas Jakl
Senior Technical Consultant
Forum Nokia

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




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


                  Signals
                    signal1                                                             Signals

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


                          Show an about dialog
                          and then maximize the
                          window



                          Exit the application
Example: Connections                   QApplication
                                          app

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

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

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

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

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

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

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

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




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




                  Signals                   Signals
                  valueChanged(int)         valueChanged(int)

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

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

    QHBoxLayout* layout = new QHBoxLayout(win);

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

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

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

    spin->setValue(50);

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

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

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




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

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




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

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

 public slots:
     void setValue(int value);

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

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

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

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

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

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

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

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

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




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




                QLayout                   QWidget                  QImage



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


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

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

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


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

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

More Related Content

What's hot

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
 
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
 
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
 
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
 
Qt Internationalization
Qt InternationalizationQt Internationalization
Qt InternationalizationICS
 
Qt Technical Presentation
Qt Technical PresentationQt Technical Presentation
Qt Technical PresentationDaniel Rocha
 
Introduction to Qt Creator
Introduction to Qt CreatorIntroduction to Qt Creator
Introduction to Qt CreatorQt
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programmingICS
 
Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QMLAlan Uthoff
 
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
 
Meet Qt 6.0
Meet Qt 6.0 Meet Qt 6.0
Meet Qt 6.0 Qt
 
Introduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene GraphIntroduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene GraphICS
 
Qt and QML performance tips & tricks for Qt 4.7
Qt and QML performance tips & tricks for Qt 4.7Qt and QML performance tips & tricks for Qt 4.7
Qt and QML performance tips & tricks for Qt 4.7Pasi Kellokoski
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QMLICS
 

What's hot (20)

QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong? QThreads: Are You Using Them Wrong?
QThreads: Are You Using Them Wrong?
 
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
 
Qt for beginners
Qt for beginnersQt for beginners
Qt for beginners
 
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
 
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
 
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
 
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
 
Qt Internationalization
Qt InternationalizationQt Internationalization
Qt Internationalization
 
Qt Technical Presentation
Qt Technical PresentationQt Technical Presentation
Qt Technical Presentation
 
Qt programming-using-cpp
Qt programming-using-cppQt programming-using-cpp
Qt programming-using-cpp
 
Introduction to Qt Creator
Introduction to Qt CreatorIntroduction to Qt Creator
Introduction to Qt Creator
 
Introduction to Qt programming
Introduction to Qt programmingIntroduction to Qt programming
Introduction to Qt programming
 
Basics of Model/View Qt programming
Basics of Model/View Qt programmingBasics of Model/View Qt programming
Basics of Model/View Qt programming
 
Introduction to QML
Introduction to QMLIntroduction to QML
Introduction to QML
 
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
 
Meet Qt 6.0
Meet Qt 6.0 Meet Qt 6.0
Meet Qt 6.0
 
Introduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene GraphIntroduction to the Qt Quick Scene Graph
Introduction to the Qt Quick Scene Graph
 
Qt and QML performance tips & tricks for Qt 4.7
Qt and QML performance tips & tricks for Qt 4.7Qt and QML performance tips & tricks for Qt 4.7
Qt and QML performance tips & tricks for Qt 4.7
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QML
 

Viewers also liked

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
 

Viewers also liked (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
 

Similar to 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
 

Similar to 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
 

More from 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
 

More from 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
 

Recently uploaded

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 

Recently uploaded (20)

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 

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