qt – introduction c++ gui programming with qt 3 blanchette and summerfield, chs. 1-5 qt project...

109
Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc.

Upload: augustus-jordan

Post on 27-Dec-2015

284 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Qt – Introduction

C++ GUI Programming with Qt 3Blanchette and Summerfield, Chs. 1-5

Qt Project site, Miller 2004, etc.

Page 2: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

GLUT, Qt

GLU

GL

GLX, AGLor WGL

X, Win32, Mac O/S

software and/or hardware

application program

OpenGL Motifwidget or similar

Recall, Software Organization forWindow & Graphics Systems

• As Glut, Qt is a “programming system” that provides access to both window and graphics system

– Widely used and robust, e.g., Google Earth– Many more widgets– Tradeoff:

• Flexibility (not all window system calls available)

window system

graphics system

Page 3: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Recall, Paradigm Control Structure• Something happens - an “event”

1. System may cause redraw, i.e., call “myDisplay”

• E.g., move window off• GLUT display function called

2. GLUT callback may handle, if defined• E.g., glutMouseFunc - myMouse

• Update any signals (values) that creating display depends on

DrawDisplay

(myDisplay)

Event – user, system, program

Program’s GLUT callback may change state of program

1

2

Page 4: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Recall, Paradigm Control Structure• Something happens - an “event”

1. System may cause redraw, i.e., call “myDisplay”

• E.g., move window off• GLUT display function called

2. GLUT callback may handle, if defined• E.g., glutMouseFunc - myMouse

• Update any signals (values) that creating display depends on

– Often, display needs to be redrawn– Programmer decides and signals this– Program indicates by postRedisplay ()

• Which actually causes system to indicate call to GLUT display function

• Draw display – because of postRedisplay– GLUT display function

DrawDisplay

(myDisplay)

Event – user, system, program

Program’s GLUT callback may change state of program

requiring redrawPostRedisplay()

1

2

Page 5: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Qt, Paradigm Control Structure1. Qt “slots” are functions like similar to e.g., glutMouseFunc

DrawDisplay

(myDisplay)

Event – user, system, program 1

2

Page 6: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Qt, Paradigm Control Structure2. Qt handles redraw

Event – user, system, program 1

2

Page 7: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Overview

• “Slots” and “signals” for event handling and inter-dialog communication

• Widget styles– Window system native, or common across platforms

• Qt ide and resources

• Qt dialogs

• Qt menus

• Qt “frame window”

Page 8: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

About UI Programming Systems

• UI programming systems, or “toolkits”, consist of these elements– E.g., GLUT (below) MS windows (below), – Also, Swing (AWT for Java), Motif (X-windows), Qt (cross-platform)

GLUT MS WindowsComponents (view hierarchy) Windows Windows and child windows

Stroke drawing package Text support GDI

Pixel model OpenGL native Bitmaps

Input handling Callback functions Msgs sent to a window proc

Widgets Menus Buttons, menus, text boxes, scrollbars, etc.

Page 9: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Examples

MS Windows Swing HTML Qt

Components Windows JComponents Elements Windows

Strokes GDI Graphics (none) Graphics

Pixels Bitmaps Image Inline images Images

Input Messages -> window proc

Listeners Javascript event handlers

Connections and slots

widgets Button, menu, textbox, …

Jbutton, Jmenu, …

Form controls, links

Button, …

• All ui programming systems have these basic elements:

Page 10: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Widgets

• Widget: “window gadget” (Qt), etc.– Controls, interactors, gizmos, gadgets

• At core of Qt programming paradigm

• Reusable user interface components

• Examples– Buttons, checkboxes, radio buttons– List boxes, combo boxes, drop-downs– Menus, toolbars– Scrollbars, splitters, zoomers– One-line text, multiline text, rich text– Trees, tables– Simple dialogs

Page 11: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Widgets

• Success (or unsuccess) story for user interface programming

• Advantages– Reuse of development effort

• Coding, testing, debugging, maintenance• Design, iteration and evaluation

– External consistency

• Disadvantages– Constrain designer’s thinking– Encourage menu & forms style, rather than richer direct manipulation style– May be used inappropriately

• E.g., instructions in title bar

– Is WIMP all there is?– Long record of mediocre (but not really bad) interfaces

Page 12: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Widget Data

• Data used in widgets

• 1. Embedded model– Application data must be copied into the widget– Changes must be copied out’

• 2. Linked model– Or, data binding– Application provides model satisfying an interface– Enables “data-bound” widgets, e.g. a table showing thousands of database rows,

or a combo box with thousands of choices

Page 13: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

UI Toolkits - Qt

• Cross-platform portability, as has GLUT• Current version re-implements native system look and feel• Or, can have (program) internal consistency

• Extends widget set, e.g., spin boxes

• Qt provides C++, Java, and Python language bindings

• Allows direct access to, e.g., OpenGL

• Also allows direct access to MS Windows API• But, is much more efficient to program in

Page 14: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

“Qt Project”• Qt Project - Commercial and free … video tutorials, user community…

– Formerly, Nokia

Page 15: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

“Qt Project”

• Download and install about as easy as it gets

• Examples from Qt 3 and 4

– Haven’t tried 5.0

Page 16: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Qt - ide• Has own ide, which works fine – all the usual things

– Even good, when working with Qt widgets vs. e.g., Glut

Page 17: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Qt – dialog box editor

• Even own dialog box editor

Page 18: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Hello, Qt!

Page 19: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Hello, Qt!Example 1 – stupid 2 line program

#include <QApplication> // more later

#include <QLabel> // more later

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

{

QApplication app(argc, argv);

QLabel *label = new QLabel("Hello Qt!");

label->show();

return app.exec();

}

• A bit for dramatic effect, but there will be advantages• Just a label in a field with no real “main window”

• Will look at some basics• Slots and signals (vs. event queues), and layouts (this is a GUI builder),

Page 20: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Hello, Qt!

#include <QApplication> // Definitions of QApplication and

#include <QLabel> // QLabel classes

// Qt is truly object-oriented

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

{

QApplication app(argc, argv); // Creates a QApplication object to

// manage app-wide resources

QLabel *label = new QLabel("Hello Qt!"); // Creates a QApplication widget (used as

// a window) that displays string

label->show(); // Make label (window) visible

return app.exec(); // Passes control to Qt

} // (would also delete QLabel)

Page 21: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Handling Events: Signals and Slots

• Qt not handle events (or event queue) directly

• Qt widgets emit signals when user action or change of state occurs

• Signal can be connected to a function, or slot– When signal emitted the slot, or function, is executed

• In example, will connect button’s “clicked” signal to slot - function quit()– quit() is “built-in” QApplication function (object)

Page 22: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

A Signal and A SlotExample 2

#include <QApplication> // Include class definitions

#include <QPushButton>

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

{

QApplication app(argc, argv); // Create QApplication object

QPushButton *button = new QPushButton("Quit"); // Create labeled button

// Associate (connect) a particular signal of this application with a slot / function

QObject::connect(button, SIGNAL(clicked()), &app, SLOT( quit() ));

button->show();

return app.exec(); // Pass control to QT

}

Page 23: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Synchronization & Layout of 2 WidgetsExample 3

• Creates three widgets:– QSpinbox, QSlider, QWidget (application’s main window, will be parent of others)

• Using signals and slots of the QSpinbox and QSlider, set value of one depending on value set in the other

– E.g., change spinbox value to 70, slider will move to appropriate position– Change slider to some position, spinbox value will be changed based on position

• “Layout manager” object will set size and position of widgets

Page 24: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

“Setting up”, 1/3

#include <QApplication> // Include class definitions,

#include <QHBoxLayout> // including for layout, slider

#include <QSlider> // and spinbox

#include <QSpinBox>

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

{

QApplication app(argc, argv);

QWidget *window = new QWidget; // Again, window will be widget

window->setWindowTitle("Enter Your Age"); // Not good interface design

Page 25: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Create & Synchronize Widgets, 2/3

QSpinBox *spinBox = new QSpinBox; // Create spinbox

QSlider *slider = new QSlider(Qt::Horizontal); // Create slider

spinBox->setRange(0, 130); // Set/define range of each

slider->setRange(0, 130); // This is easy!

// As before, a widget signal causes a function (slot) to be called – here, “setting each other”

// here, when the value in the spinbox is changed, the function to set the value in the

// slider is called, and passed the new value of the spinbox to be the new value of the slider

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

// … and vice versa

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

spinBox->setValue(35); // Set initial value for spinbox, slider will then get set

Page 26: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Layout of Widgets by Qt, 3/3

// Qt manages the relative positioning of the child windows, here, as BoxLayout

QHBoxLayout *layout = new QHBoxLayout;

layout->addWidget(spinBox); // Place widgets in set to be

layout->addWidget(slider); // positioned

window->setLayout(layout); // Installs layout manager on win

window->show();

return app.exec();

}

Page 27: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Widget Styles

• Recall, Qt is cross-platform

• Can have Qt applications in windowing system style where executed (external consistency) or in same style across windowing systems (internal consistency)

Page 28: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Qt IDE

• Works fine

Page 29: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Qt IDE

• Open project

• Open file

Page 30: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Help

• Works fine

Page 31: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Help

• Works fine

Page 32: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

QT – Dialogs

• Blanchette and Summerfield, Ch. 2

Page 33: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Dialogs, and Qt

• “Dialog” in ui programming refers to exchange of information of user and program

• Dialog boxes are ui elements that can do this, as are other elements – For Qt-ese, just say “dialogs”

• “GUI applications” consist of main window, menu bar, tool bar, … and many dialog boxes (dialogs)

– From a programming perspective, could create an application that was just a “dialog”, e.g., calculator

• Important enough that “ui programming system” always provide means to create efficiently

– Sometimes “efficient creation” takes a while to get used to – Will see Qt Creator

Page 34: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Dialogs –1st Example

• Implement as (sub)class– Independent, self-contained component– Signals and slots all in one– No “window”– QWidget > QDialog > FindDialog

• At right,– QDialog not shown

• Dialog will consist of 5 widgets– Edit box, 2 check boxes, 2 buttons

• Program will do class setups, definition and placement of widgets

• Three files: – finddialog.h, finddialog.cpp, main.cpp

Page 35: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Steps in Defining and Implementing Subclass findDialog

• Will look at the code in detail – “survival kit” for creating dialogs

1. finddialog.h– Set up: include, forward declarations– FindDialog subclass definition

2. finddialog.cpp– Will implement findDialog class:– Create dialog elements (widgets)– Connect signals and slots– Lay out widgets using layout managers– Define slots, or functions

3. main.cpp– As before, create new object, show it, and execute

Page 36: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

1. finddialog.hSet up: include, forward

declarations

#ifndef FINDDIALOG_H // For c++ preprocessor – only include once

#define FINDDIALOG_H

#include <QDialog> // QDialog is Qt base class (it inherits Qwidget)

// Again, below from last time

class QCheckBox; // forward declarations of the Qt classes used

class QLabel; // tells C++ compiler exists, later defined

class QLineEdit;

class QPushButton;

Page 37: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

finddialog.h FindDialog - Subclass

Definition

class FindDialog : public QDialog // FindDialog is a subclass of QDialog

{

Q_OBJECT // Required macro for classes defining sgnls or slots

public:

FindDialog (QWidget *parent = 0); // Qt widget class constructor, here, no parent

// (“signals” and “slots” are macros)

signals: // Define signal emitted when “Find” button clicked

void findNext (const QString &str, Qt::CaseSensitivity cs); // depends on match case

void findPrevious (const QString &str, Qt::CaseSensitivity cs); // Qt::Ca… is an enum type

private slots: // Define slots

void findClicked ();

void enableFindButton (const QString &text);

private: // Forward declarations of classes

QLabel *label; QLineEdit *lineEdit;

QCheckBox *caseCheckBox; QCheckBox *backwardCheckBox;

QPushButton *findButton; QPushButton *closeButton;

}

Page 38: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

2. finddialog.cppImplement finddialog class:Create dialog elts (widgets)

#include <QtGui> // Definitions of Qt’s GUI classes - hundreds

#include "finddialog.h“

FindDialog::FindDialog (QWidget *parent)

: Qdialog (parent) // pass parent to base class constructor

{

label = new Qlabel (tr ("Find &what")); // ----- Create dialog element, Qlabel, etc. --------

lineEdit = new QLineEdit; // tr func for translation, & indicates shortcut key

label->setBuddy (lineEdit); // “buddy” is widget that accepts focus w/shortcut

caseCheckBox = new QCheckBox (tr ("Match &case")); // ------ Qcheckbox ------

backwardCheckBox = new QCheckBox (tr ("Search &backward")); // ------ Qcheckbox ------

findButton = new QPushButton (tr ("&Find")); // ------ QPushbutton ------

findButton->setDefault (true); // “default” indicates executed on key Enter

findButton->setEnabled (false); // not enabled, grayed out

closeButton = new QPushButton (tr ("Close"));

Page 39: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

finddialog.cppConnect signals and slots

// Signal “textchanged” from lineEdit widget enables button labeled find by private slot enableFindButton

connect ( lineEdit, SIGNAL (textChanged (const QString &)),

this, SLOT (enableFindButton (const QString &)));

// Again, private slot, findClicked, called when signal clicked emitted by widget findbutton

connect ( findButton, SIGNAL (clicked ()),

this, SLOT (findClicked ()));

// As before, Qt function close called when widget closeButton emits clicked signal

connect ( closeButton, SIGNAL (clicked ()),

this, SLOT (close ()));

Page 40: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

finddialog.cpp Lay out widgets using layout managers …tedious, but …

// layouts are nested – constrain widgets and other layouts

QHBoxLayout *topLeftLayout = new QHBoxLayout;

topLeftLayout->addWidget(label);

topLeftLayout->addWidget(lineEdit);

QVBoxLayout *leftLayout = new QVBoxLayout;

leftLayout->addLayout(topLeftLayout);

leftLayout->addWidget(caseCheckBox);

leftLayout->addWidget(backwardCheckBox);

// over to right for continuation ->

QVBoxLayout *rightLayout = new QVBoxLayout;

rightLayout->addWidget(findButton);

rightLayout->addWidget(closeButton);

rightLayout->addStretch(); // fill – here, below

QHBoxLayout *mainLayout = new QHBoxLayout;

mainLayout->addLayout(leftLayout);

mainLayout->addLayout(rightLayout);

setLayout(mainLayout);

setWindowTitle (tr ("Find")); setFixedHeight (sizeHint().height()); }

Page 41: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

FindDialog Constructors -Parent-child Relationships

text

Page 42: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Define finddialog slots, or functions

… very briefly, complicated example

// Called when user clicks Find button, emits signal findPrevious() or findNext

void FindDialog ::findClicked()

{

QString text = lineEdit->text();

Qt::CaseSensitivity cs =

caseCheckBox->isChecked() ? Qt::CaseSensitive

: Qt::CaseInsensitive;

if (backwardCheckBox->isChecked()) {

emit findPrevious(text, cs);

} else {

emit findNext(text, cs); // emit keyword (macro) specific to Qt

}

}

// Called whenever user changes text in line editor, enables button if there is text in line editor

void FindDialog::enableFindButton(const QString &text)

{

findButton->setEnabled (!text.isEmpty ());

}

Page 43: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

3. main.cpp

// As before, simply create a new object, here FindDialog, show it, and execute

#include <QApplication>

#include "finddialog.h“

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

{

QApplication app (argc, argv);

FindDialog *dialog = new FindDialog;

dialog->show();

return app.exec();

}

Page 44: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

More about Signals and Slots

Page 45: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

More about Signals and Slots

• “Signals and slots enable application programmer to bind objects together without objects knowing anything about each other”

– Essentially c++ member functions– Can be virtual, overloaded, public, protected, private, invoked indirectly– Connected to a signal and automatically called each time the signal is emitted

• connect (sender, SIGNAL (signal), receiver, SLOT (slot) )

• So far, only different signals to different slots

• Other ways, as well

Page 46: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Signals and Slots, 1

• connect (sender, SIGNAL (signal), receiver, SLOT (slot) )

1. One signal can be connected to many slots:– connect(slider, SIGNAL(valueChanged(int)),

spinBox, SLOT(setValue(int)));– connect(slider, SIGNAL(valueChanged(int)),

this, SLOT(updateStatusBarIndicator(int)));– When signal emitted, slots called one after the other, in arbitrary order

2. Many signals can be connected to the same slot:– connect(lcd, SIGNAL(overflow()),

this, SLOT(handleMathError()));– connect(calculator, SIGNAL(divisionByZero()),

this, SLOT(handleMathError()));– When either signal is emitted, the slot is called.

Page 47: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Signals and Slots, 2

• Again• connect (sender, SIGNAL (signal), receiver, SLOT (slot) )

3. A signal can be connected to another signal:– connect(lineEdit, SIGNAL(textChanged(const QString &)),

this, SIGNAL(updateRecord(const QString &)));– When the first signal is emitted, the second signal is emitted as well.

4. Connections can be removed:– disconnect(lcd, SIGNAL(overflow()),

this, SLOT(handleMathError()));

Page 48: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Qt Designer

• “visual” dialog box design tool

• Layout (positioning) of widgets – buttons, check boxes, …

Page 49: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Qt Designer

• x

Page 50: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Qt Designer

• x

Page 51: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Qt Designer

• .

Page 52: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Qt Dialog: Overview

Page 53: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Qt Dialog: Overview

• Another example of essential Qt concepts – Addressbook tutorial

• Qt – “main window”

• Subclassing – many “actions” / methods

• Menus, tool bars– Selection of item creates action, using signals and slots

• Implementing functionality – in actions

• “Context menus – right button

• Modal vs. modeless dialogs

Page 54: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Another Example

• Another example of essential Qt concepts

• Tutorial – address book – Qt 4.5 Reference Documentation

• Essentially all of the elements of Qt programming needed

• Will look at first part of tutorial example

– Files organization– Class definition– Widgets (labels and text input fields)– Layout

Page 55: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Addressbook Subclass & Widgets

• Addressbook will be subclass of QWidget

• Widgets (elements)

• QLabel objects– nameLabel, addresslabel

• Input fields – objects– QLineEdit: nameLine– QTextEdit: addressText

Page 56: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Files

• c/c++, use files to organize implementation

• addressbook.h – definition file for

AddressBook class

• addressbook.cpp – implementation file for

AddressBook class

• main.cpp – main() function, with an

instance of AddressBook.

Page 57: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

addressbook.hDefines the AddressBook Class

#include <QWidget>

class QLabel;

class QLineEdit;

class QTextEdit;

class AddressBook : public QWidget // Declare AddressBook subclass of QWidget

{

Q_OBJECT // Qt macro for signals and slots, etc.

public:

AddressBook (QWidget *parent = 0);

private:

QLineEdit *nameLine; // Declare private instance of QLineEdit

QTextEdit *addressText; // “ QTextEdit

};

Page 58: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

addressbook.cpp – Part 1Implements addressbook class

// Will declare local objects and create layout in Part 1

// Part 2 will implement functionality (maybe more later)

#include <QtGui>

#include "addressbook.h"

// Constructor of AddressBook accepts QWidget

// parent

AddressBook::AddressBook(QWidget *parent)

: QWidget(parent)

{

// declare local objects

QLabel *nameLabel = new QLabel(tr("Name:"));

nameLine = new QLineEdit;

QLabel *addressLabel = new

QLabel(tr("Address:"));

addressText = new QTextEdit;

Page 59: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

addressbook.cppImplements addressbook class

// Create layout

// Here, use GridLayout (BoxLayout last time)

// divides space into grid with row and col nums

GridLayout *mainLayout = new QGridLayout;

mainLayout->addWidget(nameLabel, 0, 0);

mainLayout->addWidget(nameLine, 0, 1);

mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);

mainLayout->addWidget(addressText, 1, 1);

// Invode layout widget’s setLayout function to install objects

setLayout(mainLayout);

setWindowTitle(tr("Simple Address Book"));

}

Page 60: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Main.cpp“executes” Qt application

// Instantiates a Qapplication object, here, app

// Qapplication manages application-wide resources, e.g., font, cursor, and runs event loop

//

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

{

QApplication app(argc, argv);

// Construct new AddressBook widget on heap with new keyword

AddressBook *addressBook = new AddressBook;

// Display the widget, when the application’s event loop is started

addressBook->show();

// Start the event loop

return app.exec();

}

Page 61: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

addressbook.cpp – Part 2Implements addressbook class – 1. add labels and buttons

#include <QtGui>

#include "addressbook.h"

AddressBook::AddressBook(QWidget *parent)

: QWidget(parent)

{

QLabel *nameLabel = new QLabel(tr("Name:"));

nameLine = new QLineEdit;

nameLine->setReadOnly(true);

QLabel *addressLabel = new QLabel(tr("Address:"));

addressText = new QTextEdit;

addressText->setReadOnly(true);

addButton = new QPushButton(tr("&Add"));

addButton->show();

submitButton = new QPushButton(tr("&Submit"));

submitButton->hide();

cancelButton = new QPushButton(tr("&Cancel"));

cancelButton->hide();

Page 62: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

addressbook.cpp – Part 2Implements addressbook class – 2. Connect signals and slots

// As we’ve seen widgets can emit signals,

// which then invoke methods (functions)

connect(addButton, SIGNAL(clicked()),

this, SLOT(addContact()));

connect(submitButton, SIGNAL(clicked()),

this, SLOT(submitContact()));

connect(cancelButton, SIGNAL(clicked()),

this, SLOT(cancel()));

Page 63: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

addressbook.cpp – Part 2Implements addressbook class – 3. Add buttons & create layout

QGridLayout *mainLayout = new QGridLayout;

mainLayout->addWidget(nameLabel, 0, 0);

mainLayout->addWidget(nameLine, 0, 1);

mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop);

mainLayout->addWidget(addressText, 1, 1);

mainLayout->addLayout(buttonLayout1, 1, 2);

setLayout(mainLayout);

setWindowTitle(tr("Simple Address Book"));

}

Page 64: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Rest of AddressBook Tutorial(or not – but has menus)

• Rest of tutorial adds more buttons (easy enough)

• Also, adds substantial functionality to methods invoked when a button is clicked (and emits the clicked signal)

– E.g., inserting names in list, searching for duplicates

• Adding such functionality will be covered (maybe) later

• First, main windows

Page 65: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Rest of AddressBook Tutorial

• Rest of tutorial adds more buttons (easy enough)

• Also, adds substantial functionality to methods invoked when a button is clicked (and emits the clicked signal)

– E.g., inserting names in list, searching for duplicates

• Adding such functionality will be covered (maybe) later

• First, main windows

Page 66: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Main Windows

• For Qt (and other systems) “main window” refers to a kind of “executive” control and coordination of elements

– Dialogs, menus, tool bars, status bars

• After this, final essential that remains is to look carefully at implementation of application functionality – Ch. 4, maybe later

• Blanchette and Summerfield build on spreadsheet dialogs

Page 67: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Creating Application’s Main Window Subclassing QMainWindow

// mainwindow.h - Create main window as subclass of QMainWindow

#include <qmainwindow.h>

#include <qstringlist.h>

class QAction;

class QLabel;

class FindDialog;

class Spreadsheet;

class MainWindow : public QMainWindow

{

Q_OBJECT

public:

MainWindow(QWidget *parent = 0, const char *name = 0);

protected:

void closeEvent(QCloseEvent *event); // reimplement to modify

void contextMenuEvent(QContextMenuEvent *event); // “ right-click menu

Page 68: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

mainwindow.h, 2 Subclassing QMainWindow – Slots for menu options

// Most menu options are implemented as private slots (methods, functions) in MainWindow

private slots: // essentially, function called when menu item selected

void newFile();

void open();

bool save();

bool saveAs();

void find();

void goToCell();

void sort();

void about();

Page 69: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

mainwindow.h, 3 Subclassing QMainWindow – More slots

void updateCellIndicators();

void spreadsheetModified();

void openRecentFile(int param);

private:

void createActions();

void createMenus();

void createToolBars();

void createStatusBar();

void readSettings();

void writeSettings();

bool maybeSave();

void loadFile(const QString &fileName);

void saveFile(const QString &fileName);

void setCurrentFile(const QString &fileName);

void updateRecentFileItems();

QString strippedName(const QString &fullFileName);

Page 70: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

mainwindow.h, 4 Subclassing QMainWindow – More slots – to support UI

Spreadsheet *spreadsheet;

FindDialog *findDialog;

QLabel *locationLabel;

QLabel *formulaLabel;

QLabel *modLabel;

QStringList recentFiles;

QString curFile;

QString fileFilters;

bool modified;

enum { MaxRecentFiles = 5 };

int recentFileIds[MaxRecentFiles];

QPopupMenu *fileMenu;

QPopupMenu *editMenu;

QPopupMenu *selectSubMenu;

QPopupMenu *toolsMenu;

QPopupMenu *optionsMenu;

QPopupMenu *helpMenu;

QToolBar *fileToolBar;

QToolBar *editToolBar;

QAction *newAct;

QAction *openAct;

QAction *saveAct;

···

QAction *aboutAct;

QAction *aboutQtAct;

};

Page 71: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

• And that’s all there is to mainwindow.h!

• … and mainwindow.cpp holds the implementation

Page 72: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

mainwindow.cpp“implementation”

MainWindow::MainWindow(QWidget *parent, const char *name)

: QMainWindow(parent, name)

{ // Below creates spreadsheet widget and it’s constituent widgets

spreadsheet = new Spreadsheet(this); // class to be defined later

setCentralWidget(spreadsheet);

createActions();

createMenus();

createToolBars();

createStatusBar();

readSettings();

setCaption(tr("Spreadsheet"));

setIcon(QPixmap::fromMimeSource("icon.png"));

findDialog = 0;

fileFilters = tr("Spreadsheet files (*.sp)");

modified = false;

}

Page 73: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

mainwindow.cppcreating menu and toolbar elements, and actions

• A Qt “action” is item that can be added to menu or toolbar

• To create menus and toolbars in Qt:– Create actions– Add actions to menus– Add actions to toolbars

• Below is Qt-ese for the menu element “New”:

void MainWindow::createActions()

{

newAct = new QAction(tr("&New"), tr("Ctrl+N"), this);

newAct->setIconSet(QPixmap::fromMimeSource("new.png"));

newAct->setStatusTip(tr("Create a new spreadsheet file"));

connect(newAct, SIGNAL(activated()), this, SLOT(newFile()));

Page 74: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

mainwindow.cppcreating menu and toolbar elements, and actions, 2

// Show Grid is toggle (Boolean) and rendered with check mark

showGridAct = new QAction(tr("&Show Grid"), 0, this);

showGridAct->setToggleAction(true);

showGridAct->setOn(spreadsheet->showGrid());

showGridAct->setStatusTip(tr("Show or hide spreadsheet "grid"));

connect(showGridAct, SIGNAL(toggled(bool)),

spreadsheet, SLOT(setShowGrid(bool)));

// So, for “About”, should be familiar now

aboutQtAct = new QAction(tr("About &Qt"), 0, this);

aboutQtAct->setStatusTip(tr("Show the Qt library’s About box"));

connect(aboutQtAct, SIGNAL(activated()), qApp, SLOT(aboutQt()));

}

// Have now created all actions

Page 75: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

mainwindow.cppBuilding the menu system, “File”

• Actions are invoked through menu system– All menus are instances of QPopupMenu

void MainWindow::createMenus()

{

fileMenu = new QPopupMenu(this); // Create file menu

newAct->addTo(fileMenu); // Add “actions” to it

openAct->addTo(fileMenu);

saveAct->addTo(fileMenu);

saveAsAct->addTo(fileMenu);

fileMenu->insertSeparator();

exitAct->addTo(fileMenu);

for (int i = 0; i < MaxRecentFiles; ++i)

recentFileIds[i] = -1;

Page 76: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

mainwindow.cppBuilding the menu system, “Edit”

• Edit menu includes a submenu, otherwise, “same song, 2nd …”– Submenu simply has parent and inserted where it is to appear

editMenu = new QPopupMenu(this);

cutAct->addTo(editMenu);

copyAct->addTo(editMenu);

pasteAct->addTo(editMenu);

deleteAct->addTo(editMenu);

selectSubMenu = new QPopupMenu(this);

selectRowAct->addTo(selectSubMenu);

selectColumnAct->addTo(selectSubMenu);

selectAllAct->addTo(selectSubMenu);

editMenu->insertItem(tr("&Select"), selectSubMenu); // submenu

editMenu->insertSeparator();

findAct->addTo(editMenu);

goToCellAct->addTo(editMenu);

Page 77: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

mainwindow.cpptoolbars

• Creating toolbars is very similar to creating menus:

void MainWindow::createToolBars()

{

fileToolBar = new QToolBar(tr("File"), this);

newAct->addTo(fileToolBar);

openAct->addTo(fileToolBar);

saveAct->addTo(fileToolBar);

editToolBar = new QToolBar(tr("Edit"), this);

cutAct->addTo(editToolBar);

copyAct->addTo(editToolBar);

pasteAct->addTo(editToolBar);

editToolBar->addSeparator();

findAct->addTo(editToolBar);

goToCellAct->addTo(editToolBar);

}

Page 78: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

mainwindow.cpp“context menu, creating”

• User right mouse button will invoke “context menu”

• Reimplement QWidget :: contextMenuEvent

void MainWindow::contextMenuEvent(QContextMenuEvent *event)

{

QPopupMenu contextMenu(this);

cutAct->addTo(&contextMenu);

copyAct->addTo(&contextMenu);

pasteAct->addTo(&contextMenu);

// “exec” causes to be shown at loc

contextMenu.exec(event->globalPos());

}

Page 79: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

mainwindow.cppcontext menu, event handling

• “Events are generated by Qt’s kernel to report mouse clicks, key presses, resize requests, and similar occurrences.”

– As noted, will reimplement QWidget :: contextMenuEvent to handle event

QPopupMenu *contextMenu = new QPopupMenu(this);

cutAct->addTo(contextMenu);

copyAct->addTo(contextMenu);

pasteAct->addTo(contextMenu);

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

delete contextMenu;

Page 80: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Implementing FunctionalityWhat happens when menu item selected?

• Recall, basic control structure - when user selects a menu item, slot/member-function is called

• “New”

newAct = new QAction(tr("&New"), tr("Ctrl+N"), this);

newAct->setIconSet(QPixmap::fromMimeSource("new.png"));

newAct->setStatusTip(tr("Create a new spreadsheet file"));

connect(newAct, SIGNAL(activated()), this, SLOT(newFile()));

• “About”

aboutQtAct = new QAction(tr("About &Qt"), 0, this);

aboutQtAct->setStatusTip(tr("Show the Qt library’s About box"));

connect(aboutQtAct, SIGNAL(activated()), qApp, SLOT(aboutQt()));

Page 81: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Implementing FunctionalityWhat happens when menu item selected?

• Functionality can be simple or complex – In fact, here, newFile implementation is … complex and rich– Will leave it to you to master such topics, as interest dictates– Today, getting feel for program elements, structure, and interactions is goal

• Functionality “built in”, e.g., “About”– connect(aboutQtAct, SIGNAL(activated()), qApp, SLOT(aboutQt()));– QMessageBox::about() - a “convenience function”

void MainWindow::about(){

QMessageBox::about(this, tr("About Spreadsheet"), tr("<h2>Spreadsheet 1.0</h2>"

"<p>Copyright &copy; 2003 Software Inc."

"<p>Spreadsheet is a small application that "

"demonstrates <b>QAction</b>, <b>QMainWindow</b>, "

"<b>QMenuBar</b>, <b>QStatusBar</b>, "

"<b>QToolBar</b>, and many other Qt classes."));

}

Page 82: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Using Dialogs(or not)

• How to create, initialize, execute, and respond to choices

• Dialog (window) “modes”– Modeless: executes independently of other windows– Modal: executes (pops up) when invoked and nothing else executes until closed

• Qt dialogs and typical user action handling– Modeless

• Have their signals connected to slots that respond to user action• Invoked using show()

– Modal• Handle user action within dialog, no signals and slots• Invoked using exec()

Page 83: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Recall, findDialog

Page 84: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Define finddialog slots, or functions

// Called when user clicks Find button, emits signal findPrevious() or findNext

void FindDialog ::findClicked()

{

QString text = lineEdit->text();

Qt::CaseSensitivity cs =

caseCheckBox->isChecked() ? Qt::CaseSensitive

: Qt::CaseInsensitive;

if (backwardCheckBox->isChecked()) {

emit findPrevious(text, cs);

} else {

emit findNext(text, cs); // emit keyword (macro) specific to Qt

}

}

// Called whenever user changes text in line editor, enables button if there is text in line editor

void FindDialog::enableFindButton(const QString &text)

{

findButton->setEnabled (!text.isEmpty ());

}

Page 85: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

A Modeless Dialog (box, window)

• findDialog - window (dialog) that enables user to search for text– Invoked when user clicks Edit|Find to “pop up” (execute) Find dialog (box)– Recall functionality implemented in last chapter– Basically, “just run it”

void MainWindow::find()

{

if (!findDialog) { // if 1st execution

findDialog = new FindDialog(this);

connect(findDialog, SIGNAL(findNext(const QString &, bool)),

spreadsheet, SLOT(findNext(const QString &, bool)));

connect(findDialog, SIGNAL(findPrev(const QString &, bool)),

spreadsheet, SLOT(findPrev(const QString &, bool)));

}

findDialog->show(); // make not hidden (if so)

findDialog->raise(); // may need to bring from “underneath” other wins

findDialog->setActiveWindow(); // make active (color title bar, give focus, etc.)

}

Page 86: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

A Modal Dialog

• When invoke modal dialogs using exec(), typically don’t need to set up any signal-slot connection

• Qdialog::exec() returns true, if dialog accepted, false otherwise– GoToCellDialog - Created with Designer in Ch. 2– OK was connected to accept(), Cancel to reject()– Will need to essentially implement all functionality

void MainWindow::goToCell()

{

GoToCellDialog dialog(this);

if (dialog.exec()) {

QString str = dialog.lineEdit->text(); // get text from input widget

spreadsheet->setCurrentCell(str.mid(1).toInt() - 1, // set… defined in program

str[0].upper().unicode() - ’A’);

}

}

Page 87: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Other Dialogs for Spreadsheet

• Many examples provided in chapter

• Some straightforward

• Some arcane

• When in doubt … keep it simple

Page 88: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Qt – Functionality,Custom Widgets

• Blanchette and Summerfield, Ch. 4,5

Page 89: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Overview

• Another example of essential Qt concepts – “Application Example”– Help > Qt Reference Documentation > Qt Examples > Application Example (in 2nd pp)

• Class definition in <app>.h:– For application’s menus, toolbars, slots, function

• Create (implement) in <app>.cpp:– Menus, toolbars, status bar– Qt “actions” for menu items

• Function to be called upon selection, by connecting item action and function– connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));

• And item stuff – shortcut, status tip– “Functionality”, or just functions, for menu items

• Define resources– E.g., images

Page 90: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Application Example

• Application with menus, toolbars, and status bar

• Simple text editor program built around QTextEdit

– “Powerful” Qt widget– Many others …– Documentation next

Page 91: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

QTextEdit Reference, 1

• A widget that is a text editor!

• Note properties

– And where come from

Page 92: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

QTextEdit Reference, 2

• Slots and signals

Page 93: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

QTextEdit Reference, 3

• Functions

Page 94: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

MainWindow Class Definitionmainwindow.h – as before, slots, functions, menus, etc.

class MainWindow : public QMainWindow

{

Q_OBJECT

class QAction;

class QMenu;

class QPlainTextEdit;

  public:

MainWindow();

 

protected:

void closeEvent(QCloseEvent *event);

 

private slots:

void newFile();

void open();

bool save();

bool saveAs();

void about();

void documentWasModified();

 

private:

void createActions();

void createMenus();

void createToolBars();

void createStatusBar();

void readSettings();

void writeSettings();

bool maybeSave();

void loadFile(const QString &fileName);

bool saveFile(const QString &fileName);

void setCurrentFile(const QString &fileName);

QString strippedName(const QString &fullFileName);

 

QPlainTextEdit *textEdit;

QString curFile;

 

QMenu *fileMenu;

QMenu *editMenu;

QMenu *helpMenu;

QToolBar *fileToolBar;

QToolBar *editToolBar; QAction *newAct;

Page 95: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

“The Central Widget”

• Depending on design - central area of main window

– In non-Qt-ese

• Can be:– Standard widget

• E.g., QtextEdit, Qtable

– Custom widget

– Widgets with layout manager

– Splitter (is like Q[V/H]Box)

– MDI workspace (multiple wins)

Page 96: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

MainWindow Class Implementationmainwindow.cpp

#include <QtGui> 

#include "mainwindow.h" 

// Invoking MainWindow creates all

MainWindow::MainWindow()

{

textEdit = new QPlainTextEdit; // One call for lots of functionality

setCentralWidget(textEdit); 

createActions();

createMenus();

createToolBars();

createStatusBar(); 

readSettings();  // Standard to save and restore on start

connect(textEdit->document(), SIGNAL(contentsChanged()),

this, SLOT(documentWasModified())); 

setCurrentFile(""); // Setup for later use

setUnifiedTitleAndToolBarOnMac(true);

Page 97: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Application’s Menus

• Similar to what seen

• BTW - status bar at bottom of main window shows description of menu item or toolbar button under cursor

Page 98: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Creating Menu Items with Actionsmainwindow.cpp

void MainWindow::createMenus()

// Create the top level menus

{

fileMenu = menuBar()->addMenu(tr("&File"));

fileMenu->addAction(newAct);

fileMenu->addAction(openAct);

fileMenu->addAction(saveAct);

fileMenu->addAction(saveAsAct);

fileMenu->addSeparator();

fileMenu->addAction(exitAct); 

editMenu = menuBar()->addMenu(tr("&Edit"));

editMenu->addAction(cutAct);

editMenu->addAction(copyAct);

editMenu->addAction(pasteAct); 

menuBar()->addSeparator(); 

helpMenu = menuBar()->addMenu(tr("&Help"));

helpMenu->addAction(aboutAct);

helpMenu->addAction(aboutQtAct);

Page 99: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Creating Toolbar and Status Bar

void MainWindow::createToolBars()

// Toolbar created as menu is

{

fileToolBar = addToolBar(tr("File"));

fileToolBar->addAction(newAct);

fileToolBar->addAction(openAct);

fileToolBar->addAction(saveAct); 

editToolBar = addToolBar(tr("Edit"));

editToolBar->addAction(cutAct);

editToolBar->addAction(copyAct);

editToolBar->addAction(pasteAct);

void MainWindow::createStatusBar()

{

statusBar()->showMessage(tr("Ready"));

}

Page 100: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Create Actions, 1“Actions” specify what happens when menu item selected

// “Actions” specify what happens when menu item selected

void MainWindow::createActions()

{

// From createMenus(): “fileMenu->addAction(newAct);”

newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this); // Note relative location of icon

newAct->setShortcuts(QKeySequence::New);

newAct->setStatusTip(tr("Create a new file"));

connect(newAct, SIGNAL(triggered()), this, SLOT(newFile())); 

openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);

openAct->setShortcuts(QKeySequence::Open);

openAct->setStatusTip(tr("Open an existing file"));

connect(openAct, SIGNAL(triggered()), this, SLOT(open())); 

saveAct = new QAction(QIcon(":/images/save.png"), tr("&Save"), this);

saveAct->setShortcuts(QKeySequence::Save);

saveAct->setStatusTip(tr("Save the document to disk"));

connect(saveAct, SIGNAL(triggered()), this, SLOT(save())); 

Page 101: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Create Actions, 2

//Continue specifying actions for rest of menu items

saveAsAct = new QAction(tr("Save &As..."), this);

saveAsAct->setShortcuts(QKeySequence::SaveAs);

saveAsAct->setStatusTip(tr("Save the document under a new name"));

connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs())); 

exitAct = new QAction(tr("E&xit"), this);

cutAct = new QAction(QIcon(":/images/cut.png"), tr("Cu&t"), this);

copyAct = new QAction(QIcon(":/images/copy.png"), tr("&Copy"), this);

pasteAct = new QAction(QIcon(":/images/paste.png"), tr("&Paste"), this);

aboutAct = new QAction(tr("&About"), this);

aboutQtAct = new QAction(tr("About &Qt"), this);

Page 102: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

“Functionality Implemented”, 1newFile, open - functions

// “Functionality” means everything that is done …

// From createActions:

// connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));

void MainWindow::newFile()

{

if (maybeSave()) {

textEdit->clear();

// Next page

setCurrentFile(""); }

void MainWindow::open()

{

if (maybeSave()) {

// Use Qt function

QString fileName = QFileDialog::getOpenFileName(this); // Use it if you have it

if (!fileName.isEmpty())

loadFile(fileName); }

}

Page 103: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Reference

Page 104: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

“Functionality Implemented”, 2setCurrentFile – one function among many

// “Maintain” file name

// E.g., set “” with call from open

void MainWindow::setCurrentFile(const QString &fileName)

{

curFile = fileName;

textEdit->document()->setModified(false);

setWindowModified(false); 

QString shownName;

if (curFile.isEmpty())

shownName = "untitled.txt";

else

shownName = strippedName(curFile); 

setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("Application")));

}

Page 105: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

“Functionality Implemented”, 3save, saveAs – more functions

bool MainWindow::save()

{

// curFile value set in func setCurrentFile

if (curFile.isEmpty()) {

return saveAs();

} else {

return saveFile(curFile);

}

bool MainWindow::saveAs()

{

// Use a Qt widget

QString fileName = QFileDialog::getSaveFileName(this);

if (fileName.isEmpty())

return false; 

return saveFile(fileName);

Page 106: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

“Functionality implemented”, 4saveFile – another function

bool MainWindow::saveFile(const QString &fileName)

{

QFile file(fileName);

if (!file.open(QFile::WriteOnly | QFile::Text)) {

QMessageBox::warning(this, tr("Application"),

tr("Cannot write file %1:\n%2.")

.arg(fileName)

.arg(file.errorString()));

return false;

}

 

QTextStream out(&file);

QApplication::setOverrideCursor(Qt::WaitCursor);

out << textEdit->toPlainText();

QApplication::restoreOverrideCursor(); 

setCurrentFile(fileName);

statusBar()->showMessage(tr("File saved"), 2000); // status bar message

return true;

}

Page 107: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

“Functionality Implemented”, 5loadFile – another function

void MainWindow::loadFile(const QString &fileName)

{

QFile file(fileName);

if (!file.open(QFile::ReadOnly | QFile::Text)) {

QMessageBox::warning(this, tr("Application"),

tr("Cannot read file %1:\n%2.")

.arg(fileName)

.arg(file.errorString()));

return;

QTextStream in(&file);

QApplication::setOverrideCursor(Qt::WaitCursor);

textEdit->setPlainText(in.readAll());

QApplication::restoreOverrideCursor(); 

setCurrentFile(fileName);

statusBar()->showMessage(tr("File loaded"), 2000);

}

Page 108: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

“Functionality Implemented”, 6about

void MainWindow::about()

{

QMessageBox::about(this, tr("About Application"),

tr("The <b>Application</b> example demonstrates how to "

"write modern GUI applications using Qt, with a menu bar, "

"toolbars, and a status bar."));

}

Page 109: Qt – Introduction C++ GUI Programming with Qt 3 Blanchette and Summerfield, Chs. 1-5 Qt Project site, Miller 2004, etc

Summary

• Idea was to provide a “template”, or examples of functionality needed

• There is more to life than file processing …