Qt Designer Widgets

download Qt Designer Widgets

of 128

Transcript of Qt Designer Widgets

  • 8/18/2019 Qt Designer Widgets

    1/128

    Qt Designer WidgetsQt Essentials - Training Course

    Presented by ics.com

    Visit us at  http://www.ics.com/learning/training/

    Produced by Nokia, Qt Development Frameworks

    Material based on Qt 4.7, created on March 16, 2011

    http://www.ics.com/learning/training/http://www.ics.com/learning/training/

  • 8/18/2019 Qt Designer Widgets

    2/128

    Part 1

    Intro to Qt

    Objects in Qt

    2/96

  • 8/18/2019 Qt Designer Widgets

    3/128

    Module: Intro to QtDeveloping a Hello World ApplicationHello World using Qt Creator

    Intro to Qt   3/96

  • 8/18/2019 Qt Designer Widgets

    4/128

    Module: Intro to Qt

    Developing a Hello World Application

    Hello World using Qt Creator

    Intro to Qt Developing a Hello World Application   4/96

  • 8/18/2019 Qt Designer Widgets

    5/128

    “Hello World” in Qt

    // main.cpp

    #include  

    int   main(int   argc,   char   *argv[])

    {

    QApplication   app(argc, argv);

    QPushButton   button("Hello world");button.show();

    return   app.exec();

    }

    •  Program consists of•   main.cpp - application code•   helloworld.pro - project file

    Demo fundamentals/ex-helloworld

    Intro to Qt Developing a Hello World Application   5/96

    http://fundamentals/ex-helloworldhttp://fundamentals/ex-helloworld

  • 8/18/2019 Qt Designer Widgets

    6/128

    Project File -  helloworld.pro

    •   helloworld.pro file•

     lists source and header files•  provides project configuration

    # File: helloworld.pro

    SOURCES   = main.cpp

    HEADERS   +=   # No headers used

    •  Assignment to variables•  Possible operators  =, +=, -=

    See qmake tutorial Documentation

    Intro to Qt Developing a Hello World Application   6/96

    http://qt.nokia.com/doc/latest/qmake-tutorial.htmlhttp://qt.nokia.com/doc/latest/qmake-tutorial.html

  • 8/18/2019 Qt Designer Widgets

    7/128

    Using qmake

    •   qmake tool•

     Creates cross-platform make-files•  Build project using qmakecd   helloworld

    qmake helloworld.pro   # creates Makefile

    make   # compiles and links application

    ./helloworld   # executes application•   Tip:   qmake -project

    •   Creates default project file based on directory content

    See qmake Manual Documentation

    Qt Creator does it all for you 

    Intro to Qt Developing a Hello World Application   7/96

    http://qt.nokia.com/doc/latest/qmake-manual.htmlhttp://qt.nokia.com/doc/latest/qmake-manual.html

  • 8/18/2019 Qt Designer Widgets

    8/128

    Module: Intro to Qt

    Developing a Hello World Application

    Hello World using Qt Creator

    Intro to Qt Hello World using Qt Creator   8/96

  • 8/18/2019 Qt Designer Widgets

    9/128

    QtCreator IDE

    •  Advanced C++ code editor

    •  Integrated GUI layout and forms designer•  Project and build management tools•  Integrated, context-sensitive help system•  Visual debugger•  Rapid code navigation tools•   Supports

    multipleplatforms

    Intro to Qt Hello World using Qt Creator   9/96

  • 8/18/2019 Qt Designer Widgets

    10/128

    Overview of Qt Creator Components

    See Creator Quick Tour Documentation

    Intro to Qt Hello World using Qt Creator   10/96

    http://doc.qt.nokia.com/qtcreator/creator-quick-tour.htmlhttp://doc.qt.nokia.com/qtcreator/creator-quick-tour.html

  • 8/18/2019 Qt Designer Widgets

    11/128

    Finding Code -Locator

    •  Click on Locator or press Ctrl+K (Mac OS X: Cmd+K)•  Type in the file name•  Press Return

    Locator Prefixes

    •   :  - Go to a symbol definition

    • l  - Go to a line in the current document•   ?  - Go to a help topic•  o  - Go to an opened document

    See Navigating Around Your Code with Locator Documentation

    Intro to Qt Hello World using Qt Creator   11/96

    http://doc.qt.nokia.com/qtcreator/creator-navigation.htmlhttp://doc.qt.nokia.com/qtcreator/creator-navigation.html

  • 8/18/2019 Qt Designer Widgets

    12/128

    Debugging an Application

    •   Debug −> Start Debugging (or  F5)

    See Qt Creator and Debugging Documentation

    Intro to Qt Hello World using Qt Creator   12/96

    http://doc.qt.nokia.com/qtcreator/creator-debugging.htmlhttp://doc.qt.nokia.com/qtcreator/creator-debugging.html

  • 8/18/2019 Qt Designer Widgets

    13/128

    Qt Creator Demo "Hello World"

    What we’ll show:

    •  Creation

    of an empty Qt project•  Adding the

    main.cpp  source file•  Writing of the

    Qt Hello World Code•  Showing Locator Features

    •  Running the application•   Debugging

    the application•  Looking up the  text property of our button

    •  There is more to Qt CreatorSee Qt Creator Manual Documentation

    Intro to Qt Hello World using Qt Creator   13/96

    http://doc.qt.nokia.com/qtcreator/index.htmlhttp://doc.qt.nokia.com/qtcreator/index.html

  • 8/18/2019 Qt Designer Widgets

    14/128

    Module: Objects in Qt

    Common Features of Qt’s Object Model

    Object Communication using Signals & Slots

    Signal/Slot VariationsHandling Events in Qt

    Objects in Qt   14/96

  • 8/18/2019 Qt Designer Widgets

    15/128

    Module Learning Objectives

    •  Learn ...•

     ... about Qt’s object model•  ... about parent-child relationships in Qt•  ... what a widget is•  ... how to combine widgets•  ... what signals & slots are•   ... how to use signals & slots for object communication•   ... which variations for signal/slot connections exist•  ... how to create custom signals & slots•  ... how Qt handles events

    Objects in Qt   15/96

  • 8/18/2019 Qt Designer Widgets

    16/128

    Module: Objects in Qt

    Common Features of Qt’s Object Model

    Object Communication using Signals & SlotsSignal/Slot Variations

    Handling Events in Qt

    Objects in Qt Common Features of Qt’s Object Model   16/96

  • 8/18/2019 Qt Designer Widgets

    17/128

    Qt’s C++ Object Model -  QObject

    •   QObject is the heart of Qt’s object model

    •  Adds features to C++, like ...•   Signals and slots•   Properties•   Event handling•   Memory management•

      ...•  Some features are standard C++•  Some use Qt’s meta-object system

    •   QObject has no visual representation

    Objects in Qt Common Features of Qt’s Object Model   17/96

  • 8/18/2019 Qt Designer Widgets

    18/128

    Object Tree

    •   QObjects organize themselves in object trees•  Based on parent-child relationship

    •   QObject(QObject   *parent = 0)•   Parent adds object to list of children•  Parent owns children

    •   Construction/Destruction•  Tree can be constructured in any order•  Tree can be destroyed in any order

    •   if object has parent: object first removed from parent•   if object has children: deletes each child first•  No object is deleted twice

    Note: Parent-child relationship is NOT inheritance 

    Objects in Qt Common Features of Qt’s Object Model   18/96

  • 8/18/2019 Qt Designer Widgets

    19/128

    Creating Objects

    •  On Heap -  QObject with parent:QLabel

      *label =   new QLabel("Some Text", parent);

    •   QLayout::addWidget() and  QWidget::setLayout() reparentchildren automatically

    •   On Stack -  QObject without parent:•   QFile, usually local to a function•   QApplication (local to main())•  Top level QWidgets:  QMainWindow

    •   On Stack - "value" types   See QVariant::Type DocumentationQString   name;

    QStringList   list;

    QColor   color;

    •  Do not inherit QObject•  Passed by value everywhere•   Exception: QString is implicitly shared (COW strategy)

    •  Stack or Heap -  QDialog - depending on lifetimeObjects in Qt Common Features of Qt’s Object Model   19/96

    http://qt.nokia.com/doc/latest/qvariant.html#Type-enumhttp://qt.nokia.com/doc/latest/qvariant.html#Type-enumhttp://qt.nokia.com/doc/latest/qvariant.html#Type-enumhttp://qt.nokia.com/doc/latest/qvariant.html#Type-enum

  • 8/18/2019 Qt Designer Widgets

    20/128

    Qt’s Widget Model - QWidget

    •  Derived from QObject

    •   Adds visual representation

    •  Base of user interface objects•   Receives events

    •  e.g. mouse, keyboard events

    •  Paints itself on screen•   Using styles

    Objects in Qt Common Features of Qt’s Object Model   20/96

  • 8/18/2019 Qt Designer Widgets

    21/128

    Object Tree and QWidget

    •   new QWidget(0)•  Widget with no parent = "window"

    •  QWidget’s children•  Positioned in parent’s coordinate system•  Clipped by parent’s boundaries

    •  QWidget parent•   Propagates state changes

    •   hides/shows children when it is hidden/shown itself•   enables/disables children when it is enabled/disabled itself

    •   Tristate  mechanism•  For hide/show and enable/disable, ensures that e.g. an explicitly

    hidden child is not shown when the parent is shown.•   Demo objects/ex-showhide

    Objects in Qt Common Features of Qt’s Object Model   21/96

    http://objects/ex-showhidehttp://objects/ex-showhide

  • 8/18/2019 Qt Designer Widgets

    22/128

    Widgets that contain other widgets

    • Container Widget•   Aggregates other child-widgets

    •  Use layouts for aggregation•   In this example:  QHBoxLayout and

    QVBoxLayout

    •  Note: Layouts are not  widgets

    •   Layout Process•  Add widgets to layout•  Layouts may be nested•  Set layout on container widget

    Objects in Qt Common Features of Qt’s Object Model   22/96

  • 8/18/2019 Qt Designer Widgets

    23/128

    Example Container Widget

    // container (window) widget creation

    QWidget   container;   // top-level widget on stack

    QLabel*   label =   new QLabel("Note:", &container);

    QTextEdit*   edit =   new QTextEdit(&container);

    QPushButton*   clear =   new QPushButton("Clear", &container);

    QPushButton*   save =   new QPushButton("Save", &container);

    // widget layout

    QVBoxLayout*   outer =   new QVBoxLayout();

    outer->addWidget(label);

    outer->addWidget(edit);

    QHBoxLayout*   inner =   new QHBoxLayout();

    inner->addWidget(clear);

    inner->addWidget(save);

    container.setLayout(outer);

    outer->addLayout(inner);   // nesting layouts

    Demo objects/ex-simplelayout

    Objects in Qt Common Features of Qt’s Object Model   23/96

    http://objects/ex-simplelayouthttp://objects/ex-simplelayout

  • 8/18/2019 Qt Designer Widgets

    24/128

    Questions And Answers

    •  What is an object tree?

    •   Which pointers to QObjects do you need to keep around?•  What does it mean when a QWidget has no parent?•  Allocate on heap or stack?

    QWidget; QStringList; QApplication; QString;

    QFile

    •   Name some layout managers and when to use them•  What does it mean to nest layouts?

    Objects in Qt Common Features of Qt’s Object Model   24/96

    Q

  • 8/18/2019 Qt Designer Widgets

    25/128

    Questions And Answers

    •  What is an object tree?

    •   Which pointers to QObjects do you need to keep around?•  What does it mean when a QWidget has no parent?•  Allocate on heap or stack?

    QWidget; QStringList; QApplication; QString;

    QFile

    •   Name some layout managers and when to use them•  What does it mean to nest layouts?

    Objects in Qt Common Features of Qt’s Object Model   24/96

    Q i A d A

  • 8/18/2019 Qt Designer Widgets

    26/128

    Questions And Answers

    •  What is an object tree?

    •   Which pointers to QObjects do you need to keep around?•  What does it mean when a QWidget has no parent?•  Allocate on heap or stack?

    QWidget; QStringList; QApplication; QString;

    QFile

    •   Name some layout managers and when to use them•  What does it mean to nest layouts?

    Objects in Qt Common Features of Qt’s Object Model   24/96

    Q ti A d A

  • 8/18/2019 Qt Designer Widgets

    27/128

    Questions And Answers

    •  What is an object tree?

    •   Which pointers to QObjects do you need to keep around?•  What does it mean when a QWidget has no parent?•  Allocate on heap or stack?

    QWidget; QStringList; QApplication; QString;

    QFile

    •   Name some layout managers and when to use them•  What does it mean to nest layouts?

    Objects in Qt Common Features of Qt’s Object Model   24/96

    Q ti A d A

  • 8/18/2019 Qt Designer Widgets

    28/128

    Questions And Answers

    •  What is an object tree?

    •   Which pointers to QObjects do you need to keep around?•  What does it mean when a QWidget has no parent?•  Allocate on heap or stack?

    QWidget; QStringList; QApplication; QString;

    QFile

    •   Name some layout managers and when to use them•  What does it mean to nest layouts?

    Objects in Qt Common Features of Qt’s Object Model   24/96

    Q ti A d A

  • 8/18/2019 Qt Designer Widgets

    29/128

    Questions And Answers

    •  What is an object tree?

    •   Which pointers to QObjects do you need to keep around?•  What does it mean when a QWidget has no parent?•  Allocate on heap or stack?

    QWidget; QStringList; QApplication; QString;

    QFile

    •   Name some layout managers and when to use them•  What does it mean to nest layouts?

    Objects in Qt Common Features of Qt’s Object Model   24/96

    Lab: Your first Qt Application

  • 8/18/2019 Qt Designer Widgets

    30/128

    Lab: Your first Qt Application

    •  Implement the application shown here•  Search the widgets

    •   See Qt Widget Gallery Documentation

    •  ... and choose your os style•   Layouts:  QHBoxLayout, QVBoxLayout

    •   See previous slides how to use them

    •  Optionally•  Provide a window title•  Add Edit, Remove buttons

    •  On the right of list

    •   Use group box to provide list caption

    Lab objects/lab-firstapp

    Objects in Qt Common Features of Qt’s Object Model   25/96

    Module: Objects in Qt

    http://qt.nokia.com/doc/latest/gallery-windowsvista.htmlhttp://objects/lab-firstapphttp://objects/lab-firstapphttp://qt.nokia.com/doc/latest/gallery-windowsvista.html

  • 8/18/2019 Qt Designer Widgets

    31/128

    Module: Objects in Qt

    Common Features of Qt’s Object ModelObject Communication using Signals & SlotsSignal/Slot Variations

    Handling Events in Qt

    Objects in Qt Object Communication using Signals & Slots   26/96

    Callbacks

  • 8/18/2019 Qt Designer Widgets

    32/128

    Callbacks

    General Problem

    How do you get from "the user clicks a button" to your businesslogic?

    •   Possible solutions•   Callbacks

    •  Based on function pointers•   Not type-safe

    •   Observer Pattern (Listener)•  Based on interface classes•   Needs listener registraction•  Many interface classes

    •  Qt uses•  Signals and slots for high-level (semantic) callbacks•  Virtual methods for low-level (syntactic) events.

    Objects in Qt Object Communication using Signals & Slots   27/96

    Signals & Slots

  • 8/18/2019 Qt Designer Widgets

    33/128

    Signals & Slots

    •  Object Communication•   Signal -  emitted to notify other objects •   Slot -  method called in response to signal 

    •  Provides type-safe callbacks•  After getting used to it, they are

    •  easier to use than message maps,•

     more secure than callbacks,•   more flexible than virtual methods

    •  Fosters component-based programming

    Objects in Qt Object Communication using Signals & Slots   28/96

    Connecting Signals to Slots

  • 8/18/2019 Qt Designer Widgets

    34/128

    Connecting Signals to Slots

    Objects in Qt Object Communication using Signals & Slots   29/96

    Connecting Signals to Slots

  • 8/18/2019 Qt Designer Widgets

    35/128

    Connecting Signals to Slots

    Objects in Qt Object Communication using Signals & Slots   29/96

    Connecting Signals to Slots

  • 8/18/2019 Qt Designer Widgets

    36/128

    Connecting Signals to Slots

    Objects in Qt Object Communication using Signals & Slots   29/96

    Connecting Signals to Slots

  • 8/18/2019 Qt Designer Widgets

    37/128

    Connecting Signals to Slots

    Objects in Qt Object Communication using Signals & Slots   29/96

    Connecting Signals to Slots

  • 8/18/2019 Qt Designer Widgets

    38/128

    Connecting Signals to Slots

    Objects in Qt Object Communication using Signals & Slots   29/96

    Connecting Signals to Slots

  • 8/18/2019 Qt Designer Widgets

    39/128

    Connecting Signals to Slots

    Objects in Qt Object Communication using Signals & Slots   29/96

    Connecting Signals to Slots

  • 8/18/2019 Qt Designer Widgets

    40/128

    Connecting Signals to Slots

    Objects in Qt Object Communication using Signals & Slots   29/96

    Connecting Signals to Slots

  • 8/18/2019 Qt Designer Widgets

    41/128

    g g

    Demo objects/ex-connect

    Objects in Qt Object Communication using Signals & Slots   29/96

    Custom Slots

    http://objects/ex-connecthttp://objects/ex-connect

  • 8/18/2019 Qt Designer Widgets

    42/128

    •   File:  myclass.hclass   MyClass :   public QObject

    {Q_OBJECT   // marker for moc

    // ...

    public   slots:

    void   setValue(int   value);   // a custom slot

    };

    •   File:  myclass.cppvoid   MyClass::setValue(int   value) {

    // slot implementation

    }

    Objects in Qt Object Communication using Signals & Slots   30/96

    Example of Custom Slots

  • 8/18/2019 Qt Designer Widgets

    43/128

    p

    •   QTimer is a class for executing functions at a later time.

    •  Connect the QTimer’s signal timeout()

     to a custom slot.•   Call  setSingleShot() for a single-shot timer.•  Finally, call start(int msec) on the timer to start it.•  For a one-time non-cancellable single-shot timer:

    QTimer::singleShot(1000, this, SLOT(doit()))

    Demo objects/ex-stop-watch

    Objects in Qt Object Communication using Signals & Slots   31/96

    Custom Signals

    http://objects/ex-stop-watchhttp://objects/ex-stop-watch

  • 8/18/2019 Qt Designer Widgets

    44/128

    g

    •   File:  myclass.hclass   MyClass :   public QObject

    {

    Q_OBJECT   // marker for moc

    // ...

    signals:

    void   valueChanged(int   value);   // a custom signal

    };

    •   File:  myclass.cpp// No implementation for a signal

    •  Sending a signalemit valueChanged(value);

    Demo objects/ex-quotebutton

    Objects in Qt Object Communication using Signals & Slots   32/96

    Q_OBJECT - flag for MOC

    http://objects/ex-quotebuttonhttp://objects/ex-quotebutton

  • 8/18/2019 Qt Designer Widgets

    45/128

    •   Q_OBJECT•  Enhances QObject with meta-object information

    •   Required for Signals & Slots•   moc creates meta-object information

    moc -o moc_myclass.cpp myclass.h

    c++ -c myclass.cpp; c++ -c moc_myclass.cpp

    c++ -o myapp moc_myclass.o myclass.o

    •   qmake takes care of moc files for you•  Analyze definition of•   Q_OBJECT

    •   signals and  slots•   emit

    •   At $QTDIR/src/corelib/kernel/qobjectdefs.h•  Look at moc generated files

    •   Demo objects/ex-signalslots

    Objects in Qt Object Communication using Signals & Slots   33/96

    Back to the Original Problem

    http://objects/ex-signalslotshttp://objects/ex-signalslots

  • 8/18/2019 Qt Designer Widgets

    46/128

    We asked some slides ago...

    How to react to a button being clicked?

    •   Solution:•  Implement a slot in your widget •  Connect the button’s clicked signal to the slot 

    •  Connect statementconnect(sender, signal, receiver, slot);

    •   Exampleconnect(button, SIGNAL(clicked()),   this, SLOT(onClicked()));

    Objects in Qt Object Communication using Signals & Slots   34/96

    Lab: Connect to Click

  • 8/18/2019 Qt Designer Widgets

    47/128

    •  Create an application as shown here•

     Clicking on “Select Color”updates label with color’s name.

    •   Hints•   QColorDialog::getColor() to fetch a color•   QColor::name() to get the color name

    •   Optional•   In  QColorDialog, honor the user clicking “cancel”, and provide it

    with the current color to start from.•   Set the selected color as the label’s background (Hint: see

    QPalette)

    Lab objects/lab-selectcolor

    Objects in Qt Object Communication using Signals & Slots   35/96

    Module: Objects in Qt

    http://objects/lab-selectcolorhttp://objects/lab-selectcolor

  • 8/18/2019 Qt Designer Widgets

    48/128

    Common Features of Qt’s Object ModelObject Communication using Signals & Slots

    Signal/Slot VariationsHandling Events in Qt

    Objects in Qt Signal/Slot Variations   36/96

    Variations of Signal/Slot Connections

  • 8/18/2019 Qt Designer Widgets

    49/128

    Signal(s) Connect to Slot(s)

    one   √    manymany

      √   one

    one  √ 

      another signal

    • Signal to Signal connection

    connect(bt, SIGNAL(clicked()),   this, SIGNAL(okSignal()));

    •   Not allowed to name parametersconnect( m_slider, SIGNAL( valueChanged( int value ) )

    this, SLOT( setValue( int newValue ) ) )

    Objects in Qt Signal/Slot Variations   37/96

    Making the Connection

  • 8/18/2019 Qt Designer Widgets

    50/128

    Rule for Signal/Slot Connection

    Can ignore arguments, but not create values from nothing

    Signal Slot

    rangeChanged(int,int)

    √   setRange(int,int)√   setValue(int)

    √    updateUi()valueChanged(int)

    √   setValue(int)√   updateUi()

    X    setRange(int,int)X    setValue(float)

    textChanged(QString)   X    setValue(int)

    clicked()

    √   updateUi()

    X    setValue(int)

    Objects in Qt Signal/Slot Variations   38/96

    Making the Connection

  • 8/18/2019 Qt Designer Widgets

    51/128

    Rule for Signal/Slot Connection

    Can ignore arguments, but not create values from nothing

    Signal Slot

    rangeChanged(int,int)

    √   setRange(int,int)√   setValue(int)

    √    updateUi()valueChanged(int)

    √   setValue(int)√   updateUi()

    X    setRange(int,int)X    setValue(float)

    textChanged(QString)   X    setValue(int)

    clicked()

    √   updateUi()

    X    setValue(int)

    Objects in Qt Signal/Slot Variations   38/96

    Making the Connection

  • 8/18/2019 Qt Designer Widgets

    52/128

    Rule for Signal/Slot Connection

    Can ignore arguments, but not create values from nothing

    Signal Slot

    rangeChanged(int,int)

    √   setRange(int,int)√   setValue(int)

    √    updateUi()valueChanged(int)

    √   setValue(int)√   updateUi()

    X    setRange(int,int)X    setValue(float)

    textChanged(QString)   X    setValue(int)

    clicked()

    √   updateUi()

    X    setValue(int)

    Objects in Qt Signal/Slot Variations   38/96

    Making the Connection

  • 8/18/2019 Qt Designer Widgets

    53/128

    Rule for Signal/Slot Connection

    Can ignore arguments, but not create values from nothing

    Signal Slot

    rangeChanged(int,int)

    √   setRange(int,int)√   setValue(int)

    √    updateUi()valueChanged(int)

    √   setValue(int)√   updateUi()

    X    setRange(int,int)X    setValue(float)

    textChanged(QString)   X    setValue(int)

    clicked()

    √   updateUi()

    X    setValue(int)

    Objects in Qt Signal/Slot Variations   38/96

    Making the Connection

  • 8/18/2019 Qt Designer Widgets

    54/128

    Rule for Signal/Slot Connection

    Can ignore arguments, but not create values from nothing

    Signal Slot

    rangeChanged(int,int)

    √   setRange(int,int)√   setValue(int)

    √    updateUi()valueChanged(int)

    √   setValue(int)√   updateUi()

    X    setRange(int,int)X    setValue(float)

    textChanged(QString)   X    setValue(int)

    clicked()

    √   updateUi()

    X    setValue(int)

    Objects in Qt Signal/Slot Variations   38/96

    Making the Connection

  • 8/18/2019 Qt Designer Widgets

    55/128

    Rule for Signal/Slot Connection

    Can ignore arguments, but not create values from nothing

    Signal Slot

    rangeChanged(int,int)

    √   setRange(int,int)√   setValue(int)

    √    updateUi()valueChanged(int)

    √   setValue(int)√   updateUi()

    X    setRange(int,int)X    setValue(float)

    textChanged(QString)   X    setValue(int)

    clicked()

    √   updateUi()

    X    setValue(int)

    Objects in Qt Signal/Slot Variations   38/96

    Making the Connection

  • 8/18/2019 Qt Designer Widgets

    56/128

    Rule for Signal/Slot Connection

    Can ignore arguments, but not create values from nothing

    Signal Slot

    rangeChanged(int,int)

    √   setRange(int,int)√   setValue(int)

    √    updateUi()valueChanged(int)

    √   setValue(int)√   updateUi()

    X    setRange(int,int)X    setValue(float)

    textChanged(QString)   X    setValue(int)

    clicked()

    √   updateUi()

    X    setValue(int)

    Objects in Qt Signal/Slot Variations   38/96

    Making the Connection

  • 8/18/2019 Qt Designer Widgets

    57/128

    Rule for Signal/Slot Connection

    Can ignore arguments, but not create values from nothing

    Signal Slot

    rangeChanged(int,int)

    √   setRange(int,int)√   setValue(int)

    √    updateUi()valueChanged(int)

    √   setValue(int)√   updateUi()

    X    setRange(int,int)X    setValue(float)

    textChanged(QString)   X    setValue(int)

    clicked()

    √   updateUi()

    X    setValue(int)

    Objects in Qt Signal/Slot Variations   38/96

    Making the Connection

  • 8/18/2019 Qt Designer Widgets

    58/128

    Rule for Signal/Slot Connection

    Can ignore arguments, but not create values from nothing

    Signal Slot

    rangeChanged(int,int)

    √   setRange(int,int)√   setValue(int)

    √    updateUi()valueChanged(int)

    √   setValue(int)√   updateUi()

    X    setRange(int,int)X    setValue(float)

    textChanged(QString)   X    setValue(int)

    clicked()

    √   updateUi()

    X    setValue(int)

    Objects in Qt Signal/Slot Variations   38/96

    Making the Connection

  • 8/18/2019 Qt Designer Widgets

    59/128

    Rule for Signal/Slot Connection

    Can ignore arguments, but not create values from nothing

    Signal Slot

    rangeChanged(int,int)

    √   setRange(int,int)√   setValue(int)

    √    updateUi()valueChanged(int)

    √   setValue(int)√   updateUi()

    X    setRange(int,int)X    setValue(float)

    textChanged(QString)   X    setValue(int)

    clicked()

    √   updateUi()

    X    setValue(int)

    Objects in Qt Signal/Slot Variations   38/96

    Making the Connection

  • 8/18/2019 Qt Designer Widgets

    60/128

    Rule for Signal/Slot Connection

    Can ignore arguments, but not create values from nothing

    Signal Slot

    rangeChanged(int,int)

    √   setRange(int,int)√   setValue(int)

    √    updateUi()valueChanged(int)

    √   setValue(int)√   updateUi()

    X    setRange(int,int)X    setValue(float)

    textChanged(QString)   X    setValue(int)

    clicked()

    √   updateUi()

    X    setValue(int)

    Objects in Qt Signal/Slot Variations   38/96

    Questions And Answers

  • 8/18/2019 Qt Designer Widgets

    61/128

    •  How do you connect a signal to a slot?

    • How would you implement a slot?

    •  Name some possible signal/slot connection combinations?•  How would you emit a signal?•  Do you need a class to implement a slot?

    • Can you return a value from a slot?

    •  When do you need to run  qmake?•  Where do you place the Q_OBJECT macro and when do you

    need it?

    Objects in Qt Signal/Slot Variations   39/96

    Questions And Answers

    H d i l l ?

  • 8/18/2019 Qt Designer Widgets

    62/128

    •  How do you connect a signal to a slot?

    • How would you implement a slot?

    •  Name some possible signal/slot connection combinations?•  How would you emit a signal?•  Do you need a class to implement a slot?

    • Can you return a value from a slot?

    •  When do you need to run  qmake?•  Where do you place the Q_OBJECT macro and when do you

    need it?

    Objects in Qt Signal/Slot Variations   39/96

    Questions And Answers

    H d t i l t l t?

  • 8/18/2019 Qt Designer Widgets

    63/128

    •  How do you connect a signal to a slot?

    • How would you implement a slot?

    •  Name some possible signal/slot connection combinations?•  How would you emit a signal?•  Do you need a class to implement a slot?

    • Can you return a value from a slot?

    •  When do you need to run  qmake?•  Where do you place the Q_OBJECT macro and when do you

    need it?

    Objects in Qt Signal/Slot Variations   39/96

    Questions And Answers

    H d t i l t l t?

  • 8/18/2019 Qt Designer Widgets

    64/128

    •  How do you connect a signal to a slot?

    • How would you implement a slot?

    •  Name some possible signal/slot connection combinations?•  How would you emit a signal?•  Do you need a class to implement a slot?

    • Can you return a value from a slot?

    •  When do you need to run  qmake?•  Where do you place the Q_OBJECT macro and when do you

    need it?

    Objects in Qt Signal/Slot Variations   39/96

    Questions And Answers

    Ho do o connect a signal to a slot?

  • 8/18/2019 Qt Designer Widgets

    65/128

    •  How do you connect a signal to a slot?

    • How would you implement a slot?

    •  Name some possible signal/slot connection combinations?•  How would you emit a signal?•  Do you need a class to implement a slot?

    • Can you return a value from a slot?

    •  When do you need to run  qmake?•  Where do you place the Q_OBJECT macro and when do you

    need it?

    Objects in Qt Signal/Slot Variations   39/96

  • 8/18/2019 Qt Designer Widgets

    66/128

    Questions And Answers

    • How do you connect a signal to a slot?

  • 8/18/2019 Qt Designer Widgets

    67/128

    •  How do you connect a signal to a slot?

    • How would you implement a slot?

    •  Name some possible signal/slot connection combinations?•  How would you emit a signal?•  Do you need a class to implement a slot?

    • Can you return a value from a slot?

    •  When do you need to run  qmake?•  Where do you place the Q_OBJECT macro and when do you

    need it?

    Objects in Qt Signal/Slot Variations   39/96

    Questions And Answers

    • How do you connect a signal to a slot?

  • 8/18/2019 Qt Designer Widgets

    68/128

    •  How do you connect a signal to a slot?

    • How would you implement a slot?

    •  Name some possible signal/slot connection combinations?•  How would you emit a signal?•  Do you need a class to implement a slot?

    • Can you return a value from a slot?

    •  When do you need to run  qmake?•  Where do you place the Q_OBJECT macro and when do you

    need it?

    Objects in Qt Signal/Slot Variations   39/96

    Lab: Source Compatibility

  • 8/18/2019 Qt Designer Widgets

    69/128

    •  Implement custom slider•  API compatible with  QSlider•   Shows current value of slider

    •  To create custom slider•   use QSlider and  QLabel

    •  To test slider•

      main.cpp provides test code•   QLCDNumber is part of test code

    •   Optional:•   Discuss pros and cons of inheriting from QSlider instead of

    using an instance in a layout.

    Lab objects/lab-slider

    Objects in Qt Signal/Slot Variations   40/96

    Module: Objects in Qt

    Common Features of Qt’s Object Model

    http://objects/lab-sliderhttp://objects/lab-slider

  • 8/18/2019 Qt Designer Widgets

    70/128

    Common Features of Qt s Object ModelObject Communication using Signals & Slots

    Signal/Slot VariationsHandling Events in Qt

    Objects in Qt Handling Events in Qt   41/96

    Event Processing

    Q i d i UI lki

  • 8/18/2019 Qt Designer Widgets

    71/128

    Qt is an event-driven UI toolkit

    QApplication::exec()  runs the event loop 

    1   Generate Events•  by input devices: keyboard, mouse, etc.•  by Qt itself (e.g. timers)

    2   Queue Events•  by event loop

    3   Dispatch Events•   by QApplication to receiver:  QObject

    •   Key events sent to widget with focus •   Mouse events sent to widget under cursor 

    4   Handle Events•   by QObject event handler methods

    Objects in Qt Handling Events in Qt   42/96

    Event Handling

    • QObject::event(QEvent *event)

  • 8/18/2019 Qt Designer Widgets

    72/128

    •   QObject::event(QEvent event)•  Handles all events for this object

    •  Specialized event handlers•   QWidget::mousePressEvent() for mouse clicks•   QWidget::keyPressEvent() for key presses

    •  Accepting an Event•   event->accept() /   event->ignore()

      Accepts or ignores the event•  Accepted is the default.

    •  Event propagation•   Happens if event is ignored•   Might be propagated to parent widget

    Demo objects/ex-allevents

    Objects in Qt Handling Events in Qt   43/96

    Example of Event Handling

    • QCloseEvent delivered to top level widgets (windows)

    http://objects/ex-alleventshttp://objects/ex-allevents

  • 8/18/2019 Qt Designer Widgets

    73/128

    •   QCloseEvent delivered to top level widgets (windows)

    • Accepting event allows window to close

    •  Ignoring event keeps window openvoid   MyWidget::closeEvent(QCloseEvent   *event) {

    if   (maybeSave()) {

    writeSettings();

    event->accept();   // close window

    }   else   {

    event->ignore();   // keep window

    }

    }

    Demo objects/ex-closeevent

    Objects in Qt Handling Events in Qt   44/96

    Events and Signals

    Signals and slots are used instead of events:

    http://objects/ex-closeeventhttp://objects/ex-closeevent

  • 8/18/2019 Qt Designer Widgets

    74/128

    Signals and slots are used instead of events:

    • To communicate between components.

    •  In cases where there is a well-defined sender and receiver.•   For example: a button and a slot to handle clicks.

    •   For some events, there is no sender in Qt.•  For example: redraw, keyboard and mouse events.

    •  To describe high level logic and control flow.Developers can create custom events if they need to.

    Objects in Qt Handling Events in Qt   45/96

    Part 2

  • 8/18/2019 Qt Designer Widgets

    75/128

    Widgets

    46/96

    Module: Objects in Qt

    Qt Designer

  • 8/18/2019 Qt Designer Widgets

    76/128

    Qt Designer

    Qt Designer   47/96

    Qt Designer

  • 8/18/2019 Qt Designer Widgets

    77/128

    •  Design UI forms visually

    •  Visual Editor for•   Signal/slot connections•   Actions•

     Tab handling•   Buddy widgets•  Widget properties•   Integration of custom widgets•   Resource files

    Qt Designer   48/96

    Designer Views

  • 8/18/2019 Qt Designer Widgets

    78/128

    Qt Designer   49/96

    Designer’s Editing Modes

    • Widget Editing

  • 8/18/2019 Qt Designer Widgets

    79/128

      Widget Editing•  Change appearance of form

    •  Add layouts•  Edit properties of widgets

    •   Signal and Slots Editing•   Connect widgets together with signals & slots

    •   Buddy Editing•   Assign buddy widgets to label•  Buddy widgets help keyboard focus handling correctly 

    •   Tab Order Editing•   Set order for widgets to receive the keyboard focus

    Qt Designer   50/96

    Designer UI Form Files

    •  Form stored in .ui file

  • 8/18/2019 Qt Designer Widgets

    80/128

    •   format is XML

    •   uic tool generates code•   From myform.ui

    •   to ui_myform.h

    // ui_mainwindow.h

    class   Ui_MainWindow {

    public:QLineEdit   *fileName;

    ...   // simplified code

    void   setupUi(QWidget   *) {   /*   setup widgets   */   }

    };

    •   Form ui file in project (.pro)•   FORMS += mainwindow.ui

    Qt Designer   51/96

    From .ui to C++

  • 8/18/2019 Qt Designer Widgets

    81/128

    Qt Designer   52/96

    Qt Creator - Form Wizards

    •   Add New...  "Designer Form"• or "Designer Form Class" (for C++ integration)

  • 8/18/2019 Qt Designer Widgets

    82/128

    •  or Designer Form Class (for C++ integration)

    Qt Designer   53/96

    Naming Widgets

    1   Place widgets on form

  • 8/18/2019 Qt Designer Widgets

    83/128

    2   Edit objectName property

    •   objectName defines member name in generated code 

    Qt Designer   54/96

    Form layout in Designer

    •   QFormLayout: Suitable for most input forms

  • 8/18/2019 Qt Designer Widgets

    84/128

    Qt Designer   55/96

    Top-Level Layout

    1   First layout child widgets

  • 8/18/2019 Qt Designer Widgets

    85/128

    2   Finally select empty space and set top-level layout

    Qt Designer   56/96

    Preview Widget in Preview Mode

    •  Check that widget is nicely resizable

  • 8/18/2019 Qt Designer Widgets

    86/128

    Qt Designer   57/96

    Code Integration - Header File

    // orderform.h

    class Ui OrderForm

  • 8/18/2019 Qt Designer Widgets

    87/128

    class   Ui_OrderForm;

    class   OrderForm :   public QDialog   {

    private:

    Ui_OrderForm   *ui;   // pointer to UI object

    };

    • "Your Widget" derives from appropriate base class

    •   *ui member encapsulate UI class•  Makes header independent of designer generated code

    Qt Designer   58/96

    Code Integration - Implementation File

    // orderform.cpp

    #include   "ui_orderform.h"

  • 8/18/2019 Qt Designer Widgets

    88/128

    OrderForm::OrderForm(QWidget   *parent):   QDialog(parent), ui(new   Ui_OrderForm) {

    ui->setupUi(this);

    }

    OrderForm::~OrderForm() {

    delete   ui; ui=0;}

    •  Default behavior in Qt Creator 

    Qt Designer   59/96

    Signals and Slots in Designer

    •  Widgets are available as public members• ui->fileName->setText("image.png")

  • 8/18/2019 Qt Designer Widgets

    89/128

    •   ui >fileName >setText( image.png )•   Name based on widgets object name 

    •  You can set up signals & slots traditionally...•   connect(ui->okButton, SIGNAL(clicked()), ...

    •  Auto-connection facility for custom slots•   Automatically connect signals to slots in your code

    •   Based on object name and signal•   void on_objectName_signal( parameters);

    •   Example:  on_okButton_clicked() slot

    •   See Automatic Connections Documentation

    •   Qt Creator: right-click on widget and "Go To Slot"•   Generates a slot using auto-connected name

    Qt Designer   60/96

    Using Custom Widgets in Designer

    Choices for Custom Widgets

    1 Promote to Custom Widget

    http://qt.nokia.com/doc/latest/designer-using-a-ui-file.html#automatic-connectionshttp://qt.nokia.com/doc/latest/designer-using-a-ui-file.html#automatic-connections

  • 8/18/2019 Qt Designer Widgets

    90/128

    1   Promote to Custom Widget 

    •  Choose the widget closest•  From context menu choose

    Promote to Custom Widget •   Code generated will now refer to given class name

    2   Implement a Designer plug-in 

    •   Demo $QTDIR/examples/designer/customwidgetplugin

    •   See Creating Custom Widgets for Qt Designer Documentation

    Qt Designer   61/96

    Dynamically loading .ui files

    •  Forms can be processed at runtime• Produces dynamically generated user interfaces

    http://examples/designer/customwidgetpluginhttp://qt.nokia.com/doc/latest/designer-creating-custom-widgets.htmlhttp://qt.nokia.com/doc/latest/designer-creating-custom-widgets.htmlhttp://examples/designer/customwidgetplugin

  • 8/18/2019 Qt Designer Widgets

    91/128

     Produces dynamically generated user interfaces

    •  Disadvantages•  Slower, harder to maintain•   Risk:  .ui file not available at runtime

    See Run Time Form Processing Documentation

    •   Loading .ui fileQUiLoader   loader;

    QFile   file("forms/textfinder.ui");

    file.open(QFile::ReadOnly);

    QWidget   *formWidget = loader.load(&file,   this);

    •  Locate objects in formui_okButton = qFindChild(this,   "okButton");

    Demo $QTDIR/examples/designer/calculatorbuilder

    •  Handle with care! 

    Qt Designer   62/96

    Lab: Designer Order Form

    •  Create an order form dialog•   With fields for price, quantity and total.

    http://qt.nokia.com/doc/latest/designer-using-a-ui-file.html#run-time-form-processinghttp://examples/designer/calculatorbuilderhttp://examples/designer/calculatorbuilderhttp://qt.nokia.com/doc/latest/designer-using-a-ui-file.html#run-time-form-processing

  • 8/18/2019 Qt Designer Widgets

    92/128

    t e ds o p ce, qua t ty a d tota•   Total field updates itself to reflect quantity and price entered

    Lab dialogs/lab-orderform

    Qt Designer   63/96

    Module: Widgets

    Common Widgets

    Layout Management

    http://dialogs/lab-orderformhttp://dialogs/lab-orderform

  • 8/18/2019 Qt Designer Widgets

    93/128

    Guidelines for Custom Widgets

    Widgets   64/96

  • 8/18/2019 Qt Designer Widgets

    94/128

    Module: Widgets

    Common WidgetsLayout Management

  • 8/18/2019 Qt Designer Widgets

    95/128

    Layout Management

    Guidelines for Custom Widgets

    Widgets Common Widgets   66/96

    Text Widgets

    •   QLabellabel = new QLabel("Text" parent);

  • 8/18/2019 Qt Designer Widgets

    96/128

    label =   new QLabel( Text , parent);

    •   setPixmap( pixmap ) - as content•   QLineEditline =   new QLineEdit(parent);

    line->setText("Edit me");

    line->setEchoMode(QLineEdit::Password);

    connect(line, SIGNAL(textChanged(QString)) ...

    connect(line, SIGNAL(editingFinished()) ...

    •   setInputMask( mask ) -   See Input Mask Documentation

    •   setValidator( validator ) -   See Validator Documentation

    •   QTextEditedit =   new QTextEdit(parent);

    edit->setPlainText("Plain Text");

    edit->append("Html Text");

    connect(edit, SIGNAL(textChanged(QString)) ...

    Widgets Common Widgets   67/96

    Button Widgets

    •   QAbstractButton•  Abstract base class of buttonsQPushButton

    http://qt.nokia.com/doc/latest/qlineedit.html#inputMask-prophttp://qt.nokia.com/doc/latest/qlineedit.html#setValidatorhttp://qt.nokia.com/doc/latest/qlineedit.html#setValidatorhttp://qt.nokia.com/doc/latest/qlineedit.html#inputMask-prop

  • 8/18/2019 Qt Designer Widgets

    97/128

    •  QPushButton

    button =   new QPushButton("Push Me", parent);button->setIcon(QIcon("images/icon.png"));

    connect(button, SIGNAL(clicked()) ...

    •   setCheckable(bool) - toggle button•   QRadioButton

    radio =   new QRadionButton("Option 1", parent);

    •   QCheckBoxcheck =   new QCheckBox("Choice 1", parent);

    •   QButtonGroup - non-visual button managergroup =   new QButtonGroup(parent);

    group->addButton(button);   // add more buttons

    group->setExclusive(true);

    connect(group, SIGNAL(buttonClicked(QAbstractButton*)) ...

    Widgets Common Widgets   68/96

  • 8/18/2019 Qt Designer Widgets

    98/128

    Organizer Widgets

    •   QGroupBoxbox =   new QGroupBox("Your Options", parent);

  • 8/18/2019 Qt Designer Widgets

    99/128

    // ... set layout and add widgets

    •   setCheckable( bool ) - checkbox in title•   QTabWidget

    tab =   new QTabWidget(parent);

    tab->addWidget(widget, icon,   "Tab 1");

    connect(tab, SIGNAL(currentChanged(int)) ...

    •   setCurrentWidget( widget )•   Displays page assoziated by widget

    •   setTabPosition( position )•   Defines where tabs are drawn

    •   setTabsClosable( bool )•

      Adds close buttons

    Widgets Common Widgets   70/96

    Item Widgets

    •   QComboBoxcombo =   new QComboBox(parent);

  • 8/18/2019 Qt Designer Widgets

    100/128

    p

    combo->addItem("Option 1", data);

    connect(combo, SIGNAL(activated(int)) ...

    QVariant   data = combo->itemData(index);

    •   setCurrentIndex( index )

    •   QListWidgetlist =   new QListWidget(parent);

    list->addItem("Item 1");

    // ownership of items with list

    item =   new QListWidgetItem("Item 2", list);

    item->setCheckState(Qt::Checked);

    connect(list, SIGNAL(itemActivated(QListWidgetItem*)) ...

    •   QListWidgetItem::setData(Qt::UserRole, data)

    •  Other Item Widgets :   QTableWidget, QTreeWidget

    Widgets Common Widgets   71/96

    Other Widgets

    •   QToolBox•   Column of tabbed widget itemsQD t Edit QTi Edit QD t Ti Edit

  • 8/18/2019 Qt Designer Widgets

    101/128

    •  QDateEdit, QTimeEdit, QDateTimeEdit•   Widget for editing date and times

    •   QCalendarWidget•   Monthly calendar widget

    •   QToolButton•  Quick-access button to commands

    •   QSplitter•   Implements a splitter widget

    •   QStackedWidget•  Stack of widgets•  Only one widget visible at a time

    See Widget Classes Documentation

    Widgets Common Widgets   72/96

    Module: Widgets

    Common WidgetsLayout Management

    http://qt.nokia.com/doc/latest/gallery.htmlhttp://qt.nokia.com/doc/latest/gallery.html

  • 8/18/2019 Qt Designer Widgets

    102/128

    Guidelines for Custom Widgets

    Widgets Layout Management   73/96

    Doing it Yourself

    •  Place and resize widgets•   move()

    i ()

  • 8/18/2019 Qt Designer Widgets

    103/128

    •   resize()

    •   setGeometry()

    •   Example:QWidget   *parent =   new QWidget(...);

    parent->resize(400,400);

    QCheckBox   *cb =   new QCheckBox(parent);

    cb->move(10, 10);

    Widgets Layout Management   74/96

    Making Qt do the Work

    Definition

    Layout: Specifying the relations of elements to each other

  • 8/18/2019 Qt Designer Widgets

    104/128

    Layout: Specifying the relations of elements to each other

    instead of the absolute positions and sizes.

    •   Advantages:•  Works with different languages.•  Works with different dialog sizes.•  Works with different font sizes.•  Better to maintain.

    •   Disadvantage•   Need to think about your layout first.

    Thinking about layout is not really a disadvantage! 

    Widgets Layout Management   75/96

    Managed Widgets and Sizes

    •  On managed widgets never call•   setGeometry(), resize(), or move()

  • 8/18/2019 Qt Designer Widgets

    105/128

    •   Preferred•   Override

    •   sizeHint()

    •   minimumSizeHint()

    •   Or call

    •   setFixedSize()

    •   setMinimumSize()

    •   setMaximumSize()

    Widgets Layout Management   76/96

    Layout Management Classes

    •   QHBoxLayout•  Lines up widgets horizontally

  • 8/18/2019 Qt Designer Widgets

    106/128

    •   QVBoxLayout•  Lines up widgets vertically

    •   QGridLayout•  Arranges the widgets in a grid

    •  QFormLayout

    •   Lines up a (label, widget) pairs in two columns.

    •   QStackedLayout•  Arranges widgets in a stack

    •  only topmost is visible

    Widgets Layout Management   77/96

    QHBoxLayout and QVBoxLayout

    •  Lines up widgets horizontally or vertically•  Divides space into boxes

  • 8/18/2019 Qt Designer Widgets

    107/128

    •   Each managed widgets fills in one box

    QWidget*   window =   new QWidget;

    QPushButton*

      one =   new QPushButton("One");

    ...

    QHBoxLayout*   layout =   new QHBoxLayout;

    layout->addWidget(one);

    ...

    window->setLayout(layout);

    example $QTDIR/examples/layouts/basiclayouts  (  See create[H,V]BoxLayout() )

    Widgets Layout Management   78/96

    Widgets in a grid -  QGridLayout

    QWidget*   window =   new QWidget;

    QPushButton*   one =   new QPushButton("One");

    QG idL t l t QG idL t

  • 8/18/2019 Qt Designer Widgets

    108/128

    QGridLayout*

      layout =   new QGridLayout;

    layout->addWidget(one, 0, 0);   // row:0, col:0

    layout->addWidget(two, 0, 1);   // row:0, col:1

    // row:1, col:0, rowSpan:1, colSpan:2

    layout->addWidget(three, 1, 0, 1, 2);

    window->setLayout(layout)

    •   Additional•   setColumnMinimumWidth() (minimum width of column)•   setRowMinimumHeight() (minimum height of row)

    •  No need to specify rows and columns before adding children.

    Demo widgets/ex-layouts ( See createGridLayout() )

    Widgets Layout Management   79/96

    QFormLayout

    •  A two-column layout•  Column 1 a label (as annotation)• Column 2 a widget (as field)

    http://widgets/ex-layoutshttp://widgets/ex-layouts

  • 8/18/2019 Qt Designer Widgets

    109/128

     Column 2 a widget (as field)

    •  Respects style guide of individual platforms.QWidget*   window =   new QWidget();

    QPushButton*   one =   new QPushButton("One");

    ...

    QFormLayout*   layout =   new QFormLayout();

    layout->addRow("One", one);...

    window->setLayout(layout)

    Demo widgets/ex-layouts ( See createFormLayout() )•  Form layout with cleanlooks and mac style

    Widgets Layout Management   80/96

    Lab:  Contact Form 

    •  Specified by graphic designer•  Your task: implement it

    http://widgets/ex-layoutshttp://widgets/ex-layouts

  • 8/18/2019 Qt Designer Widgets

    110/128

    •  Focus on correct layout•  Details disabled by default•   ’Show Details’ enables details

    Optional:

    • Click on Picture•  Lets user choose image•  See lab description

    •  Validate Zip-Code as integersLab widgets/lab-contactform

    Widgets Layout Management   81/96

    Some Layout Terms

    •   Stretch•  Relative resize factor • QBoxLayout::addWidget(widget, stretch)

    http://widgets/lab-contactformhttp://widgets/lab-contactform

  • 8/18/2019 Qt Designer Widgets

    111/128

      QBoxLayout::addWidget(widget, stretch)

    •   QBoxLayout::addStretch(stretch)•   QGridLayout::setRowStretch(row, stretch)

    •   QGridLayout::setColumnStretch(col, stretch)

    •   Contents Margins•   Space reserved around the managed widgets.•   QLayout::setContentsMargins(l,t,r,b)

    •   Spacing•  Space reserved between widgets •   QBoxLayout::addSpacing(size)

    Widgets Layout Management   82/96

    More Layout Terms

    •   Strut•  Limits perpendicular box dimension •  e.g. height for QHBoxLayout

  • 8/18/2019 Qt Designer Widgets

    112/128

    e g e g t o Q o ayout•  Only for box layouts 

    •  Min, max and fixed sizes•   QWidget::setMinimumSize( QSize )

    •   QWidget::setMaximumSize( QSize )

    •   QWidget::setFixedSize( QSize )

    •  Individual width and height contraints also available 

    •   Nested Layouts•  Allows flexible layouts •   QLayout::addLayout(...)

    Widgets Layout Management   83/96

    Widgets Size Policies

    •   QSizePolicy describes interest of widget in resizingQSizePolicy   policy = widget->sizePolicy();

    policy.setHorizontalPolicy(QSizePolicy::Fixed);

  • 8/18/2019 Qt Designer Widgets

    113/128

    policy.setHorizontalPolicy(QSizePolicy::Fixed);

    widget->setSizePolicy(policy);

    •  One policy per direction (horizontal and vertical)•  Button-like widgets set size policy to the following:

    •  may stretch horizontally•   are fixed vertically•   Similar to QLineEdit, QProgressBar, ...

    •  Widgets which provide scroll bars (e.g. QTextEdit)•  Can use additional space•   Work with less than sizeHint()

    •  sizeHint(): recommended size for widget

    Widgets Layout Management   84/96

    Available Size PoliciesPolicy   sizeHint()   Widget

    Fixed  authoritative can not grow or shrink

  • 8/18/2019 Qt Designer Widgets

    114/128

    Minimum   minimal, suffi-cient can expand, no advantage ofbeing larger

    Maximum  is maximum can shrink

    Preferred  is best can shrink, no advantage of

    being largerMinimum

    Expanding

    is minimum can use extra space

    Expanding  sensible size can grow and shrink

    Widgets Layout Management   85/96

    Lab:  Layout of buttons 

    •  Develop the following layouts•  Adjust the layouts as shown below.

  • 8/18/2019 Qt Designer Widgets

    115/128

    •   Optionally:•  Make buttons resize vertically when making the window higher.

    Lab widgets/lab-layoutbuttons

    Widgets Layout Management   86/96

    Questions And Answers

    •   How do you change the minimum size of a widget?•  Name the available layout managers.

    http://widgets/lab-layoutbuttonshttp://widgets/lab-layoutbuttons

  • 8/18/2019 Qt Designer Widgets

    116/128

    •  How do you specify stretch?•  When are you allowed to call resize and  move on a widget?

    Widgets Layout Management   87/96

    Questions And Answers

    •   How do you change the minimum size of a widget?•  Name the available layout managers.

  • 8/18/2019 Qt Designer Widgets

    117/128

    •  How do you specify stretch?•  When are you allowed to call resize and  move on a widget?

    Widgets Layout Management   87/96

    Questions And Answers

    •   How do you change the minimum size of a widget?•  Name the available layout managers.

  • 8/18/2019 Qt Designer Widgets

    118/128

    •  How do you specify stretch?•  When are you allowed to call resize and  move on a widget?

    Widgets Layout Management   87/96

    Questions And Answers

    •   How do you change the minimum size of a widget?•  Name the available layout managers.

  • 8/18/2019 Qt Designer Widgets

    119/128

    •  How do you specify stretch?•  When are you allowed to call resize and  move on a widget?

    Widgets Layout Management   87/96

    Module: Widgets

    Common WidgetsLayout ManagementGuidelines for Custom Widgets

  • 8/18/2019 Qt Designer Widgets

    120/128

    g

    Widgets Guidelines for Custom Widgets   88/96

    Guidelines: Creating a Custom Widget

    •   It’s as easy as deriving from QWidgetclass   CustomWidget :   public QWidget

    {

  • 8/18/2019 Qt Designer Widgets

    121/128

    public:

    explicit   CustomWidget(QWidget*   parent=0);

    }

    •   If you need custom Signal Slots•   add Q_OBJECT

    •  Use layouts to arrange widgets inside, or paint the widgetyourself.

    Widgets Guidelines for Custom Widgets   89/96

    Guidelines: Base class and Event Handlers•  Do not reinvent the wheel

    •   See Widget Gallery Documentation

     Decide on a base class

    http://qt.nokia.com/doc/latest/gallery.htmlhttp://qt.nokia.com/doc/latest/gallery.html

  • 8/18/2019 Qt Designer Widgets

    122/128

    • •   Often QWidget or  QFrame•  Overload needed event handlers

    •   Often:•   QWidget::mousePressEvent(),

    QWidget::mouseReleaseEvent()

    •   If widget accepts keyboard input•   QWidget::keyPressEvent()

    •   If widget changes appearance on focus•   QWidget::focusInEvent(),

    QWidget::focusOutEvent()

    Widgets Guidelines for Custom Widgets   90/96

    Guidelines: Drawing a Widget

    •  Decide on composite or draw approach?•   If composite : Use layouts to arrange other widgets•   If draw : implement paint event

    i i

  • 8/18/2019 Qt Designer Widgets

    123/128

    •   Reimplement  QWidget::paintEvent() for drawing•  To draw widget’s visual appearance•   Drawing often depends on internal states

    •  Decide which signals to emit•

     Usually from within event handlers•   Especially mousePressEvent() or  mouseDoubleClickEvent()

    •  Decide carefully on types of signal parameters•  General types increase reusability•   Candidates are  bool, int and  const QString&

    Widgets Guidelines for Custom Widgets   91/96

    Guidelines: Internal States and Subclassing

    •  Decide on publishing internal states•  Which internal states should be made publically accessible?•   Implement accessor methods

    D id hi h h d h ld b l

  • 8/18/2019 Qt Designer Widgets

    124/128

    •  Decide which setter methods should be slots•   Candidates are methods with integral or common parameters

    •  Decide on allowing subclassing•   If yes

      Decide which methods to make protected instead of private•  Which methods to make virtual

    Widgets Guidelines for Custom Widgets   92/96

    Guidelines: Widget Constructor

    •  Decide on parameters at construction time•  Enrich the constructor as necessary•   Or implement more than one constructor• If t i d d f id t t k tl

  • 8/18/2019 Qt Designer Widgets

    125/128

    •   If a parameter is needed for widget to work correctly•   User should be forced to pass it in the constructor

    •  Keep the Qt convention with:explicit   Constructor(...,   QWidget   *parent = 0)

    Widgets Guidelines for Custom Widgets   93/96

    Lab: File Chooser•  Create a reusable file chooser component•   2 Modes

    •   Choose File•

    Ch Di t

  • 8/18/2019 Qt Designer Widgets

    126/128

     Choose Directory•  Think about the Custom Widget Guidelines! •  Create a reusable API for a  FileChooser? 

    Lab widgets/lab-filechooser

    •  After lab discuss your API

    Widgets Guidelines for Custom Widgets   94/96

    Lab: Compass Widget

    •   Implement a “compass widget” and let user ...•  Select a direction

    •  north, west, south, east

    • and optionally none

    http://widgets/lab-filechooserhttp://widgets/lab-filechooser

  • 8/18/2019 Qt Designer Widgets

    127/128

    •   and optionally none•  Provide API to ...

    •  change direction programmatically•   get informed when direction changes

    •  Optional•  Add direction None•  Select direction with the keyboard

    Lab widgets/lab-compasswidget

    Widgets Guidelines for Custom Widgets   95/96

    c

    2010 Nokia Corporation and its subsidiary(-ies).

    http://widgets/lab-compasswidgethttp://widgets/lab-compasswidget

  • 8/18/2019 Qt Designer Widgets

    128/128

    Nokia, the Nokia logo, Qt, and the Qt logo are trademarks of Nokia

    Corporation and/or its subsidiaries in Finland and other countries. All

    other company, product, or service names may be trademarks or

    service marks of others and are the property of their respectiveowners. The use of the word partner does not imply a partnership

    relationship between Nokia and any other company.

    Widgets Legal   96/96