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
Part 1
Intro to Qt
Objects in Qt
2/96
Module: Intro to Qt
Developing a Hello World Application
Hello World using Qt Creator
Intro to Qt
3/96
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
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
Using qmake
qmake tool
Creates cross-platform make-files
Build project using qmake
cd 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
Module: Intro to Qt
Developing a Hello World Application
Hello World using Qt Creator
Intro to Qt
Hello World using Qt Creator
8/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
multiple
platforms
Intro to Qt
Hello World using Qt Creator
9/96
Overview of Qt Creator Components
See Creator Quick Tour Documentation
Intro to Qt
Hello World using Qt Creator
10/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
Debugging an Application
Debug > Start Debugging (or F5)
See Qt Creator and Debugging Documentation
Intro to Qt
Hello World using Qt Creator
12/96
Qt Creator Demo "Hello World"
What well 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 Creator
See Qt Creator Manual Documentation
Intro to Qt
Hello World using Qt Creator
13/96
Module: Objects in Qt
Common Features of Qts Object Model
Object Communication using Signals & Slots
Signal/Slot Variations
Handling Events in Qt
Objects in Qt
14/96
Module Learning Objectives
Learn ...
... about Qts 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
Module: Objects in Qt
Common Features of Qts Object Model
Object Communication using Signals & Slots
Signal/Slot Variations
Handling Events in Qt
Objects in Qt
Common Features of Qts Object Model
16/96
Qts C++ Object Model - QObject
QObject is the heart of Qts object model
Adds features to C++, like ...
Signals and slots
Properties
Event handling
Memory management
...
Some features are standard C++
Some use Qts meta-object system
QObject has no visual representation
Objects in Qt
Common Features of Qts Object Model
17/96
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
Parent
QObject
Children
QObject
QObject
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 Qts Object Model
18/96
Creating Objects
On Heap - QObject with parent:
QLabel *label = new QLabel("Some Text", parent);
QLayout::addWidget() and QWidget::setLayout() reparent
children 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 Qts Object Model
19/96
Qts 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
QObject
QWidget
QLabel
QFile
QTextEdit
QPushButton
Common Features of Qts Object Model
20/96
Object Tree and QWidget
new QWidget(0)
Widget with no parent = "window"
QWidgets children
Positioned in parents coordinate system
Clipped by parents 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 Qts Object Model
21/96
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 Qts Object Model
22/96
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 Qts Object Model
23/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 Qts Object Model
24/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 Qts Object Model
24/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 Qts Object Model
24/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 Qts Object Model
24/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 Qts Object Model
24/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 Qts Object Model
24/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 Qts Object Model
25/96
Module: Objects in Qt
Common Features of Qts Object Model
Object Communication using Signals & Slots
Signal/Slot Variations
Handling Events in Qt
Objects in Qt
Object Communication using Signals & Slots
26/96
Callbacks
General Problem
How do you get from "the user clicks a button" to your business
logic?
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
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
Objects in Qt
Object Communication using Signals & Slots
29/96
Connecting Signals to Slots
42
Signal
emitted
Objects in Qt
Object Communication using Signals & Slots
29/96
Connecting Signals to Slots
42
Slot implemented
Objects in Qt
Object Communication using Signals & Slots
29/96
Connecting Signals to Slots
42
42
Signal/Slot connection
Objects in Qt
Object Communication using Signals & Slots
29/96
Connecting Signals to Slots
42
42
QObject::connect( slider, SIGNAL( valueChanged( int ) ),
spinbox, SLOT( setValue( int ) ) );
Objects in Qt
Object Communication using Signals & Slots
29/96
Connecting Signals to Slots
void QSlider::mousePressEvent(...)
{
...
emit valueChanged( newValue );
...
}
42
Objects in Qt
42
Object Communication using Signals & Slots
29/96
Connecting Signals to Slots
void QSlider::setValue( int value )
{
...
m_value = value;
...
}
42
Objects in Qt
42
Object Communication using Signals & Slots
29/96
Connecting Signals to Slots
void QSlider::mousePressEvent(...)
{
...
emit valueChanged( newValue );
...
}
void QSlider::setValue( int value )
{
...
m_value = value;
...
}
42
Signal
emitted
42
Slot implemented
Signal/Slot connection
QObject::connect( slider, SIGNAL( valueChanged( int ) ),
spinbox, SLOT( setValue( int ) ) );
Demo objects/ex-connect
Objects in Qt
Object Communication using Signals & Slots
29/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.cpp
void MyClass::setValue(int value) {
// slot implementation
}
Objects in Qt
Object Communication using Signals & Slots
30/96
Example of Custom Slots
QTimer is a class for executing functions at a later time.
Connect the QTimers 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
File: myclass.h
class 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 signal
emit valueChanged(value);
Demo objects/ex-quotebutton
Objects in Qt
Object Communication using Signals & Slots
32/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.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
We asked some slides ago...
How to react to a button being clicked?
Solution:
Implement a slot in your widget
Connect the buttons clicked signal to the slot
Connect statement
connect(sender, signal, receiver, slot);
Example
connect(button, SIGNAL(clicked()), this, SLOT(onClicked()));
Objects in Qt
Object Communication using Signals & Slots
34/96
Lab: Connect to Click
Create an application as shown here
Clicking on Select Color
updates label with colors 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 labels background (Hint: see
QPalette)
Lab objects/lab-selectcolor
Objects in Qt
Object Communication using Signals & Slots
35/96
Module: Objects in Qt
Common Features of Qts Object Model
Object Communication using Signals & Slots
Signal/Slot Variations
Handling Events in Qt
Objects in Qt
Signal/Slot Variations
36/96
Variations of Signal/Slot Connections
Signal(s)
one
many
one
Connect to
Slot(s)
many
one
another signal
Signal to Signal connection
connect(bt, SIGNAL(clicked()), this, SIGNAL(okSignal()));
Not allowed to name parameters
connect( m_slider, SIGNAL( valueChanged( int value ) )
this,
SLOT( setValue( int newValue ) ) )
Objects in Qt
Signal/Slot Variations
37/96
Making the Connection
Rule for Signal/Slot Connection
Can ignore arguments, but not create values from nothing
Signal
rangeChanged(int,int)
valueChanged(int)
textChanged(QString)
clicked()
Objects in Qt
X
X
X
Slot
setRange(int,int)
setValue(int)
updateUi()
setValue(int)
updateUi()
setRange(int,int)
setValue(float)
setValue(int)
updateUi()
setValue(int)
Signal/Slot Variations
38/96
Making the Connection
Rule for Signal/Slot Connection
Can ignore arguments, but not create values from nothing
Signal
rangeChanged(int,int)
valueChanged(int)
textChanged(QString)
clicked()
Objects in Qt
X
X
X
Slot
setRange(int,int)
setValue(int)
updateUi()
setValue(int)
updateUi()
setRange(int,int)
setValue(float)
setValue(int)
updateUi()
setValue(int)
Signal/Slot Variations
38/96
Making the Connection
Rule for Signal/Slot Connection
Can ignore arguments, but not create values from nothing
Signal
rangeChanged(int,int)
valueChanged(int)
textChanged(QString)
clicked()
Objects in Qt
X
X
X
Slot
setRange(int,int)
setValue(int)
updateUi()
setValue(int)
updateUi()
setRange(int,int)
setValue(float)
setValue(int)
updateUi()
setValue(int)
Signal/Slot Variations
38/96
Making the Connection
Rule for Signal/Slot Connection
Can ignore arguments, but not create values from nothing
Signal
rangeChanged(int,int)
valueChanged(int)
textChanged(QString)
clicked()
Objects in Qt
X
X
X
Slot
setRange(int,int)
setValue(int)
updateUi()
setValue(int)
updateUi()
setRange(int,int)
setValue(float)
setValue(int)
updateUi()
setValue(int)
Signal/Slot Variations
38/96
Making the Connection
Rule for Signal/Slot Connection
Can ignore arguments, but not create values from nothing
Signal
rangeChanged(int,int)
valueChanged(int)
textChanged(QString)
clicked()
Objects in Qt
X
X
X
Slot
setRange(int,int)
setValue(int)
updateUi()
setValue(int)
updateUi()
setRange(int,int)
setValue(float)
setValue(int)
updateUi()
setValue(int)
Signal/Slot Variations
38/96
Making the Connection
Rule for Signal/Slot Connection
Can ignore arguments, but not create values from nothing
Signal
rangeChanged(int,int)
valueChanged(int)
textChanged(QString)
clicked()
Objects in Qt
X
X
X
Slot
setRange(int,int)
setValue(int)
updateUi()
setValue(int)
updateUi()
setRange(int,int)
setValue(float)
setValue(int)
updateUi()
setValue(int)
Signal/Slot Variations
38/96
Making the Connection
Rule for Signal/Slot Connection
Can ignore arguments, but not create values from nothing
Signal
rangeChanged(int,int)
valueChanged(int)
textChanged(QString)
clicked()
Objects in Qt
X
X
X
Slot
setRange(int,int)
setValue(int)
updateUi()
setValue(int)
updateUi()
setRange(int,int)
setValue(float)
setValue(int)
updateUi()
setValue(int)
Signal/Slot Variations
38/96
Making the Connection
Rule for Signal/Slot Connection
Can ignore arguments, but not create values from nothing
Signal
rangeChanged(int,int)
valueChanged(int)
textChanged(QString)
clicked()
Objects in Qt
X
X
X
Slot
setRange(int,int)
setValue(int)
updateUi()
setValue(int)
updateUi()
setRange(int,int)
setValue(float)
setValue(int)
updateUi()
setValue(int)
Signal/Slot Variations
38/96
Making the Connection
Rule for Signal/Slot Connection
Can ignore arguments, but not create values from nothing
Signal
rangeChanged(int,int)
valueChanged(int)
textChanged(QString)
clicked()
Objects in Qt
X
X
X
Slot
setRange(int,int)
setValue(int)
updateUi()
setValue(int)
updateUi()
setRange(int,int)
setValue(float)
setValue(int)
updateUi()
setValue(int)
Signal/Slot Variations
38/96
Making the Connection
Rule for Signal/Slot Connection
Can ignore arguments, but not create values from nothing
Signal
rangeChanged(int,int)
valueChanged(int)
textChanged(QString)
clicked()
Objects in Qt
X
X
X
Slot
setRange(int,int)
setValue(int)
updateUi()
setValue(int)
updateUi()
setRange(int,int)
setValue(float)
setValue(int)
updateUi()
setValue(int)
Signal/Slot Variations
38/96
Making the Connection
Rule for Signal/Slot Connection
Can ignore arguments, but not create values from nothing
Signal
rangeChanged(int,int)
valueChanged(int)
textChanged(QString)
clicked()
Objects in Qt
X
X
X
Slot
setRange(int,int)
setValue(int)
updateUi()
setValue(int)
updateUi()
setRange(int,int)
setValue(float)
setValue(int)
updateUi()
setValue(int)
Signal/Slot Variations
38/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
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
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
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
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
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
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
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
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
Module: Objects in Qt
Common Features of Qts Object Model
Object Communication using Signals & Slots
Signal/Slot Variations
Handling Events in Qt
Objects in Qt
Handling Events in Qt
41/96
Event Processing
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)
Queue Events
Dispatch Events
by event loop
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)
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)
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
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
Part 2
Widgets
46/96
Module: Objects in Qt
Qt Designer
Qt Designer
47/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
Designer Views
Object Inspector
Displays hierarchy of objects on form
Widget Box
Property Editor
Provides selection of widgets, layouts
Displays properties of selected object
Qt Designer
49/96
Designers 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
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.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++
saves to
OrderForm.ui
designer
(Design Mode from Creator)
orderform.h
uic
ui_orderform.h
produces
class Ui_OrderForm {
public:
QVBoxLayout *verticalLayout;
QLineEdit *lineEdit;
QDoubleSpinBox *doubleSpinBox;
QSpinBox *spinBox;
[...]
orderform.cpp
#include "orderform.h"
#include "ui_orderform.h"
OrderForm::OrderForm(QWidget *parent)
: QWidget(parent), ui(new Ui::OrderForm)
{ ui->setupUi(this);}
OrderForm::~OrderForm()
{ delete ui; }
Qt Designer
52/96
Qt Creator - Form Wizards
Add New... "Designer Form"
or "Designer Form Class" (for C++ integration)
Qt Designer
53/96
Naming Widgets
1
2
Place widgets on form
Edit objectName property
objectName defines member name in generated code
Qt Designer
54/96
Form layout in Designer
QFormLayout: Suitable for most input forms
Qt Designer
55/96
Top-Level Layout
1
First layout child widgets
Finally select empty space and set top-level layout
Qt Designer
56/96
Preview Widget in Preview Mode
Check that widget is nicely resizable
Qt Designer
57/96
Code Integration - Header File
// orderform.h
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"
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")
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
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
Disadvantages
Slower, harder to maintain
Risk: .ui file not available at runtime
See Run Time Form Processing Documentation
Loading .ui file
QUiLoader loader;
QFile file("forms/textfinder.ui");
file.open(QFile::ReadOnly);
QWidget *formWidget = loader.load(&file, this);
Locate objects in form
ui_okButton = qFindChild<QPushButton*>(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.
Total field updates itself to reflect quantity and price entered
Lab dialogs/lab-orderform
Qt Designer
63/96
Module: Widgets
Common Widgets
Layout Management
Guidelines for Custom Widgets
Widgets
64/96
Module Objectives
Common Widgets
Text widgets
Value based widgets
Organizer widgets
Item based widgtes
Layout Management
Geometry management
Advantages of layout managers
Qts layout managers
Size policies
Custom Widgets
Rules for creating own widgets
Widgets
65/96
Module: Widgets
Common Widgets
Layout Management
Guidelines for Custom Widgets
Widgets
Common Widgets
66/96
Text Widgets
QLabel
label = 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
QTextEdit
edit = new QTextEdit(parent);
edit->setPlainText("Plain Text");
edit->append("<h1>Html Text</h1>");
connect(edit, SIGNAL(textChanged(QString)) ...
Widgets
Common Widgets
67/96
Button Widgets
QAbstractButton
Abstract base class of buttons
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);
QCheckBox
check = new QCheckBox("Choice 1", parent);
QButtonGroup - non-visual button manager
group = new QButtonGroup(parent);
group->addButton(button); // add more buttons
group->setExclusive(true);
connect(group, SIGNAL(buttonClicked(QAbstractButton*)) ...
Widgets
Common Widgets
68/96
Value Widgets
QSlider
slider = new QSlider(Qt::Horizontal, parent);
slider->setRange(0, 99);
slider->setValue(42);
connect(slider, SIGNAL(valueChanged(int)) ...
QProgressBar
progress = new QProgressBar(parent);
progress->setRange(0, 99);
progress->setValue(42);
// format: %v for value; %p for percentage
progress->setFormat("%v (%p%)");
QSpinBox
spin = new QSpinBox(parent);
spin->setRange(0, 99);
spin->setValue(42);
spin->setSuffix(" USD");
connect(spin, SIGNAL(valueChanged(int)) ...
Widgets
Common Widgets
69/96
Organizer Widgets
QGroupBox
box = 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
Item Widgets
QComboBox
combo = 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 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 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
Module: Widgets
Common Widgets
Layout Management
Guidelines for Custom Widgets
Widgets
Layout Management
73/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
Making Qt do the Work
Definition
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()
Preferred
Override
sizeHint()
minimumSizeHint()
Or call
setFixedSize()
setMinimumSize()
setMaximumSize()
Widgets
Layout Management
76/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
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 ( See
create[H,V]BoxLayout() )
Widgets
Layout Management
78/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: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)
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)
( See createFormLayout() )
Form layout with cleanlooks and mac style
Demo widgets/ex-layouts
Widgets
Layout Management
80/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
Contact
Firstname
Lastname
Zip-Code
Town
Picture
(128x128)
[ ] Show Details
Details
Lets user choose image
See lab description
Validate Zip-Code as integers
Lab widgets/lab-contactform
Widgets
Layout Management
81/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
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
Widgets Size Policies
QSizePolicy describes interest of widget in resizing
QSizePolicy 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
Available Size Policies
Policy
Fixed
Minimum
Maximum
Preferred
Minimum
Expanding
Expanding
authoritative
Widget
can not grow or shrink
minimal, sufficient
is maximum
can expand, no advantage of
being larger
can shrink
is best
is minimum
can shrink, no advantage of
being larger
can use extra space
sensible size
can grow and shrink
sizeHint()
Widgets
Layout Management
85/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
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
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
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
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
Module: Widgets
Common Widgets
Layout Management
Guidelines for Custom Widgets
Widgets
Guidelines for Custom Widgets
88/96
Guidelines: Creating a Custom Widget
Its as easy as deriving from QWidget
class 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 widget
yourself.
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
Often QWidget or QFrame
Overload needed event handlers
Often:
QWidget::mousePressEvent(),
QWidget::mouseReleaseEvent()
If
If
widget accepts keyboard input
QWidget::keyPressEvent()
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
Reimplement QWidget::paintEvent() for drawing
To draw widgets 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
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 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
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
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).
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 respective
owners. The use of the word partner does not imply a partnership
relationship between Nokia and any other company.
Widgets
Legal
96/96