programming with qt

26
Dale Roberts Programming with Qt Programming with Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: [email protected] Department of Computer and Information Science, School of Science, IUPUI

Upload: keiran

Post on 12-Jan-2016

50 views

Category:

Documents


1 download

DESCRIPTION

Department of Computer and Information Science, School of Science, IUPUI. Programming with Qt. Dale Roberts, Lecturer Computer Science, IUPUI E-mail: [email protected]. Outline. The Qt Story The Layered X Programming APIs Implementing Cross-Platform GUI Libraries A Simple Example - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Programming with Qt

Dale Roberts

Programming with QtProgramming with Qt

Dale Roberts, LecturerComputer Science, IUPUIE-mail: [email protected]

Department of Computer and Information Science,School of Science, IUPUI

Page 2: Programming with Qt

Dale Roberts

OutlineOutline

The Qt StoryThe Qt Story

The Layered X Programming APIsThe Layered X Programming APIs

Implementing Cross-Platform GUI LibrariesImplementing Cross-Platform GUI Libraries

A Simple ExampleA Simple Example

Callback FunctionCallback Function

Signals and SlotsSignals and Slots

Other Features of QtOther Features of Qt

Page 3: Programming with Qt

Dale Roberts

GUI toolkitsGUI toolkits

Windows – MFCWindows – MFC

Mac – MacOSMac – MacOS

Unix – many. Most popular: Motif (on which CDE is Unix – many. Most popular: Motif (on which CDE is based). Specifies look and feel. based). Specifies look and feel.

(Difficult, error-prone, and not much fun.)(Difficult, error-prone, and not much fun.)

QT: portableQT: portable"framework" – also handles sending events to widgets"framework" – also handles sending events to widgets

Not based on layering (too slow, LCD)Not based on layering (too slow, LCD)

Not based on API emulation (slow; different platforms require Not based on API emulation (slow; different platforms require different APIdifferent API

Based on GUI emulation Based on GUI emulation

Page 4: Programming with Qt

Dale Roberts

Signals and SlotsSignals and Slots

Various Various widgetswidgets

Panes – Panes – splittersplitter

Tables – Tables – tabletable

XML parsing – XML parsing – tagreadertagreader

Networking, sound, printingNetworking, sound, printing

2D graphics – 2D graphics – drawlinesdrawlines canvascanvas xformxform

OpenGL support – OpenGL support – geargear

OpenGL widgets, pixmaps – OpenGL widgets, pixmaps – glpixmapsglpixmaps

Page 5: Programming with Qt

Dale Roberts

The Qt StoryThe Qt StoryThe Qt toolkit is a multi-platform C++ GUI toolkit (class library) that The Qt toolkit is a multi-platform C++ GUI toolkit (class library) that has been developed over a 4 year period. has been developed over a 4 year period.

The company Troll Tech AS was founded in 1994 to secure future The company Troll Tech AS was founded in 1994 to secure future development of Qt. development of Qt.

Qt for X11 has a non-commercial license which grants any Qt for X11 has a non-commercial license which grants any developer the right to use Qt to develop software for the free developer the right to use Qt to develop software for the free software community.software community.

Qt allows the user to choose between the Motif and the Windows Qt allows the user to choose between the Motif and the Windows look and feel.look and feel.

Page 6: Programming with Qt

Dale Roberts

The Layered X Programming APIsThe Layered X Programming APIs

Page 7: Programming with Qt

Dale Roberts

Implementing Cross-Platform GUI LibrariesImplementing Cross-Platform GUI Libraries

Three typical approaches for developing a cross-platform product Three typical approaches for developing a cross-platform product are toare to1. “Dumb-down” the components1. “Dumb-down” the components2. Map the components onto an existing API2. Map the components onto an existing API3. “Smart-up” the components3. “Smart-up” the components

Page 8: Programming with Qt

Dale Roberts

““Dumbing-down” ComponentsDumbing-down” ComponentsAPI LayeringAPI Layering- e.g. wxWindows- e.g. wxWindows- advantage:- advantage:

1. easy to program1. easy to program2. look-and-feel is 100% compatible with the 2. look-and-feel is 100% compatible with the native look-and-feelnative look-and-feel

- disadvantage:- disadvantage:1. slower1. slower2. awkward control flow2. awkward control flow3. typically provide the lowest common denominat3. typically provide the lowest common denominat

oror of functionalityof functionality4. difficult to inherit widgets and specialize them4. difficult to inherit widgets and specialize them

Page 9: Programming with Qt

Dale Roberts

““Mapping” ComponentsMapping” Components

API emulationAPI emulation

- e.g. MainWin, Wind/U- e.g. MainWin, Wind/U

- advantage:- advantage:

1. not necessary to emulate original platform1. not necessary to emulate original platform

- disadvantage:- disadvantage:

1. too different for making API emulation very1. too different for making API emulation very

practicalpractical

2. emulated platform would be slower2. emulated platform would be slower

3. unstable3. unstable

Page 10: Programming with Qt

Dale Roberts

““Smarting-up” ComponentsSmarting-up” Components

GUI emulationGUI emulation- e.g. Qt- e.g. Qt- advantage:- advantage:

1. fastest1. fastest2. changeable style2. changeable style3. easy to inherit widgets and to redefine its3. easy to inherit widgets and to redefine its behaviorbehavior

- disadvantage:- disadvantage:1. can’t 100% exact1. can’t 100% exact2. codes has to rewritten if a new widget be created2. codes has to rewritten if a new widget be created

Page 11: Programming with Qt

Dale Roberts

A Simple ExampleA Simple Example/* HelloWorld.cpp *//* HelloWorld.cpp */

1 #include <qapplication.h>1 #include <qapplication.h> 2 #include <qlabel.h>2 #include <qlabel.h> 33 4 int main(int argc, char **argv) {4 int main(int argc, char **argv) { 55 6 QApplication myapp(argc, argv);6 QApplication myapp(argc, argv); 77 8 Qlabel *mylabel = new Qlabel(“Hello World”);8 Qlabel *mylabel = new Qlabel(“Hello World”); 9 mylabel->resize(100, 200);9 mylabel->resize(100, 200);101011 myapp.setMainWidget(mylabel);11 myapp.setMainWidget(mylabel);1212 mylabel->show(); mylabel->show();1313 return myapp.exec(); return myapp.exec();14 }14 }

Page 12: Programming with Qt

Dale Roberts

Callback FunctionCallback FunctionOne of the most feared and hackish aspects of GUI programming hOne of the most feared and hackish aspects of GUI programming has always been the dreaded callback-function.as always been the dreaded callback-function.A register table for widget (e.g. Motif) A register table for widget (e.g. Motif) - no type checking- no type checking- example:- example: 1. quit = XtVaCreateManagedWidget(……);1. quit = XtVaCreateManagedWidget(……); 2. XtAddCallback(quit, XmNactivateCallback,2. XtAddCallback(quit, XmNactivateCallback,

QuitCallback, NULL);QuitCallback, NULL); 3. void QuitCallback(Widget w, XtPointer3. void QuitCallback(Widget w, XtPointer

clientData, XtPointer callData){clientData, XtPointer callData){ exit(0);exit(0); }}

Page 13: Programming with Qt

Dale Roberts

Callback Function(cont)Callback Function(cont)Virtual function(e.g. wxWindows)Virtual function(e.g. wxWindows)

- too many classes need to inherit for all widgets- too many classes need to inherit for all widgets

- high dependence between GUI and kernel of application- high dependence between GUI and kernel of application

- would be slower in a inefficient vtable- would be slower in a inefficient vtable

Macro(e.g. MFCMacro(e.g. MFC 、、 OWL)OWL)

- message map was complicated and difficult to codeing- message map was complicated and difficult to codeing

- need additional preprocess, IDE or application builder- need additional preprocess, IDE or application builder

Page 14: Programming with Qt

Dale Roberts

Event HandlingEvent Handling

QT's new approach: signals and slotsQT's new approach: signals and slotsA widget sends out various A widget sends out various signalssignals

Object methods can be declared as Object methods can be declared as slotsslots

Compatible signals and slots can be Compatible signals and slots can be connectedconnected or or plugged together like a telephone switchboard (parameter plugged together like a telephone switchboard (parameter types must match)types must match)

Strict separation Strict separation This strict separation between UI components and This strict separation between UI components and program elements lends itself to component-based program elements lends itself to component-based programmingprogramming

Goal: separate UI from program logicGoal: separate UI from program logic

Page 15: Programming with Qt

Dale Roberts

Signals and SlotsSignals and Slots

Page 16: Programming with Qt

Dale Roberts

Signals and Slots (cont)Signals and Slots (cont)

advantage:advantage:

- independent interface- independent interface

- type-safe- type-safe

- process transparence- process transparence

disadvantage:disadvantage:

- not as fast as a direct function pointer call. - not as fast as a direct function pointer call.

( ( A signal triggering a slot has been measured to A signal triggering a slot has been measured to

approximately 50 microseconds on a SPARC2. )approximately 50 microseconds on a SPARC2. )

Page 17: Programming with Qt

Dale Roberts

Signals and Slots(cont)Signals and Slots(cont)

1 class PixmapRotator : public QWidget { 1 class PixmapRotator : public QWidget { 2 2 Q_OBJECTQ_OBJECT 3 public: 3 public: 4 PixmapRotator(QWidget *parent=0, const char *name=0);4 PixmapRotator(QWidget *parent=0, const char *name=0); 5 public 5 public slotsslots: : 6 void setAngle(int degrees); 6 void setAngle(int degrees); 7 7 signalssignals: : 8 void angleChanged(int); 8 void angleChanged(int); 9 private: 9 private: 10 int ang; 10 int ang; 11 }; 11 }; 12 void PixmapRotator::setAngle( int degrees ) { 12 void PixmapRotator::setAngle( int degrees ) { 13 degrees = degrees % 360;13 degrees = degrees % 360; // keep in range <-360, 360> // keep in range <-360, 360> 14 if(ang == degrees) 14 if(ang == degrees) 15 return; 15 return; // actual state change? // actual state change? 16 ang = degrees; 16 ang = degrees; // a new angle // a new angle 17 17 emitemit angleChanged(ang); angleChanged(ang); // tell world ... // tell world ... 18 } 18 } 19 QObject::connect(scrollBar, 19 QObject::connect(scrollBar, SIGNALSIGNAL(valueChanged(int)), rotator, (valueChanged(int)), rotator,

SLOTSLOT(setAngle(int))); (setAngle(int)));

Page 18: Programming with Qt

Dale Roberts

Signals and Slots(cont)Signals and Slots(cont)

Qt meta object compiler (moc)Qt meta object compiler (moc)- It parses C++ header files and generates C++ code- It parses C++ header files and generates C++ code

necessary for Qt to handle signals and slots. The signals,necessary for Qt to handle signals and slots. The signals,

slots and emit keywords are macros, so the compilerslots and emit keywords are macros, so the compiler

preprocessor changes or removes them. preprocessor changes or removes them.

How to do?How to do? 1. moc –o moc_file.moc moc_file.cpp moc_file.h1. moc –o moc_file.moc moc_file.cpp moc_file.h

2. #include “moc_file.moc”2. #include “moc_file.moc”

Page 19: Programming with Qt

Dale Roberts

Defining Signals and SlotsDefining Signals and Slots

New C++ syntax for defining signals and slots, New C++ syntax for defining signals and slots, added to public, private, etc.added to public, private, etc.class myClass : public Qobject {class myClass : public Qobject {

Q_OBJECTQ_OBJECT //required macro, no semicolon//required macro, no semicolon

……

signals:signals:

void somethingHappened();void somethingHappened();

… …

public slots:public slots:

void slotDoSomething();void slotDoSomething();

……

private slots:private slots:

void slotDoSomethingInternal();void slotDoSomethingInternal();

……

};};

Page 20: Programming with Qt

Dale Roberts

EventsEvents

Signals: emit eventsSignals: emit eventsdeclare as signals, otherwise normal member functionsdeclare as signals, otherwise normal member functionsYou don't implement them. Rather, you send them with You don't implement them. Rather, you send them with the (new) keyword emitthe (new) keyword emitE.g. emit(sliderChanged(5))E.g. emit(sliderChanged(5))

Slots: receive and handle eventsSlots: receive and handle eventsNormal member functions declared as slotsNormal member functions declared as slots

Connect: must connect signals to slotsConnect: must connect signals to slotsQObject::connect( mymenu, SIGNAL(activated(int)), QObject::connect( mymenu, SIGNAL(activated(int)), myobject, SLOT(slotDoMenuFunction(int)) );myobject, SLOT(slotDoMenuFunction(int)) );

moc: meta object compiler (preprocessor) moc: meta object compiler (preprocessor) converts these new keywords to real C++converts these new keywords to real C++

Page 21: Programming with Qt

Dale Roberts

WidgetsWidgets

Base class for all UI widgetsBase class for all UI widgets

PropertiesPropertieswidth, height, backgroundColor, font, mouseTracking, width, height, backgroundColor, font, mouseTracking, backgroundPixmap, etc.backgroundPixmap, etc.

SlotsSlotsrepaint, show, hide, move, setGeometry, setMainWidget, repaint, show, hide, move, setGeometry, setMainWidget, etc.etc.

Signals:Signals:mouseMoveEvent, keyPressEvent, resizeEvent, mouseMoveEvent, keyPressEvent, resizeEvent, paintEvent, enterEvent, leaveEvent, etc.paintEvent, enterEvent, leaveEvent, etc.

Page 22: Programming with Qt

Dale Roberts

Qt, a GUI toolkitQt, a GUI toolkit

Events processed with signals and slotssignal generates an event, e.g., button push

slot processes the event, e.g., pop up a file dialog box

QPushButton * quitB = new QPushButton(“Quit”,...,...);

connect (quitB, SIGNAL(clicked()), qApp, SLOT(quit());qApp is a global variable, of type QApplication

one QApplication per program defined first in main()

main returns qApp.exec()

SIGNAL and SLOT are macros, expanded by a meta-object

compiler (moc)moc generates .cpp files from user-defined Qt subclasses

Page 23: Programming with Qt

Dale Roberts

Designing GUI’sDesigning GUI’s

What about Designing GUIs?Design decisions: who designs the GUI?

What (if anything) do you need to know about app internals?

Qt expertise, who has it? [remember, Java on the horizon]

ImplementationLay out the GUI [draw it, sketch it]

get the main widgets up and running, but not connected

develop methods/events that are application specific

develop commands, menus, buttons, etc.

Compiling using moc, Qt classes, seeMakefile

Page 24: Programming with Qt

Dale Roberts

Other Features of QtOther Features of QtThe Qt Paint EngineThe Qt Paint Engine- QPainter- QPainter is highly optimized and contains several is highly optimized and contains several

caching mechanisms to speed up drawing. Under X11, caching mechanisms to speed up drawing. Under X11, it caches GCs (graphics contexts), which often make itit caches GCs (graphics contexts), which often make it faster than native X11 programs.faster than native X11 programs.

- QPainter- QPainter contains all the functionality one would expect contains all the functionality one would expect from a professional 2D graphics library. The coordinatefrom a professional 2D graphics library. The coordinate system of a QPainter can be transformed using the system of a QPainter can be transformed using the standard 2D transformations (translate, scale, rotate andstandard 2D transformations (translate, scale, rotate and

shear).shear).

Page 25: Programming with Qt

Dale Roberts

Other Features of Qt(cont)Other Features of Qt(cont)

Support ClassesSupport Classes

- Qt also contains a set of general purpose classes and a - Qt also contains a set of general purpose classes and a

number of collection-classes to ease the development ofnumber of collection-classes to ease the development of

multi-platform applications.multi-platform applications.

- Qt has platform independent support for the operating- Qt has platform independent support for the operating

system dependent functions, such as time/date, system dependent functions, such as time/date,

files/directories and TCP/IP sockets.files/directories and TCP/IP sockets.

Page 26: Programming with Qt

Dale Roberts

AcknowledgementsAcknowledgements

Plantinga, Harry. Calvin CollegePlantinga, Harry. Calvin College

Trolltech Tutorials.Trolltech Tutorials.