Qt – Introduction C++ GUI Programming with Qt 3

Slides:



Advertisements
Similar presentations
First Steps with Qt Julien Finet Kitware Inc. Jan. 05 th 2010.
Advertisements

Lecture 4: Embedded Application Framework Qt Tutorial Cheng-Liang (Paul) Hsieh ECE 424 Embedded Systems Design.
QT GUI Programming CS340 – Software Design © 2009 – Jason Leigh University of Illinois at Chicago.
QT – Introduction C++ GUI Programming with Qt 4 Blanchette and Summerfield, Ch. 1 Miller, 2004.
© by Pearson Education, Inc. All Rights Reserved.
Chapter 6 Multiform Projects Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Guide to Oracle10G1 Introduction To Forms Builder Chapter 5.
Automating Tasks With Macros
A Guide to Oracle9i1 Introduction To Forms Builder Chapter 5.
Automating Tasks With Macros. 2 Design a switchboard and dialog box for a graphical user interface Database developers interact directly with Access.
Chapter 2: The Visual Studio.NET Development Environment Visual Basic.NET Programming: From Problem Analysis to Program Design.
Object-Oriented Analysis and Design
1 Introduction to the Visual Studio.NET IDE Powerpoint slides modified from Deitel & Deitel.
QT Intro. 김기형
2. Introduction to the Visual Studio.NET IDE 2. Introduction to the Visual Studio.NET IDE Ch2 – Deitel’s Book.
Blanchette and Summerfield, Ch. 2
Welcome to CIS 083 ! Events CIS 068.
Department of Mechanical Engineering, LSUSession VII MATLAB Tutorials Session VIII Graphical User Interface using MATLAB Rajeev Madazhy
Introduction to Visual Basic. Quick Links Windows Application Programming Event-Driven Application Becoming familiar with VB Control Objects Saving and.
IE 411/511: Visual Programming for Industrial Applications
Creating a Web Site to Gather Data and Conduct Research.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Microsoft Access Lesson 1 Lexington Technology Center February 11, 2003 Bob Herring On the Web at
Designing Interface Components. Components Navigation components - the user uses these components to give instructions. Input – Components that are used.
Chapter 3 – Part 1 Word Processing Writer for Linux CMPF 112 : COMPUTING SKILLS.
XP New Perspectives on Microsoft Office Access 2003, Second Edition- Tutorial 2 1 Microsoft Office Access 2003 Tutorial 2 – Creating And Maintaining A.
Chapter One An Introduction to Visual Basic 2010 Programming with Microsoft Visual Basic th Edition.
Object Oriented Software Development 9. Creating Graphical User Interfaces.
Adding a New Option to the Framework. Introduction This is intended as a step by step guide to adding a new action to the menu or toolbar. The order of.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Creating Graphical User Interfaces (GUI’s) with MATLAB By Jeffrey A. Webb OSU Gateway Coalition Member.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
 2006 Pearson Education, Inc. All rights reserved Introduction to the Visual C# 2005 Express Edition IDE.
C# GUI - Basics. Objectives.NET supports two types: WinForms, traditional, desktop GUI apps. WebForms – newer, for Web apps. Visual Studio.NET supports.
Chapter 2 – Introduction to the Visual Studio .NET IDE
Dale Roberts Introduction to Visual Programming Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
Java Applets: GUI Components, Events, Etc. Ralph Westfall June, 2010.
QT – Dialog C++ GUI Programming with Qt 4 Qt 4.5 Reference Documentation Blanchette and Summerfield, Ch. 3.
-1- National Alliance for Medical Image Computing First Steps with Qt Julien Finet Kitware Inc. Jan. 05 th 2010.
3 Copyright © 2004, Oracle. All rights reserved. Working in the Forms Developer Environment.
Copyright © Curt Hill More Components Varying the input of Dev-C++ Windows Programs.
XP New Perspectives on Microsoft Office Access 2003 Tutorial 10 1 Microsoft Office Access 2003 Tutorial 10 – Automating Tasks With Macros.
Class Builder Tutorial Presented By- Amit Singh & Sylendra Prasad.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
QT Programming QT Programming Ruku Roychowdhury. Background QT is a cross platform application framework. Widely used to develop GUI applications. Originally.
GUIs Basic Concepts. GUI GUI : Graphical User Interface Window/Frame : a window on the screen Controls/Widgets : GUI components.
 2002 Prentice Hall. All rights reserved. 1 Chapter 2 – Introduction to the Visual Studio.NET IDE Outline 2.1Introduction 2.2Visual Studio.NET Integrated.
Chapter 5 Introduction To Form Builder. Lesson A Objectives  Display Forms Builder forms in a Web browser  Use a data block form to view, insert, update,
QT – Introduction C++ GUI Programming with Qt 4
Fall UI Design and Implementation1 Lecture 17: Toolkits.
Object-Oriented Application Development Using VB.NET 1 Chapter 2 The Visual Studio.NET Development Environment.
Microsoft Office 2013 Try It! Chapter 4 Storing Data in Access.
QT – Windows, menus, and such C++ GUI Programming with Qt 4 Qt 4.5 Reference Documentation Blanchette and Summerfield, Ch. 3.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Address Book Application Introducing Database Programming.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Creating New Forms Projects can appear more professional when using different windows for different types of information. Select Add Windows Form from.
IE 411/511: Visual Programming for Industrial Applications Lecture Notes #2 Introduction to the Visual Basic Express 2010 Integrated Development Environment.
LCG AA Meeting 30 June 2004 Ilka Antcheva Graphics User Interface in ROOT.
 2002 Prentice Hall. All rights reserved. 1 Introduction to the Visual Studio.NET IDE Outline Introduction Visual Studio.NET Integrated Development Environment.
Chapter 2: The Visual Studio.NET Development Environment Visual Basic.NET Programming: From Problem Analysis to Program Design.
Working in the Forms Developer Environment
Chap 7. Building Java Graphical User Interfaces
Graphical User Interfaces -- Introduction
Chapter 2 – Introduction to the Visual Studio .NET IDE
Custom Widgets & Events
Constructors, GUI’s(Using Swing) and ActionListner
6. WinForms 2003 C# GUI - Basics.
Overview of the IDE Visual Studio .NET is Microsoft’s Integrated Development Environment (IDE) for creating, running and debugging programs (also.
Presentation transcript:

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

Recall, Software Organization for Window & 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) GLUT, Qt GLU GL GLX, AGL or WGL X, Win32, Mac O/S software and/or hardware application program OpenGL Motif widget or similar window system graphics system

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 Event – user, system, program 1 2 Program’s GLUT callback may change state of program Draw Display (myDisplay)

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 Event – user, system, program 1 2 Program’s GLUT callback may change state of program requiring redraw PostRedisplay() Draw Display (myDisplay)

Event – user, system, program Qt, Paradigm Control Structure 1. Qt “slots” are functions like similar to e.g., glutMouseFunc Something happens - an “event” 1. System may cause redraw, i.e., call “myDisplay” done by Qt E.g., move window off GLUT display function called 2. GLUT Qt callback may handle, if defined E.g., glutMouseFunc – myMouse Qt slot 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 Event – user, system, program 1 2 Program’s GLUT Qt callback may change state of program requiring redraw PostRedisplay() Draw Display (myDisplay)

Qt, Paradigm Control Structure 2. Qt handles redraw Something happens - an “event” 1. System may cause redraw, i.e., call “myDisplay” done by Qt E.g., move window off GLUT display function called 2. GLUT Qt callback may handle, if defined E.g., glutMouseFunc – myMouse Qt slot 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 Event – user, system, program 1 2 Program’s GLUT Qt callback may change state of program requiring redraw PostRedisplay() Draw Display (myDisplay)

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”

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 Windows Components (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.

Examples All ui programming systems have these basic elements: MS Windows Swing HTML Qt Components Windows JComponents Elements Strokes GDI Graphics (none) 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, …

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

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

Widget Data Data used in widgets 1. Embedded model 2. Linked 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

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

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

“Qt Project” Download and install about as easy as it gets Examples from Qt 3 and 4 Haven’t tried 5.0

Qt - ide Has own ide, which works fine – all the usual things Even good, when working with Qt widgets vs. e.g., Glut

Qt – dialog box editor Even own dialog box editor

Hello, Qt!

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

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)

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)

A Signal and A Slot Example 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 }

Synchronization & Layout of 2 Widgets Example 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

“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

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

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

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)

Qt IDE Works fine

Qt IDE Open project Open file

Help Works fine

Help Works fine

QT – Dialogs Blanchette and Summerfield, Ch. 2

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

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

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

1. finddialog.h Set 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;

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

2. finddialog.cpp Implement 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"));

finddialog.cpp Connect 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 ()));

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

FindDialog Constructors - Parent-child Relationships text

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

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

More about Signals and Slots

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

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))); 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()), When either signal is emitted, the slot is called.

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

Qt Designer “visual” dialog box design tool Layout (positioning) of widgets – buttons, check boxes, …

Qt Designer x

Qt Designer x

Qt Designer .

Qt Dialog: Overview

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

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

Addressbook Subclass & Widgets Addressbook will be subclass of QWidget Widgets (elements) QLabel objects nameLabel, addresslabel Input fields – objects QLineEdit: nameLine QTextEdit: addressText

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.

addressbook.h Defines 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 };

addressbook.cpp – Part 1 Implements 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;

addressbook.cpp Implements 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")); }

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

addressbook. cpp – Part 2 Implements addressbook class – 1 addressbook.cpp – Part 2 Implements 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();

addressbook. cpp – Part 2 Implements addressbook class – 2 addressbook.cpp – Part 2 Implements 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()));

addressbook. cpp – Part 2 Implements addressbook class – 3 addressbook.cpp – Part 2 Implements 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")); }

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

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

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

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

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

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

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

And that’s all there is to mainwindow.h! … and mainwindow.cpp holds the implementation

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

mainwindow.cpp creating 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()));

mainwindow.cpp creating 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

mainwindow.cpp Building 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;

mainwindow.cpp Building 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);

mainwindow.cpp toolbars 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); }

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

mainwindow.cpp context 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;

Implementing Functionality What 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()));

Implementing Functionality What 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 © 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.")); }

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

Recall, findDialog

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

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

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

Other Dialogs for Spreadsheet Many examples provided in chapter Some straightforward Some arcane When in doubt … keep it simple

Qt – Functionality, Custom Widgets Blanchette and Summerfield, Ch. 4,5

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

Application Example Application with menus, toolbars, and status bar Simple text editor program built around QTextEdit “Powerful” Qt widget Many others … Documentation next

QTextEdit Reference, 1 A widget that is a text editor! Note properties And where come from

QTextEdit Reference, 2 Slots and signals

QTextEdit Reference, 3 Functions

MainWindow Class Definition mainwindow MainWindow Class Definition mainwindow.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; …

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

MainWindow Class Implementation mainwindow.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); } 

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

Creating Menu Items with Actions mainwindow.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); } 

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

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

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

“Functionality Implemented”, 1 newFile, 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() // Use Qt function QString fileName = QFileDialog::getOpenFileName(this); // Use it if you have it if (!fileName.isEmpty()) loadFile(fileName); } }

Reference

“Functionality Implemented”, 2 setCurrentFile – 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"))); }

“Functionality Implemented”, 3 save, 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);

“Functionality implemented”, 4 saveFile – 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;

“Functionality Implemented”, 5 loadFile – 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); }

“Functionality Implemented”, 6 about 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.")); }

Summary Idea was to provide a “template”, or examples of functionality needed There is more to life than file processing …