Presentation is loading. Please wait.

Presentation is loading. Please wait.

Qt – Introduction C++ GUI Programming with Qt 3

Similar presentations


Presentation on theme: "Qt – Introduction C++ GUI Programming with Qt 3"— Presentation transcript:

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

2 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

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

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

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

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

7 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”

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

9 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, …

10 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

11 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

12 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

13 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

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

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

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

17 Qt – dialog box editor Even own dialog box editor

18 Hello, Qt!

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

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

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

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

23 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

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

25 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

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

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

28 Qt IDE Works fine

29 Qt IDE Open project Open file

30 Help Works fine

31 Help Works fine

32 QT – Dialogs Blanchette and Summerfield, Ch. 2

33 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

34 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

35 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

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

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

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

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

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

41 FindDialog Constructors - Parent-child Relationships
text

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

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

44 More about Signals and Slots

45 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

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

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

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

49 Qt Designer x

50 Qt Designer x

51 Qt Designer .

52 Qt Dialog: Overview

53 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

54 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

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

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

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

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

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

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

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

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

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

64 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

65 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

66 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

67 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

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

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

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

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

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

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

74 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

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

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

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

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

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

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

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

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

83 Recall, findDialog

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

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

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

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

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

89 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

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

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

92 QTextEdit Reference, 2 Slots and signals

93 QTextEdit Reference, 3 Functions

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

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

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

97 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

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

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

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

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

102 “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); } }

103 Reference

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

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

106 “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;

107 “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); }

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

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


Download ppt "Qt – Introduction C++ GUI Programming with Qt 3"

Similar presentations


Ads by Google