ptg7041395
www.it-ebooks.info
ptg7041395
An Introduction to Design
Patterns in C++ with Qt
™
,
2nd Edition
www.it-ebooks.info
ptg7041395
O
pen Source technology has revolutionized the computing world.
From MySQL to the Python programming language, these technologies
are in use on many different systems, ranging from proprietary systems,
to Linux systems, to traditional UNIX systems, to mainframes. The Prentice
Hall Open Source Software Development Series is designed to bring
you the best of these Open Source technologies. Not only will you learn
how to use them for your projects, but you will learn from them. By seeing
real code from real applications, you will learn the best practices of Open
Source developers the world over.
Visit informit.com/opensourcedev for a complete list of available publications.
The Prentice Hall Open Source
Software Development Series
Arnold Robbins, Series Editor
www.it-ebooks.info
ptg7041395
An Introduction to Design
Patterns in C++ with Qt
™
,
2nd Edition
005.13’3 dc23
2011018378
Copyright © 2012 Alan and Paul Ezust
All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be
obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or
by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to:
Pearson Education, Inc
Rights and Contracts Department
501 Boylston Street, Suite 900
Boston, MA 02116
Fax (617) 671-3447
Tu x i s c r e a t e d b y L a r r y E w i n g , l e w i n g @ i s c . t a m u . e d u , u s i n g G I M P.
Qt and the Qt logo are trademarks of Nokia Corporation and/or its subsidiaries in Finland and other countries.
ISBN-13: 978-0-132-82645-7
ISBN-10: 0-132-82645-3
Te x t p r i n t ed i n th e Un i t ed S ta t e s on r e cy c l ed p a p er a t C ou r i e r i n We s t f or d , Ma s s a ch u s e t ts .
First printing September 2011
Editor-in-Chief: Mark Taub
Acquisitions Editor: Debra Williams Cauley
Managing Editor: Kristy Hart
Project Editor: Jovana San Nicolas-Shirley
Copy Editor: Apostrophe Editing Services
Indexer: Cheryl Lenser
Proofreader: Gill Editorial Services
Publishing Coordinator: Kim Boedigheimer
Cover Designer: Alan Clements
Compositor: Nonie Ratcliff
www.it-ebooks.info
ptg7041395
i s b o o k i s d e d i c a t e d t o M i r i a m E z u s t , w i t h o u t
www.it-ebooks.info
ptg7041395
1.16 Reference Variables 60
1.17 const* and *const 61
1.18 Review Questions 64
Chapter 2: Top of the class 67
2.1 First, There Was struct 67
2.2 Class Definitions 69
2.3 Member Access Specifiers 71
2.4 Encapsulation 74
2.5 Introduction to UML 75
2.6 Friends of a Class 76
2.7 Constructors 77
2.8 Destructors 80
2.9 The Keyword static 81
2.10 Class Declarations and Definitions 86
2.11 Copy Constructors and Assignment Operators 88
2.12 Conversions 92
2.13 const Member Functions 95
2.14 Subobjects 97
2.15 Exercise: Classes 98
2.16 Review Questions 108
Chapter 3: Introduction to Qt 113
3.1 Style Guidelines, Naming Conventions 114
3.2 The Qt Core Module 116
3.3 QtCreator—An IDE for Qt Programming 119
3.4 Exercises: Introduction to Qt 120
3.5 Review Questions 121
Chapter 4: Lists 122
4.1 Introduction to Containers 122
6.9 Managed Containers, Composites, and Aggregates 206
6.10 Containers of Pointers 210
6.11 Review Questions 228
Chapter 7: Libraries and Design Patterns 234
7.1 Building and Reusing Libraries 236
7.2 Exercise: Installing Libraries 244
Contents ix
www.it-ebooks.info
ptg7041395
7.3 Frameworks and Components 247
7.4 Design Patterns 248
7.5 Review Questions 257
Chapter 8: QObject, QApplication, Signals, and Slots 259
8.1 Values and Objects 263
8.2 Composite Pattern: Parents and Children 264
8.3 QApplication and the Event Loop 272
8.4 Q_OBJECT and moc: A checklist 274
8.5 Signals and Slots 275
8.6 QObject Lifecycle 277
8.7 QTestLib 277
8.8 Exercises: QObject, QApplication, Signals, and Slots 282
8.9 Review Questions 282
Chapter 9: Widgets and Designer 283
9.1 Widget Categories 284
9.2 Designer Introduction 286
9.3 Dialogs 290
9.4 Form Layout 292
9.5 Icons, Images, and Resources 295
9.6 Layout of Widgets 298
9.7 Designer Integration with Code 306
12.6 MetaTypes, Declaring, and Registering 394
12.7 invokeMethod() 396
12.8 Exercises: Reflection 397
12.9 Review Questions 397
Chapter 13: Models and Views 399
13.1 Model-View-Controller (MVC) 400
13.2 Qt Models and Views 402
13.3 Table Models 414
13.4 Tree Models 424
13.5 Smarter Pointers 429
13.6 Exercises: Models and Views 431
13.7 Review Questions 433
Contents xi
www.it-ebooks.info
ptg7041395
Chapter 14: Validation and Regular Expressions 434
14.1 Input Masks 435
14.2 Validators 438
14.3 Regular Expressions 440
14.4 Regular Expression Validation 449
14.5 Subclassing QValidator 451
14.6 Exercises: Validation and Regular Expressions 454
14.7 Review Questions 456
Chapter 15: Parsing XML 457
15.1 The Qt XML Parsers 460
15.2 SAX Parsing 462
15.3 XML, Tree Structures, and DOM 466
15.4 XML Streams 476
15.5 Review Questions 479
Chapter 16: More Design Patterns 481
19.12 Exercises: Types and Expressions 592
19.13 Review Questions 594
Chapter 20: Scope and Storage Class 595
20.1 Declarations and Definitions 595
20.2 Identifier Scope 597
20.3 Storage Class 606
20.4 Namespaces 610
20.5 Review Questions 615
Chapter 21: Memory Access 617
21.1 Pointer Pathology 618
21.2 Further Pointer Pathology with Heap Memory 620
21.3 Memory Access Summary 623
21.4 Introduction to Arrays 624
21.5 Pointer Arithmetic 626
21.6 Arrays, Functions, and Return Values 627
21.7 Different Kinds of Arrays 629
Contents xiii
www.it-ebooks.info
ptg7041395
21.8 Valid Pointer Operations 629
21.9 Arrays and Memory: Important Points 632
21.10 Exercises: Memory Access 633
21.11 Review Questions 634
Chapter 22: Inheritance in Detail 635
22.1 virtual Pointers, virtual Tables 635
22.2 Polymorphism and virtual Destructors 638
22.3 Multiple Inheritance 642
22.4 public, protected, and private Derivation 650
22.5 Review Questions 652
Part III: Programming Assignments 653
KDE used Qt as the underlying framework. After some time as a user, I started
contributing to the KDE project. Although I had studied object-oriented programming
at university, it was only when I started developing for KDE with Qt that I really
learned and understood many of the concepts.
C++ as a programming language is in some ways incomplete. Most other languages
such as Java, Python, or C# come with a rather complete set of frameworks. e scope
of the C++ standard library is, however, limited to low-level functionality, containers,
and algorithms.
Combining a powerful and complex language such as C++ with a standard library
that is limited in scope but makes extensive use of all the advanced features of C++
creates an extremely steep learning curve for developers who want to start developing
in C++.
i s i s w h e r e Q t c a n h e l p . Q t i s a c o m p r e h e n s i v e , h i g h - q u a l i t y f r a m e w o r k f o r
professional application development. It covers most of the functionality that is missing
from the standard library, such as threading, Unicode support, XML handling, and
most important, ways to create graphical user interfaces (GUIs).
When I did my rst bits of coding in C++, I was using Qt. Qt made it easy for me
to start on my rst projects and made it easy to learn new concepts of the C++ language
while developing real applications. It was actually a lot of fun to work with Qt, so I
soon migrated all my work from other languages to using Qt and C++.
Qt has always focused on trying to provide an intuitive and easy-to-use API set. e
focus of the framework has always been on helping application developers to get their
work done. is focus has, however, often led to rather clean implementations of
www.it-ebooks.info
ptg7041395
xvi An Introduction to Design Patterns in C++ with Qt™, 2nd Edition
another platform like a mobile phone, embedded hardware, Mac, Windows, Linux
desktop, and others is only a recompile away. e people who build Qt do everything
possible to make developers’ lives as easy as possible. Alan and Paul’s book can give
you, the developer, the guidance you need.
We hope that you enjoy the journey to becoming a C++ developer [who can] one
day contribute to KDE or one of the many other open source projects using Qt.
Maybe you can write Qt software for a living, as many thousands of developers do
1
GNU Lesser General Public License
www.it-ebooks.info
ptg7041395
Foreword xvii
today. e opportunity is there—the number of jobs for skilled Qt engineers is
increasing every year.
i s t e x t i s n o t o n l y f o r t h o s e n e w t o C + + a n d Q t . E x p e r i e n c e d s o f t w a r e
developers can also obtain much value from the many surprising new ideas contained
in Paul and Alan’s work. e book also serves as a good lookup resource due to the
large index.
To d ay Q t d e ve lo pm en t t a k es p l a ce i n t h e o p en w it h b o t h Q t’s o wn e n g in ee r s a n d
the large community of contributors working on the same code repository. We hope
one day you will contribute code to Qt or add to the Qt ecosystem in another way
as Paul and Alan have done with this excellent new book.
—Lars Knoll
Director of Qt Research and Development
www.it-ebooks.info
ptg7041395
This page intentionally left blank
for easy integration.
• Java programs are platform independent (Wintel, Solaris, MacOS, Linux,
*nix, etc.).
www.it-ebooks.info
ptg7041395
xx An Introduction to Design Patterns in C++ with Qt, 2nd Edition Many of these benets can be achieved with C++ used with Qt.
• Qt provides a comprehensive set of GUI classes that run faster, look better,
and are more flexible than Java’s Swing classes.
• Signals and slots are easier to use than (Action|Event|Key)Listener inter-
faces in Java.
• Qt has a plugin architecture that makes it possible to load code into an ap-
plication without recompiling or relinking.
• Q t p r o v i d e s foreach , which makes iteration through collections simpler to
read and write.
Although Qt does not provide garbage collection, it provides a variety of alterna-
tives you can use to avoid the need to delete heap objects directly:
• Containers (see Section 6.8 ) that support reference counting and copy on
write
• Parents and children (see Section 8.2 )
• QPointer , and QSharedPointer , and QWeakReference (see Section 19.11 ).
• Subobjects (see Section 2.14 )
Each programming example is extracted from working source code. The Web version provides
a hyperlink from each code excerpt to its full source le. This makes it easy to try the examples
yourself. The text and listings in the Web version also contain hyperlinks from each library
ClassName to its class documentation page.
www.it-ebooks.info
ptg7041395
P r e f a c e t o t h e S e c o n d E d i t i o n
It is hard to know when a book is “nished,” especially when writing about a subject
(Qt) that is also under constant development. So, like Qt, our book has been under
constant development since its conception.
Since the publication of the rst edition, Trolltech released Qt 4.2, Nokia pur-
chased Trolltech, Nokia released Qt 4.7.3, and Alan became a Nokia Certied Qt
Specialist.
In the second edition, there are improvements in every chapter. Many eyeballs
have scrutinized it, and we have rewritten a number of examples and explanations.
We have added new exercises and review questions, some with handouts and
solutions.
e r s t p a r t o f t h e b o o k h a s b e e n r e a r r a n g e d t o i n t r o d u c e Q t e a r l i e r t h a n b e f o r e .
We decided to take advantage of some of Qt’s static convenience functions to write
simple dialog-based applications prior to fully covering classes, functions, etc. File
Streams have also been introduced earlier so that we could present more interesting
examples and assignments.
Widgets, Main Windows, Models and Views, Reection, reads, and Databases
have all been rewritten to use new classes that have been added to Qt since our rst
ate, we have pointed out the Qt classes that implement or use the pattern.
Tips and best practices have been taken from various sources, including Nokia’s
ocial Qt training material, and are made available to you here. All of the examples
in this edition have been tested with Qt 4.7.
1
Make sure that the libphonon-dev package has been installed if you plan to work with those materials.
www.it-ebooks.info
ptg7041395
This page intentionally left blank
www.it-ebooks.info