Presentation is loading. Please wait.

Presentation is loading. Please wait.

QT – Introduction C++ GUI Programming with Qt 4

Similar presentations


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

1 QT – Introduction C++ GUI Programming with Qt 4
Blanchette and Summerfield, Ch. 1, 2 Miller, 2004

2 Software Org. – Window & Graphics Systems
Qt also 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 Overview “Slots” and “signals” for event handling and inter-dialog communication Widget styles Window system native, or common across platforms Qt ide and resources

4 About UI Programming Systems
UI programming systems, or “toolkits”, consist of these elements E.g., GLUT (below) MS windows (below), 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.

5 Examples All 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, …

6 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

7 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

8 Widget Data Data used in widgets Embedded model Linked model
Application data must be copied into the widget Changes must be copied out’ 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

9 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

10 Qt Nokia - Commercial and free

11 Qt Has own ide, which works fine

12 Hello, Qt!

13 Hello, Qt! Example 1 #include <QApplication> #include <QLabel> 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),

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

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

16 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 QObject::connect(button, SIGNAL(clicked()), &app, SLOT(quit())); button->show(); return app.exec(); // Pass control to QT }

17 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

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

19 Create & Synchronize Widgets, 2/3
QSpinBox *spinBox = new QSpinBox; // Create spinbox and slider QSlider *slider = new QSlider(Qt::Horizontal); spinBox->setRange(0, 130); // Set/define range of each slider->setRange(0, 130); // This is easy! // As before, a particular widget signal causes a function (slot) to be called // 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

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

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

22 Qt IDE Works fine

23 Qt IDE Open project Open file

24 Help Works fine

25 Help Works fine

26 QT – Dialogs Blanchette and Summerfield, Ch. 2

27 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

28 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

29 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

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

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

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

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

34 finddialog.cpp Lay out widgets using layout managers
// 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()); }

35 FindDialog Constructors - Parent-child Relationships
text

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

37 3. main.cpp // As before, simply create a new object, here FindDialog, show it, and execuute #include <QApplication> #include "finddialog.h“ int main (int argc, char *argv[]) { QApplication app (argc, argv); FindDialog *dialog = new FindDialog; dialog->show(); return app.exec(); }

38 More about Signals and Slots

39 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

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

41 Signals and Slots, 2 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()));

42 Can Use Signals not only with Widgets, but as More General Mechanism
// Define class class Employee : public QObject { Q_OBJECT public: Employee() { mySalary = 0; } int salary() const { return mySalary; } public slots: void setSalary (int newSalary); signals: void salaryChanged (int newSalary); private: int mySalary; }; // Use signal to communicate with any/all slots // (functions) connected to salaryChanged // signal! void Employee::setSalary (int newSalary) { if (newSalary != mySalary) { mySalary = newSalary; emit salaryChanged (mySalary); }

43 Qt Designer x

44 Qt Designer x

45 Qt Designer .

46 End .


Download ppt "QT – Introduction C++ GUI Programming with Qt 4"

Similar presentations


Ads by Google