dale roberts introduction to qt dale roberts, lecturer computer science, iupui e-mail:...

35
Dale Roberts Introduction to Qt Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: [email protected] Department of Computer and Information Science, School of Science, IUPUI

Upload: georgia-shelton

Post on 23-Dec-2015

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Introduction to QtIntroduction to Qt

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

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

Page 2: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

GUI HistoryGUI HistoryIn 1962, Douglas Engelbart In 1962, Douglas Engelbart invented the first “mouse,” invented the first “mouse,” which he called an “X-Y which he called an “X-Y Position Indicator.”Position Indicator.”It was a little gizmo housed in It was a little gizmo housed in a wooden box on wheels that a wooden box on wheels that moved around the desktop and moved around the desktop and took the cursor with it on the took the cursor with it on the display. display.

Source: US Patent Office

Page 3: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

GUI HistoryGUI History

In 1963 a grad student at In 1963 a grad student at MIT, Ivan Sutherland, MIT, Ivan Sutherland, submitted as his thesis a submitted as his thesis a program called program called “Sketchpad.” This was “Sketchpad.” This was the first GUI (Graphical the first GUI (Graphical User Interface) long User Interface) long before the term was before the term was coined." coined."

http://accad.osu.edu/~waynec/history/images/ivan-sutherland.jpg

Page 4: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

GUI HistoryGUI History

In the 1970s, at Xerox’s In the 1970s, at Xerox’s PARC facility, Alan Keys PARC facility, Alan Keys created an object-created an object-oriented graphical oriented graphical programming language programming language called “Smalltalk.” called “Smalltalk.” Smalltalk featured a Smalltalk featured a graphical user interface graphical user interface (GUI) that looked (GUI) that looked suspiciously similar to suspiciously similar to later iterations from both later iterations from both Apple and Microsoft. Apple and Microsoft.

http://www.sra.co.jp/people/aoki/SqueakIdioms/chapter01/Xerox1100SIP.jpg

Page 5: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

GUI HistoryGUI History1981, Xerox attempted to 1981, Xerox attempted to market the “Star.” It market the “Star.” It introduced the idea of what introduced the idea of what you see is what you get you see is what you get (WYSIWYG). (WYSIWYG). Commercial failureCommercial failure

cost ($15,000); cost ($15,000); IBM had just announced a less IBM had just announced a less expensive machineexpensive machine

limited functionalitylimited functionalitye.g., no spreadsheete.g., no spreadsheet

closed architecture, closed architecture, 3rd party vendors could not add 3rd party vendors could not add applicationsapplications

perceived as slow perceived as slow but really fast!but really fast!

slavish adherence to direct slavish adherence to direct manipulationmanipulation

http://www.catb.org/~esr/writings/taouu/html/graphics/xerox_star.jpg

Page 6: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Apple gets a GUIApple gets a GUI

In 1983, the Apple Lisa In 1983, the Apple Lisa was first GUI offering.was first GUI offering.

http://fp3.antelecom.net/gcifu/applemuseum/lisa2.html

http://www.s-line.de/homepages/horber-privat/bilder/apple2a.jpg

Apple II, 1980

Lisa

Page 7: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Apple gets a GUIApple gets a GUIIn 1984, Macintosh was the first In 1984, Macintosh was the first computer with a GUI marketed to computer with a GUI marketed to the masses.the masses.

““old ideas” but well done! old ideas” but well done!

Commercial success because:Commercial success because:aggressive pricing ($2500)aggressive pricing ($2500)did not need to trail blaze did not need to trail blaze

learned from mistakes of Lisa and learned from mistakes of Lisa and corrected them; ideas now “mature”corrected them; ideas now “mature”market now ready for themmarket now ready for them

developer’s toolkit encouraged 3rd developer’s toolkit encouraged 3rd party non-Apple software party non-Apple software interface guidelines encouraged interface guidelines encouraged consistency between applicationsconsistency between applicationsdomination in desktop publishing domination in desktop publishing because of affordable laser printer because of affordable laser printer and excellent graphicsand excellent graphicsFull Microsoft Office suiteFull Microsoft Office suite(Apple was the dominant player at (Apple was the dominant player at this time.)this time.)

http://computermuseum.50megs.com/images/collection/apple-mac-plus.jpg

http://toastytech.com/guis/bigmac1.gif

Page 8: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Unix Gets a GUIUnix Gets a GUIThe X Windows System was The X Windows System was introduced in the mid-1980s to introduced in the mid-1980s to provide graphical support for provide graphical support for unix operating systems.unix operating systems.The implementation was a The implementation was a client-server approach, where client-server approach, where an X window system server an X window system server ran on the displaying machine, ran on the displaying machine, and the client programs and the client programs communicated with it using a communicated with it using a network protocol.network protocol.X provides only a X provides only a communication communication mechanism, mechanism, not policynot policy. At least three major . At least three major user interface look & feel user interface look & feel styles are widely used on X - styles are widely used on X - MIT's own Athena style, Sun MIT's own Athena style, Sun and AT&T's OpenLook, and and AT&T's OpenLook, and OSF's Motif (supported OSF's Motif (supported primarily by HP and IBM). primarily by HP and IBM).

http://www.pattosoft.com.au/jason/Articles/HistoryOfComputers/X11.gif

Page 9: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Microsoft Gets a GUIMicrosoft Gets a GUI

Microsoft introduced Microsoft introduced Windows 1.0 in 1985Windows 1.0 in 1985

Tiled Windows, no Tiled Windows, no overlappingoverlapping

Windows 2.03 in 1987Windows 2.03 in 1987Overlapping windowsOverlapping windows

Windows 3.0 in 1990Windows 3.0 in 1990Features Program ManagerFeatures Program Manager

Page 10: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

ShellsShellsUnix and DOS operating systems circa 1980s do support Unix and DOS operating systems circa 1980s do support text-based user interfaces via a program called a shell. text-based user interfaces via a program called a shell. These shells insert another layer between the user and These shells insert another layer between the user and the operating system. Typical text shells under unix are the operating system. Typical text shells under unix are csh and ksh. The typical text shell under microsoft is csh and ksh. The typical text shell under microsoft is command.com. It is still emulated today by cmd.exe. command.com. It is still emulated today by cmd.exe. Original unix and Microsoft GUI support was also Original unix and Microsoft GUI support was also implemented as shells. The dominant unix GUI library implemented as shells. The dominant unix GUI library became an open library called X11 supported by the became an open library called X11 supported by the X.org foundation. Microsoft introduced Windows 1.0 as X.org foundation. Microsoft introduced Windows 1.0 as a shell that ran on a layer above MS-DOS. a shell that ran on a layer above MS-DOS. The original Apple GUI is embedded into its operating The original Apple GUI is embedded into its operating system kernel. Windows migrated to embedding GUI system kernel. Windows migrated to embedding GUI support beginning with Windows NT.support beginning with Windows NT.

Page 11: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Windows TimelineWindows Timeline

It took roughly 15 years It took roughly 15 years to consolidate its shell-to consolidate its shell-based GUI architecture based GUI architecture offerings with its offerings with its embedded GUI embedded GUI architecture offerings.architecture offerings.

http://www.microsoft.com/windows/WinHistoryProGraphic.mspx

Page 12: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

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 6 year period. has been developed over a 6 year period.

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

On May 20, 1995, Qt was made available under commercial and non-On May 20, 1995, Qt was made available under commercial and non-commercial GNU licenses. The non-commercial license grants any commercial GNU licenses. The non-commercial license grants any developer the right to use Qt to develop software for the free softwadeveloper the right to use Qt to develop software for the free software community.re community.

It was ten months before the first commercial license was purchaseIt was ten months before the first commercial license was purchased. The European Space Agency purchased the second.d. The European Space Agency purchased the second.

Around 1997, Qt was chosen as the code basis for the KDE linux deAround 1997, Qt was chosen as the code basis for the KDE linux desktop environment.sktop environment.

Qt 3.0 was released in 2001 with Windows, Unix, Linux, Embedded LQt 3.0 was released in 2001 with Windows, Unix, Linux, Embedded Linux, and Mac OS X libraries.inux, and Mac OS X libraries.

Page 13: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Why GUI Toolkits?Why GUI Toolkits?Unix GUIs are typically based on the X Window System.Unix GUIs are typically based on the X Window System.Primitive X11 functions let you draw primitive graphics Primitive X11 functions let you draw primitive graphics like line and rectangles, set foreground and background like line and rectangles, set foreground and background colors, and (most importantly) interact with the user and colors, and (most importantly) interact with the user and send events back to the server.send events back to the server.The functions are network transparent, meaning that the The functions are network transparent, meaning that the server can display graphic on the local workstation or server can display graphic on the local workstation or across the world. This is the same model as telnet.across the world. This is the same model as telnet.Programming graphical objects like buttons, scrollbars, Programming graphical objects like buttons, scrollbars, dialog boxes, and toolbars is very difficult using pure dialog boxes, and toolbars is very difficult using pure X11.X11.GUI Toolkits facilitate GUI programming under Unix.GUI Toolkits facilitate GUI programming under Unix.Motif is both a GUI toolkit and popular GUI standard. Motif is both a GUI toolkit and popular GUI standard. Dalheimer argues that it is does not support type safety Dalheimer argues that it is does not support type safety and is awkward compared to Qt. However, Qt does and is awkward compared to Qt. However, Qt does support the Motif look-and-feel as well as Windows.support the Motif look-and-feel as well as Windows.

Page 14: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Why Cross-Platform GUI toolkitsWhy Cross-Platform GUI toolkits

Increases target market.Increases target market.

May provides the same look-and-feel across May provides the same look-and-feel across platform. Reduces training and documentation platform. Reduces training and documentation costs.costs.

Page 15: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Stategies for Implementing Cross-Platform GUIsStategies for Implementing Cross-Platform GUIs

API Layering – Mapping one API to many othersAPI Layering – Mapping one API to many othersExample – wxWindows – Win32 API on top of Motif or Xt Example – wxWindows – Win32 API on top of Motif or Xt API under Unix.API under Unix.

Advantages – easy to write, 100% compatible native look Advantages – easy to write, 100% compatible native look and feel.and feel.

Disadvantages – Disadvantages – slowerslower

problems mapping to vastly different API architecturesproblems mapping to vastly different API architectures

Lowest common denominator – i.e. no pop-up help anywhereLowest common denominator – i.e. no pop-up help anywhere

Objects required a C++ wrapper to work with them in C++Objects required a C++ wrapper to work with them in C++

Page 16: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Stategies for Implementing Cross-Platform GUIsStategies for Implementing Cross-Platform GUIs

API Emulation – Implement a full API emulation API Emulation – Implement a full API emulation (programming gaps where APIs to not directly (programming gaps where APIs to not directly map)map)

Examples – MainWin and Wind/U – Win32 API on top of Examples – MainWin and Wind/U – Win32 API on top of Motif or Xt API under Unix.Motif or Xt API under Unix.Advantages – Running on native platform requires no Advantages – Running on native platform requires no emulation, and is therefore fast. Provides full emulation. emulation, and is therefore fast. Provides full emulation. I.e. you can run Word under Unix.I.e. you can run Word under Unix.Disadvantages – Disadvantages –

slower on emulated platformsslower on emulated platformstowers of layers: MFC on Win32 on Motif on Xt on X11towers of layers: MFC on Win32 on Motif on Xt on X11toolkit harder to emulatetoolkit harder to emulateProblems with undocumented featuresProblems with undocumented featuresNo direct support for C++. APIs still needs a C++ wrapper.No direct support for C++. APIs still needs a C++ wrapper.

Page 17: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Stategies for Implementing Cross-Platform GUIsStategies for Implementing Cross-Platform GUIs

GUI Emulation – Complete API written on top of GUI Emulation – Complete API written on top of primitive graphics (i.e. supported by all GUI OS). Each primitive graphics (i.e. supported by all GUI OS). Each widget is drawn by the toolkit.widget is drawn by the toolkit.

Examples – Qt (C++) and GTK (C)Examples – Qt (C++) and GTK (C)Advantages – Advantages –

Faster because toolkit layer talks directly to OS.Faster because toolkit layer talks directly to OS.Easy to change display style from within application – Motif style under Easy to change display style from within application – Motif style under Windows, or Windows style under Unix.Windows, or Windows style under Unix.Widgets are implemented as C++ classes and can be inherited from Widgets are implemented as C++ classes and can be inherited from directly in client code. (This is the reason Qt is chosen instead of GTK)directly in client code. (This is the reason Qt is chosen instead of GTK)

Disadvantages – Disadvantages – Does not support porting of existing programs (i.e. no Word under Unix).Does not support porting of existing programs (i.e. no Word under Unix).More work to create implementations for every OS release for every More work to create implementations for every OS release for every target platform. This means Qt support lags behind OS releases. target platform. This means Qt support lags behind OS releases. Impacts not only Qt but any widgets created by userImpacts not only Qt but any widgets created by userEmulation of look-and-feel is not 100% exact.Emulation of look-and-feel is not 100% exact.

Page 18: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Qt AssistantQt Assistant

All documentation is All documentation is available through the available through the trolltech web site.trolltech web site.

Qt Assistant is a Qt help Qt Assistant is a Qt help browser that runs under browser that runs under Windows.Windows.

It has with search and It has with search and indexing features that indexing features that make it quicker and make it quicker and easier than the web.easier than the web.

Page 19: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

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”, 0);8 Qlabel *mylabel = new Qlabel(“Hello World”, 0); 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 20: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Line-by-lineLine-by-line1 #include <qapplication.h>1 #include <qapplication.h>2 #include <qlabel.h>2 #include <qlabel.h>Always #include any Q types referenced in code.Always #include any Q types referenced in code.

6 QApplication myapp(argc, argv);6 QApplication myapp(argc, argv);Creates an object to manage application-wide resources. Passes argCreates an object to manage application-wide resources. Passes argc and argv because Qt supports a few command line arguments of its c and argv because Qt supports a few command line arguments of its own.own.

88Qlabel *mylabel = new Qlabel(“Hello World”, 0);Qlabel *mylabel = new Qlabel(“Hello World”, 0);Creates a QLabel widget on the heap. A widgets is any visual elemenCreates a QLabel widget on the heap. A widgets is any visual element in a user interface. Widgets can contain other widgets. For examplt in a user interface. Widgets can contain other widgets. For example a window may contain a QMenuBar,0 QToolBar, QStatusBar, and e a window may contain a QMenuBar,0 QToolBar, QStatusBar, and other widgets. The 0 parameters says that that the label is a stand-alother widgets. The 0 parameters says that that the label is a stand-alone window, is not inside another window.one window, is not inside another window.

Page 21: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Line-by-lineLine-by-line9 mylabel->resize(100, 200);9 mylabel->resize(100, 200);Invokes the resize() member function.Invokes the resize() member function.

11 myapp.setMainWidget(mylabel);11 myapp.setMainWidget(mylabel);Make the label the main application widget. This means that closing the label wiMake the label the main application widget. This means that closing the label windows closes the application.ndows closes the application.

12 mylabel->show();12 mylabel->show();Invoke the show() member function to make the label visible. All widgets are creInvoke the show() member function to make the label visible. All widgets are created invisible so that their properties can be manipulated without flickering. For ated invisible so that their properties can be manipulated without flickering. For example, you would show a widget and then change its size and color. You would example, you would show a widget and then change its size and color. You would change the size and color first, and then show the widget.change the size and color first, and then show the widget.

13 return myapp.exec();13 return myapp.exec();Passes control of the application to Qt. At this point the application goes into “evPasses control of the application to Qt. At this point the application goes into “event-driven” mode. It will just sit there until the user does something to create an ent-driven” mode. It will just sit there until the user does something to create an even. This is the same concept as Word. Word starts and waits for the user to do even. This is the same concept as Word. Word starts and waits for the user to do something. something.

Page 22: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Callback FunctionCallback FunctionOne of the most feared and hackish aspects of GUI programming One of the most feared and hackish aspects of GUI programming has always been the dreaded callback-function.has 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.1. quit = XtVaCreateManagedWidget(……);quit = XtVaCreateManagedWidget(……);2.2. tAddCallback(tAddCallback(

quit, quit, XmNactivateCallback, XmNactivateCallback, QuitCallback, QuitCallback, NULL); NULL);

3.3. void QuitCallback(void QuitCallback( Widget w, Widget w, XtPointer, XtPointer, clientData, clientData, XtPointer callData); XtPointer callData);

Page 23: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Callback FunctionCallback FunctionVirtual 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 coding- message map was complicated and difficult to coding

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

Page 24: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

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 25: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Signals and SlotsSignals and Slots

clicked_method()

Page 26: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

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 27: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

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 28: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

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”

Fortunately, the Qt utility qmake takes care of all this.

Page 29: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

qmakeqmake

The qmake utility is typically invoked with the following The qmake utility is typically invoked with the following three commands]three commands]

qmake –projectqmake –project

qmakeqmake

make (or nmake under Windows)make (or nmake under Windows)

Rules:Rules:Be sure to place code in its own directory.Be sure to place code in its own directory.

qmake scans all subdirectories for dependencies. Do not place qmake scans all subdirectories for dependencies. Do not place archive version under a “save” subdirectory.archive version under a “save” subdirectory.

If you reorganize your files, like adding a new .h, delete all the .pro If you reorganize your files, like adding a new .h, delete all the .pro and other working files, then start over.and other working files, then start over.

Page 30: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

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 31: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

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 32: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

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 33: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

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 34: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

Other Features of QtOther Features of QtThe Qt Paint EngineThe Qt Paint EngineQPainterQPainter is highly optimized and contains several caching mec is highly optimized and contains several caching mechanisms to speed up drawing. Under X11, it caches GCs (graphhanisms to speed up drawing. Under X11, it caches GCs (graphics contexts), which often make it faster than native X11 prograics contexts), which often make it faster than native X11 programs.ms.

QPainterQPainter contains all the functionality one would expect from a prof contains all the functionality one would expect from a professional 2D graphics library. The coordinate system of a QPainter cessional 2D graphics library. The coordinate system of a QPainter can be transformed using the standard 2D transformations (translate,an be transformed using the standard 2D transformations (translate, scale, rotate and shear). scale, rotate and shear). QtQt supports Open GL for 3D graphics. supports Open GL for 3D graphics.Qt also contains a set of general purpose classes and a number of Qt also contains a set of general purpose classes and a number of collection-classes to ease the development of multi-platform appliccollection-classes to ease the development of multi-platform applications.ations.Qt has platform independent support for the operating system depeQt has platform independent support for the operating system dependent functions, such as time/date, files/directories and TCP/IP socndent functions, such as time/date, files/directories and TCP/IP sockets.kets.

Page 35: Dale Roberts Introduction to Qt Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer and Information Science,

Dale Roberts

AcknowledgementsAcknowledgements

Plantinga, Harry. Calvin CollegePlantinga, Harry. Calvin College

Trolltech Tutorials.Trolltech Tutorials.

pages.cpsc.ucalgary.ca/ pages.cpsc.ucalgary.ca/ ~saul/hci_topics/topics/history.html ~saul/hci_topics/topics/history.html