qt for beginners part 2 widgets

52
Qt For Beginners - Part 2 Widgets Brian Quinn, Qt Consultant and Engineer Integrated Computer Solutions Visit us at http://www.ics.com Video Available at: http://bit.ly/qt-beginners-part-2-widgets Copyright 2016, Integrated Computers Solutions, Inc. This work may not be reproduced in whole or in part without the express written consent of Integrated Computer Solutions, Inc. 1

Upload: ics

Post on 16-Apr-2017

1.994 views

Category:

Software


4 download

TRANSCRIPT

Page 1: Qt for beginners part 2   widgets

Qt For Beginners - Part 2Widgets

Brian Quinn, Qt Consultant and EngineerIntegrated Computer SolutionsVisit us at http://www.ics.com

Video Available at: http://bit.ly/qt-beginners-part-2-widgets Copyright 2016, Integrated Computers Solutions, Inc.

This work may not be reproduced in whole or in part without the express written consent of

Integrated Computer Solutions, Inc.

1

Page 2: Qt for beginners part 2   widgets

Agenda

● Introduction to Widgets● Layout Management● Qt Designer Introduction● Dialogs● Designer Forms and Code Integration● Application Creation● Resources● Q & A

2

Page 3: Qt for beginners part 2   widgets

Agenda

● Introduction to Widgets● Layout Management● Qt Designer Introduction● Dialogs● Designer Forms and Code Integration● Application Creation● Resources● Q & A

3

Page 4: Qt for beginners part 2   widgets

Why Widgets? ● Solid and Reliable

● Easy to Use

● Multitude of Features

● Extensive Documentation

4

Page 5: Qt for beginners part 2   widgets

All of the Parts and Pieces

● The Lowly QWidget○ Basis of all visual items in the widget “family”○ Just an empty rectangle○ Makes sure that it looks like it’s native to the OS

● Parent-child relationship○ x,y coordinates in relative regions○ Parent defines coordinate space

● Custom widgets

5

Page 6: Qt for beginners part 2   widgets

● Displays○ Labels○ Digital Display○ Progress Bar

● Inputs○ Line Edits○ Spin Boxes ○ Combo Boxes

● Buttons○ Push Buttons○ Checkboxes ○ Radio buttons

● Containers○ Group Boxes○ Frames○ Tabs

● Views○ Lists○ Tables○ Trees

● And Much More!

The Many kinds of Widgets

6

Page 7: Qt for beginners part 2   widgets

Display Widgets

Only meant display information, no user interaction

QLabel● Shows a string of characters and or an image

QLabel *myLabel = new QLabel("Qt Fundamentals!", parent);myLabel->setPixmap(pic);

QLCDNumber● Stylized numeric display

QLCDNumber *myLCD = new QLCDNumber(parent);myLCD->display(552016);

QProgressBar● Percentage and animation included

QProgressBar *myProgress = new QProgressBar(parent);myProgress->setRange(0, 100);myProgress->setValue(70);

7

Page 8: Qt for beginners part 2   widgets

Text Input Widgets

QLineEdit● Can mask input● Data validationQTextEdit● Accepts HTML tags

QLineEdit *line = new QLineEdit(parent);line->setText("Edit me");line->setValidator(validator);

QLineEdit *output = new QLineEdit(parent);output->setEchoMode(QLineEdit::Password);

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

...

QTextEdit *edit = new QTextEdit(parent);edit->setPlainText("Plain Text");edit->append("<h1>Html Text</h1>");

8

Page 9: Qt for beginners part 2   widgets

Button Widgets

9

QAbstractButton

● Abstract base class of buttons, providing all of their core functionality

QPushButton

● The most basic buttonQPushButton *button = new QPushButton("Push Me", parent);

button->setIcon(QIcon("images/icon.png"));

setCheckable(bool); - toggle button

QRadioButton

● Radio buttons are autoExclusive by defaultQRadioButton *radio = new QRadioButton("Option 1", parent);

QCheckBox

● An inclusive choice selectorQCheckBox *check = new QCheckBox("Choice 1", parent);

Page 10: Qt for beginners part 2   widgets

Spinboxes

QSpinBox and QDoubleSpinBox● Numeric-exclusive data● Keyboard and Mouse input● Stepwise incrementing included

QSpinBox *spin = new QSpinBox(parent); spin->setRange(10, 80);spin->setValue(42);spin->setSuffix(" USD");connect(spin, SIGNAL(valueChanged(int)) ......QDoubleSpinBox *dspin = new QDoubleSpinBox(parent); dspin->setRange(0.0, 1.0);dspin->setValue(0.5); dspin->setSuffix(" Kg");connect(spin, SIGNAL(valueChanged(double)) ...

10

Page 11: Qt for beginners part 2   widgets

Sliders, Dials, and Combo Boxes

QSlider and QDial● Drag or click to the desired value

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

QDial *volDial = new QDial(parent);

QComboBox● enter or select the desired value from the drop-down list

QComboBox *combo = new QComboBox(parent);combo->addItems(QStringList() << "Apples" << "Bananas" << "Cherries");

11

Page 12: Qt for beginners part 2   widgets

Organizer Widgets

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

setCheckable(bool) - checkbox in title

QTabWidgettab = new QTabWidget(parent);

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

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

● setCurrentWidget(widget)○ Displays page associated with widget

● setTabPosition(position)○ Defines where tabs are drawn

● setTabsClosable(bool)○ Adds close buttons

12

Page 13: Qt for beginners part 2   widgets

Agenda

● Introduction to Widgets● Layout Management● Qt Designer Introduction● Dialogs● Designer Forms and Code Integration● Application Creation● Resources● Q & A

13

Page 14: Qt for beginners part 2   widgets

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);

14

Page 15: Qt for beginners part 2   widgets

Making Qt Do The Work

DefinitionLayout: 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 a disadvantage!

15

Page 16: Qt for beginners part 2   widgets

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

16

Page 17: Qt for beginners part 2   widgets

QHBoxLayout and QVBoxLayout

● Lines up widgets horizontally or vertically● Divides space into boxes● Each managed widget fills in one box

QWidget *window = new QWidget();

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

QHBoxLayout *layout = new QHBoxLayout();

layout->addWidget(one);

window->setLayout(layout);

17

Page 18: Qt for beginners part 2   widgets

Widgets In a Grid - QGridLayoutQWidget *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)

● No need to specify rows and columns before adding children

18

Page 19: Qt for beginners part 2   widgets

QFormLayout

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

● Respects style guide of individual platforms.

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

QFormLayout *layout = new QFormLayout();

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

window->setLayout(layout);

● Form layout with Cleanlooks and Mac style

19

Page 20: Qt for beginners part 2   widgets

Some Layout Terms

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

○ QBoxLayout::addStretch(stretch)

● Contents Margins○ Space reserved around the managed widgets.○ QLayout::setContentsMargins(left,top,right,bottom)

● Spacing○ Space reserved between widgets○ QBoxLayout::addSpacing(size)

20

Page 21: Qt for beginners part 2   widgets

Nested Layouts

● A Box within a box○ Allows flexible layouts○ QLayout::addLayout(...)

21

Page 22: Qt for beginners part 2   widgets

Agenda

● Introduction to Widgets● Layout Management● Qt Designer Introduction● Dialogs● Designer Forms and Code Integration● Application Creation● Resources

22

Page 23: Qt for beginners part 2   widgets

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

23

Page 24: Qt for beginners part 2   widgets

Designer Tips

● Use the Designer! ● Avoid d'n'd of layouts from the Widget Box in favor of

multiple-selection + Layout Toolbar Buttons above the Widget Editor.● "Signals and Slots" edit mode is easier for creating signals and slots. The

"signals and slots" dockable is good for editing and removing already existing connections.

● Don't add something to a GroupBox until it is already laid out correctly.● Move things temporarily to another empty widget as scratch-space when you

have complicated nested layouts and Group Boxes.

24

Page 25: Qt for beginners part 2   widgets

Agenda

● Introduction to Widgets● Layout Management● Qt Designer Introduction● Dialogs● Designer Forms and Code Integration● Application Creation● Resources● Q & A

25

Page 26: Qt for beginners part 2   widgets

Dialog Windows - QDialog● Base class of dialog window widgets● Modal dialog:

○ Remains in foreground, until closed○ Blocks input to remaining application

QDialog myDialog(this);…if (myDialog.exec() == QDialog::Accepted) { // exec blocks until user closes dialog}

● Modeless dialog:○ Operates independently in application○ Use show()

● No need to keep dialogs around forever○ Call QObject::deleteLater()○ Or setAttribute(Qt::WA_DeleteOnClose)

26

Page 27: Qt for beginners part 2   widgets

Asking for Files - QFileDialog● Asking for a file name

QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"));if (!fileName.isNull()) { // do something useful}

● QFileDialog::getOpenFileNames()

○ Returns one or more selected existing files● QFileDialog::getSaveFileName()

○ Returns a file name. File does not have to exist.● QFileDialog::getExistingDirectory()

○ Returns an existing directory.● setFilter("Image Files (*.png *.jpg *.bmp)")

○ Displays files matching the patterns

27

Page 28: Qt for beginners part 2   widgets

Showing Messages - QMessageBox● Provides a modal dialog for …

○ informing the user○ asking a question and receiving an answer

● Typical usage, questioning a userQMessageBox::StandardButton ret = QFileDialog::question(parent, title, text);if (ret == QMessageBox::Ok) { // Do something useful}

● Other convenience methods○ QMessageBox::information(...)○ QMessageBox::warning(...)○ QMessageBox::critical(...)○ QMessageBox::about(...)

28

Page 29: Qt for beginners part 2   widgets

29

Feedback Progress - QProgressDialogQProgressDialog dialog("Copy", "Abort", 0, count, this);

dialog.setWindowModality(Qt::WindowModal);

for (int i = 0; i < count; i++) {

dialog.setValue(i);

if (dialog.wasCanceled()) { break; }

//... Copy one file

}

dialog.setValue(count); // Ensure set to maximum

● Can estimate time or work left with setValue()● Can check if operation was canceled:

○ Connect to QProgressDialog::canceled()

Page 30: Qt for beginners part 2   widgets

Other Common Dialogs

● Selecting Color - QColorDialog○ QColorDialog::getColor(...)

● Selecting Font - QFontDialog○ QFontDialog::getFont(...)

30

Page 31: Qt for beginners part 2   widgets

Agenda

● Introduction to Widgets● Layout Management● Qt Designer Introduction● Dialogs● Designer Forms and Code Integration● Application Creation● Resources● Q & A

31

Page 32: Qt for beginners part 2   widgets

Code Integration

● Code integration of .ui files with C++ classes:○ Separates UI from back-end code○ Allows drag and drop WYSIWYG adjustments○ Easy communication to/from C++○ Using properties and signal/slot connections

32

Page 33: Qt for beginners part 2   widgets

Designer UI Form Files

● Form stored in .ui file○ format is XML

● uic tool generates code○ From myform.ui

■ to ui_myform.h○ Class created in the Ui namespace

● List form ui in project file (.pro)○ FORMS += mainwindow.ui

33

Page 34: Qt for beginners part 2   widgets

From .ui to C++

34

OrderForm.uisaves to

uic

Qt Designer orDesign Mode in Qt Creator

class 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; }

producesorderform.h

ui_orderform.

h

orderform.cpp

Page 35: Qt for beginners part 2   widgets

Code Integration - Header

// orderform.hnamespace Ui { class OrderForm;}

class OrderForm : public QDialog {private: Ui::OrderForm *ui; // pointer to UI object};● Host widget derives from appropriate base class● *ui member encapsulate UI class

○ Makes header independent of Designer generated code

35

Page 36: Qt for beginners part 2   widgets

Code Integration - C++

// orderform.cpp#include "ui_orderform.h"

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

OrderForm::~OrderForm(){delete ui;

}● Default behavior in Qt Creator

36

Page 37: Qt for beginners part 2   widgets

Forms and Multiple Inheritance

Another way to integrate forms is through multiple inheritance● Inherit from both a QWidget and the Ui_Form class● Advantage: Simple and easy to use● Disadvantage: Header dependent on Designer generated code● Disadvantage: Risk of name-clashes with inherited QWidget members// orderform.h#include "ui_orderform.h"

class OrderForm : public QDialog, private Ui::OrderForm{ …};

// orderform.cppOrderForm::OrderForm(QWidget *parent) : QDialog(parent) { setupUi(this);}

37

Page 38: Qt for beginners part 2   widgets

Agenda

● Introduction to Widgets● Layout Management● Qt Designer Introduction● Dialogs● Designer Forms and Code Integration● Application Creation● Resources

38

Page 39: Qt for beginners part 2   widgets

Main Window

● QMainWindow: main application window● Has own layout

○ Central Widget○ QMenuBar○ QToolBar○ QDockWidget○ QStatusBar

● Central Widget○ QMainWindow::setCentralWidget(widget)○ Just any widget object

39

Page 40: Qt for beginners part 2   widgets

Create Menu Bar

● QMenuBar: a horizontal menu bar● QMenu: represents a menu

○ indicates action state● QAction: menu items added to QMenu

void MainWindow::setupMenuBar() { QMenuBar *bar = menuBar(); QMenu *menu = bar->addMenu(tr("&File")); menu->addAction(action); menu->addSeparator();

QMenu *subMenu = menu->addMenu(tr("Sub Menu")); ...

40

Page 41: Qt for beginners part 2   widgets

Creating Toolbars - QToolBar

● Movable panel …○ Contains set of controls○ Can be horizontal or vertical

● QMainWindow::addToolbar(toolbar)○ Adds toolbar to main window

● QMainWindow::addToolBarBreak()○ Adds section splitter

● QToolBar::addAction(action)○ Adds action to toolbar

● QToolBar::addWidget(widget)○ Adds widget to toolbar

Example:void MainWindow::setupToolBar() {

QToolBar *bar = addToolBar(tr("File"));

bar->addAction(action);

bar->addSeparator();

bar->addWidget(new QLineEdit(tr("Find ...")));

...

41

Page 42: Qt for beginners part 2   widgets

QToolButton

● Quick-access button to commands or options● Used when adding action to QToolBar● Can be used instead QPushButton

○ Different visual appearance!● Advantage: allows to attach action

QToolButton *button = new QToolButton(this);button->setDefaultAction(action);// Can have a menubutton->setMenu(menu);// Shows menu indicator on buttonbutton->setPopupMode(QToolButton::MenuButtonPopup);// Control over text + icon placementsbutton->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);

42

Page 43: Qt for beginners part 2   widgets

QIcon, QPixmap, QImage

● Qt has different classes for representing images○ QPixmap

■ for on-screen images○ QImage

■ for off-screen images○ QIcon

■ Support for:● different sizes● states (on, off)● modes (active, disabled, selected)

43

Page 44: Qt for beginners part 2   widgets

The Status Bar - QStatusBar

● Horizontal bar○ Suitable for presenting status information

● showMessage(message, timeout)○ Displays temporary message for specified milli-seconds

● clearMessage()○ Removes any temporary message

● addWidget() or addPermanentWidget()○ Normal, permanent messages displayed by widget

void MainWindow::createStatusBar() {QStatusBar *bar = statusBar() {bar->showMessage(tr("Ready"));bar->addWidget(new QLabel(tr("Label on StatusBar")));...

44

Page 45: Qt for beginners part 2   widgets

Creating Dock Windows - QDockWidget

● Window docked into main window● Qt::DockWidgetArea enum

○ Left, Right, Top, Bottom dock areas● QMainWindow::setCorner(corner,area)

○ Sets area to occupy specified corner● QMainWindow::setDockOptions(options)

○ Specifies docking behavior (animated, nested, tabbed, ...)

void MainWindow::createDockWidget() {QDockWidget *dock = new QDockWidget(tr("Title"), this);dock->setAllowedAreas(Qt::LeftDockWidgetArea);QListWidget *widget = new QListWidget(dock);dock->setWidget(widget);addDockWidget(Qt::LeftDockWidgetArea, dock);...

45

Page 46: Qt for beginners part 2   widgets

QMenu and Context Menus

● Launch via event handlervoid MyWidget::contextMenuEvent(event) {

m_contextMenu->exec(event->globalPos());

● or signal customContextMenuRequested()○ Connect to signal to show context menu

● Or via QWidget::actions() list○ QWidget::addAction(action)

○ setContextMenuPolicy(Qt::ActionsContextMenu)

○ Displays QWidget::actions() as context menu

46

Page 47: Qt for beginners part 2   widgets

Agenda

● Introduction to Widgets● Layout Management● Qt Designer Introduction● Dialogs● Designer Forms and Code Integration● Application Creation● Resources● Q & A

47

Page 48: Qt for beginners part 2   widgets

Resource System

● Platform-independent mechanism for storing binary files○ Not limited to images

● Resource files stored in application's executable● Useful if application requires files

○ E.g. icons, translation files, sounds○ No risk of losing files, easier deployment

48

Page 49: Qt for beginners part 2   widgets

Using Resources

● Resources specified in .qrc file

<!DOCTYPE RCC><RCC version="1.0">

<qresource>

<file>images/copy.png</file>

<file>images/cut.png</file>

...

<qresource>

</RCC>○ Can be created using Qt Creator

● Resources are accessible with ':' prefix○ Example: ":/images/cut.png"○ Simply use resource path instead of filename○ QIcon(":/images/cut.png")

● To compile resource, edit .pro file○ RESOURCES += application.qrc

○ qmake produces make rules to generate binary file

49

Page 50: Qt for beginners part 2   widgets

● Path Prefix○ <qresource prefix="/myresources">

○ File accessible via ":/myresources/..."● Aliases

○ <file alias="cut.png">images/scissors.png</file>

○ File accessible via ":/cut.png"● Static Libraries and Resources

○ Need to force initialization○ Q_INIT_RESOURCE(basename);

● Loading resources at runtime○ Use rcc to create binary and register resource○ rcc -binary data.qrc -o data.rcc○ QResource::registerResource("data.rcc")

● Traverse resource tree using QDir(":/")

Resource Specifics

50

Page 51: Qt for beginners part 2   widgets

Agenda

● Introduction to Widgets● Layout Management● Qt Designer Introduction● Dialogs● Designer Forms and Code Integration● Application Creation● Resources● Q & A

51

Page 52: Qt for beginners part 2   widgets

Next Time on Qt for Beginners!

Join us as we explore QML on May 19!