qt designer widgets - ade malsasa akbar · module: intro to qt developing a hello world application...

128
Qt Designer Widgets Qt 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

Upload: hoangtuyen

Post on 06-Nov-2018

234 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

Page 2: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Part 1

Intro to Qt

Objects in Qt

2/96

Page 3: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

Intro to Qt 3/96

Page 4: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Module: Intro to Qt

Developing a Hello World ApplicationHello World using Qt Creator

Intro to Qt Developing a Hello World Application 4/96

Page 5: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

“Hello World” in Qt

// main.cpp

#include <QtGui>

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

Page 6: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Project File - helloworld.pro

• helloworld.pro file• lists source and header files• provides project configuration

# File: helloworld.proSOURCES = main.cppHEADERS += # No headers used

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

See qmake tutorial Documentation

Intro to Qt Developing a Hello World Application 6/96

Page 7: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Using qmake

• qmake tool• Creates cross-platform make-files

• Build project using qmakecd helloworldqmake helloworld.pro # creates Makefilemake # 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

Page 8: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Module: Intro to Qt

Developing a Hello World ApplicationHello World using Qt Creator

Intro to Qt Hello World using Qt Creator 8/96

Page 9: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

Page 10: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Overview of Qt Creator Components

See Creator Quick Tour Documentation

Intro to Qt Hello World using Qt Creator 10/96

Page 11: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Finding Code -Locator

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

Locator Prefixes• : <class name> - Go to a symbol definition• l <line number> - Go to a line in the current document• ? <help topic> - Go to a help topic• o <open document> - Go to an opened document

See Navigating Around Your Code with Locator Documentation

Intro to Qt Hello World using Qt Creator 11/96

Page 12: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Debugging an Application

• Debug −> Start Debugging (or F5)

See Qt Creator and Debugging Documentation

Intro to Qt Hello World using Qt Creator 12/96

Page 13: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Qt Creator Demo "Hello World"

What we’ll show:• Creation

of an empty Qt project• Adding themain.cpp source file

• Writing of theQt 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

Page 14: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Module: Objects in QtCommon Features of Qt’s Object ModelObject Communication using Signals & SlotsSignal/Slot VariationsHandling Events in Qt

Objects in Qt 14/96

Page 15: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

Page 16: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Module: Objects in Qt

Common Features of Qt’s Object ModelObject Communication using Signals & SlotsSignal/Slot VariationsHandling Events in Qt

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

Page 17: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

Page 18: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Object Tree

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

QObject

QObject

QObject

Children

Parent• 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

Page 19: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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 Documentation

QString 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 lifetime

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

Page 20: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Qt’s Widget Model - QWidget

QLabel

QFile

QPushButton

QTextEdit

QWidget

QObject• 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

Page 21: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

Page 22: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Widgets that contain other widgets

• Container Widget• Aggregates other child-widgets

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

• 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

Page 23: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Example Container Widget

// container (window) widget creationQWidget container; // top-level widget on stackQLabel* label = new QLabel("Note:", &container);QTextEdit* edit = new QTextEdit(&container);QPushButton* clear = new QPushButton("Clear", &container);QPushButton* save = new QPushButton("Save", &container);

// widget layoutQVBoxLayout* 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

Page 24: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

Page 25: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

Page 26: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

Page 27: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

Page 28: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

Page 29: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

Page 30: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

Page 31: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Module: Objects in Qt

Common Features of Qt’s Object ModelObject Communication using Signals & SlotsSignal/Slot VariationsHandling Events in Qt

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

Page 32: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Callbacks

General ProblemHow 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

Page 33: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

Page 34: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Connecting Signals to Slots

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

Page 35: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Connecting Signals to Slots

Signal emitted

4242

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

Page 36: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Connecting Signals to Slots

Slot implemented

4242

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

Page 37: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Connecting Signals to Slots

Signal/Slot connection

4242 4242

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

Page 38: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Connecting Signals to Slots

4242 4242

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

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

Page 39: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Connecting Signals to Slots

4242 4242

void QSlider::mousePressEvent(...){ ... emit valueChanged( newValue ); ...}

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

Page 40: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Connecting Signals to Slots

4242 4242

void QSlider::setValue( int value ){ ... m_value = value; ...}

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

Page 41: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Connecting Signals to Slots

Signal emitted Slot implemented

Signal/Slot connection

4242 4242

void QSlider::mousePressEvent(...){ ... emit valueChanged( newValue ); ...}

void QSlider::setValue( int value ){ ... m_value = value; ...}

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

Demo objects/ex-connect

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

Page 42: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Custom Slots• File: myclass.h

class 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

Page 43: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Example of Custom Slots

• 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

Page 44: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Custom Signals

• 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

Page 45: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Q_OBJECT - flag for MOC

• Q_OBJECT• Enhances QObject with meta-object information• Required for Signals & Slots• moc creates meta-object information

moc -o moc_myclass.cpp myclass.hc++ -c myclass.cpp; c++ -c moc_myclass.cppc++ -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

Page 46: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Back to the Original Problem

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

Page 47: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Lab: Connect to Click

• 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: seeQPalette)

Lab objects/lab-selectcolor

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

Page 48: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Module: Objects in Qt

Common Features of Qt’s Object ModelObject Communication using Signals & SlotsSignal/Slot VariationsHandling Events in Qt

Objects in Qt Signal/Slot Variations 36/96

Page 49: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Variations of Signal/Slot Connections

Signal(s) Connect to Slot(s)one

√many

many√

oneone

√another signal

• Signal to Signal connectionconnect(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

Page 50: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Making the Connection

Rule for Signal/Slot ConnectionCan 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

Page 51: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Making the Connection

Rule for Signal/Slot ConnectionCan 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

Page 52: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Making the Connection

Rule for Signal/Slot ConnectionCan 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

Page 53: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Making the Connection

Rule for Signal/Slot ConnectionCan 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

Page 54: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Making the Connection

Rule for Signal/Slot ConnectionCan 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

Page 55: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Making the Connection

Rule for Signal/Slot ConnectionCan 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

Page 56: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Making the Connection

Rule for Signal/Slot ConnectionCan 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

Page 57: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Making the Connection

Rule for Signal/Slot ConnectionCan 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

Page 58: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Making the Connection

Rule for Signal/Slot ConnectionCan 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

Page 59: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Making the Connection

Rule for Signal/Slot ConnectionCan 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

Page 60: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Making the Connection

Rule for Signal/Slot ConnectionCan 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

Page 61: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Questions And Answers

• 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

Page 62: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Questions And Answers

• 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

Page 63: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Questions And Answers

• 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

Page 64: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Questions And Answers

• 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

Page 65: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Questions And Answers

• 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

Page 66: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Questions And Answers

• 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

Page 67: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Questions And Answers

• 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

Page 68: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Questions And Answers

• 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

Page 69: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Lab: Source Compatibility

• 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

Page 70: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Module: Objects in Qt

Common Features of Qt’s Object ModelObject Communication using Signals & SlotsSignal/Slot VariationsHandling Events in Qt

Objects in Qt Handling Events in Qt 41/96

Page 71: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Event Processing

Qt is an event-driven UI toolkitQApplication::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

Page 72: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Event Handling

• 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

Page 73: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Example of Event Handling

• QCloseEvent delivered to top level widgets (windows)• Accepting event allows window to close• Ignoring event keeps window open

void 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

Page 74: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Events and Signals

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

Page 75: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Part 2

Widgets

46/96

Page 76: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Module: Objects in Qt

Qt Designer

Qt Designer 47/96

Page 77: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Qt Designer

• 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

Page 78: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Designer Views

Object InspectorDisplays hierarchy of objects on form

Widget BoxProvides selection of widgets, layouts

Property EditorDisplays properties of selected object

Qt Designer 49/96

Page 79: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Designer’s Editing Modes

• 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

Page 80: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Designer UI Form Files

• Form stored in .ui file• format is XML

• uic tool generates code• From myform.ui

• to ui_myform.h

// ui_mainwindow.hclass Ui_MainWindow {public:QLineEdit *fileName;... // simplified codevoid setupUi(QWidget *) { /* setup widgets */ }

};

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

Qt Designer 51/96

Page 81: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

From .ui to C++

OrderForm.uisaves to

designer(Design Mode from Creator) uic

ui_orderform.horderform.h

orderform.cppclass Ui_OrderForm { public: QVBoxLayout *verticalLayout; QLineEdit *lineEdit; QDoubleSpinBox *doubleSpinBox; QSpinBox *spinBox; [...]#include "orderform.h"

#include "ui_orderform.h"

OrderForm::OrderForm(QWidget *parent) : QWidget(parent), ui(new Ui::OrderForm) { ui->setupUi(this);}

OrderForm::~OrderForm() { delete ui; }

produces

Qt Designer 52/96

Page 82: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Qt Creator - Form Wizards• Add New... "Designer Form"

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

Qt Designer 53/96

Page 83: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Naming Widgets

1 Place widgets on form2 Edit objectName property

• objectName defines member name in generated code

Qt Designer 54/96

Page 84: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Form layout in Designer

• QFormLayout: Suitable for most input forms

Qt Designer 55/96

Page 85: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Top-Level Layout

1 First layout child widgets2 Finally select empty space and set top-level layout

Qt Designer 56/96

Page 86: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Preview Widget in Preview Mode

• Check that widget is nicely resizable

Qt Designer 57/96

Page 87: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Code Integration - Header File

// orderform.hclass 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

Page 88: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Code Integration - Implementation File// orderform.cpp#include "ui_orderform.h"

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

Page 89: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Signals and Slots in Designer

• Widgets are available as public members• 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

Page 90: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Using Custom Widgets in Designer

Choices for Custom Widgets1 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

Page 91: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Dynamically loading .ui files

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

• Disadvantages• Slower, harder to maintain• Risk: .ui file not available at runtimeSee 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<QPushButton*>(this, "okButton");

Demo $QTDIR/examples/designer/calculatorbuilder

• Handle with care!

Qt Designer 62/96

Page 92: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Lab: Designer Order Form

• Create an order form dialog• With fields for price, quantity and total.• Total field updates itself to reflect quantity and price entered

Lab dialogs/lab-orderform

Qt Designer 63/96

Page 93: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Module: WidgetsCommon WidgetsLayout ManagementGuidelines for Custom Widgets

Widgets 64/96

Page 94: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Module Objectives

• Common Widgets• Text widgets• Value based widgets• Organizer widgets• Item based widgtes

• Layout Management• Geometry management• Advantages of layout managers• Qt’s layout managers• Size policies

• Custom Widgets• Rules for creating own widgets

Widgets 65/96

Page 95: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Module: Widgets

Common WidgetsLayout ManagementGuidelines for Custom Widgets

Widgets Common Widgets 66/96

Page 96: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Text Widgets

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

• setPixmap( pixmap ) - as content• QLineEdit

line = 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("<h1>Html Text</h1>");connect(edit, SIGNAL(textChanged(QString)) ...

Widgets Common Widgets 67/96

Page 97: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Button Widgets

• QAbstractButton• Abstract base class of buttons

• QPushButtonbutton = 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 buttonsgroup->setExclusive(true);connect(group, SIGNAL(buttonClicked(QAbstractButton*)) ...

Widgets Common Widgets 68/96

Page 98: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Value Widgets

• QSliderslider = new QSlider(Qt::Horizontal, parent);slider->setRange(0, 99);slider->setValue(42);connect(slider, SIGNAL(valueChanged(int)) ...

• QProgressBarprogress = new QProgressBar(parent);progress->setRange(0, 99);progress->setValue(42);// format: %v for value; %p for percentageprogress->setFormat("%v (%p%)");

• QSpinBoxspin = new QSpinBox(parent);spin->setRange(0, 99);spin->setValue(42);spin->setSuffix(" USD");connect(spin, SIGNAL(valueChanged(int)) ...

Widgets Common Widgets 69/96

Page 99: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Organizer Widgets

• QGroupBoxbox = new QGroupBox("Your Options", parent);// ... 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

Page 100: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Item Widgets

• QComboBoxcombo = new QComboBox(parent);combo->addItem("Option 1", data);connect(combo, SIGNAL(activated(int)) ...QVariant data = combo->itemData(index);

• setCurrentIndex( index )• QListWidget

list = new QListWidget(parent);list->addItem("Item 1");// ownership of items with listitem = 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

Page 101: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Other Widgets

• QToolBox• Column of tabbed widget items

• 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

Page 102: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Module: Widgets

Common WidgetsLayout ManagementGuidelines for Custom Widgets

Widgets Layout Management 73/96

Page 103: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Doing it Yourself

• Place and resize widgets• move()• 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

Page 104: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Making Qt do the Work

DefinitionLayout: Specifying the relations of elements to each otherinstead 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

Page 105: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Managed Widgets and Sizes

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

• Preferred• Override

• sizeHint()• minimumSizeHint()

• Or call• setFixedSize()• setMinimumSize()• setMaximumSize()

Widgets Layout Management 76/96

Page 106: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Layout Management Classes

• QHBoxLayout• Lines up widgets horizontally

• 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

Page 107: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

QHBoxLayout and QVBoxLayout

• Lines up widgets horizontally or vertically• Divides space into boxes• 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 ( Seecreate[H,V]BoxLayout() )

Widgets Layout Management 78/96

Page 108: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Widgets in a grid - QGridLayout

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

QGridLayout* layout = new QGridLayout;layout->addWidget(one, 0, 0); // row:0, col:0layout->addWidget(two, 0, 1); // row:0, col:1// row:1, col:0, rowSpan:1, colSpan:2layout->addWidget(three, 1, 0, 1, 2);

window->setLayout(layout)

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

• No need to specifyrows and columns before adding children.

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

Widgets Layout Management 79/96

Page 109: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

QFormLayout

• A two-column layout• Column 1 a label (as annotation)• 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

Page 110: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Lab: Contact Form

• Specified by graphic designer• Your task: implement it• 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

Firstname Lastname

Zip-Code Town

Picture(128x128)

Contact

Details

[ ] Show Details

Widgets Layout Management 81/96

Page 111: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Some Layout Terms

• Stretch• Relative resize factor• 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

Page 112: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

More Layout Terms

• Strut• Limits perpendicular box dimension• e.g. height for QHBoxLayout• 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

Page 113: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Widgets Size Policies

• QSizePolicy describes interest of widget in resizingQSizePolicy policy = widget->sizePolicy();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

Page 114: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Available Size PoliciesPolicy sizeHint() Widget

Fixedauthoritative can not grow or shrink

Minimumminimal, suffi-cient

can expand, no advantage ofbeing larger

Maximumis maximum can shrink

Preferredis best can shrink, no advantage of

being larger

MinimumExpanding

is minimum can use extra space

Expandingsensible size can grow and shrink

Widgets Layout Management 85/96

Page 115: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Lab: Layout of buttons

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

• Make buttons resize vertically when making the window higher.

Lab widgets/lab-layoutbuttons

Widgets Layout Management 86/96

Page 116: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Questions And Answers

• How do you change the minimum size of a widget?• Name the available layout managers.• How do you specify stretch?• When are you allowed to call resize and move on a widget?

Widgets Layout Management 87/96

Page 117: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Questions And Answers

• How do you change the minimum size of a widget?• Name the available layout managers.• How do you specify stretch?• When are you allowed to call resize and move on a widget?

Widgets Layout Management 87/96

Page 118: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Questions And Answers

• How do you change the minimum size of a widget?• Name the available layout managers.• How do you specify stretch?• When are you allowed to call resize and move on a widget?

Widgets Layout Management 87/96

Page 119: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Questions And Answers

• How do you change the minimum size of a widget?• Name the available layout managers.• How do you specify stretch?• When are you allowed to call resize and move on a widget?

Widgets Layout Management 87/96

Page 120: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Module: Widgets

Common WidgetsLayout ManagementGuidelines for Custom Widgets

Widgets Guidelines for Custom Widgets 88/96

Page 121: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Guidelines: Creating a Custom Widget

• It’s as easy as deriving from QWidgetclass CustomWidget : public QWidget{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

Page 122: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

• See Widget Gallery Documentation

• Decide on a base class• 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

Page 123: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Guidelines: Drawing a Widget

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

• 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

Page 124: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Guidelines: Internal States and Subclassing

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

• 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

Page 125: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Guidelines: Widget Constructor

• Decide on parameters at construction time• Enrich the constructor as necessary• Or implement more than one constructor• 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

Page 126: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

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

• Choose File• 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

Page 127: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

Lab: Compass Widget

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

• north, west, south, east• 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

Page 128: Qt Designer Widgets - Ade Malsasa Akbar · Module: Intro to Qt Developing a Hello World Application Hello World using Qt Creator Intro to Qt Developing a Hello World Application 4/96

c© 2010 Nokia Corporation and its subsidiary(-ies).

Nokia, the Nokia logo, Qt, and the Qt logo are trademarks of NokiaCorporation and/or its subsidiaries in Finland and other countries. Allother company, product, or service names may be trademarks orservice marks of others and are the property of their respectiveowners. The use of the word partner does not imply a partnershiprelationship between Nokia and any other company.

Widgets Legal 96/96