O'Reilly logo

Programming with Qt, 2nd Edition by Matthias Kalle Dalheimer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Preface

A Productive Weekend

A few years ago, someone emailed me on a Friday. He wanted to start a small project, but did not really have the resources for it. He outlined the requirements and asked how long it would take me.

The next Monday, he phoned to ask if I thought the project was feasible and how much time I would need. I said that I already had a working prototype. I had hacked it together in a few hours the day before—and because I had used Qt, I had still found enough time to play outside with my son. Needless to say, I got the contract. Does this sound too good to be true? Well, I admit, I lied a bit. It was raining cats and dogs that Sunday and we had to play inside. But the rest is true.

The Qt class library makes it easy to write applications that are visually attractive, fast, and ready to run on Windows, Unix, MacOS X, and (Linux-based) embedded systems in a very short time. Had I used Motif, gtk, or another toolkit for this task, I might not have managed it in such a short time. If I had to port my program to Windows, the number of choices would have been even smaller, and for embedded systems there are hardly any alternatives.

Until the first edition of this book, there was not much Qt documentation for beginners. The package itself includes a tutorial, but leaves out a lot. There are other example programs, but often you have to search through several files to find what you are looking for and sometimes you don’t find it at all. Some people think it’s hard to get started with Qt, but after they have overcome the initial hurdles, they see that Qt helps them in a lot of ways when they write their applications. That’s why I decided to write this book. It will teach you how to program with Qt from the start and it will help you make more sense of the documentation that comes with Qt.

What You Should Know

Qt,[1] written and distributed by the Norwegian company Trolltech, is a C++ class library and this book requires some C++ knowledge. However, you don’t have to be a C++ expert to start programming with Qt. We have included a short overview of C++ language features that are used in Qt programs.

Qt is mostly about GUI programming (although it can also help you write a web server and other non-GUI applications). Accordingly, it helps to know a bit about how GUI programs are written. If you already know what an event loop is and how GUI programs are usually structured, this knowledge will make things easier for you at the beginning. I have tried to keep this book as self-contained as possible, though, so if you have never written a GUI program before, now would be a good time to start. Qt makes GUI programming much easier—even easier than with most (if not all) other toolkits.

I assume that you know how to use a text editor to enter program source code and that you know how to start your compiler and linker to generate an executable program. Unless there is something Qt-specific about these operations, I won’t talk about these topics. All programs in this book were tested with Linux 2.4.7 and the G++ compiler, and Windows 2000 and the Microsoft Visual C++ compiler. If you use another version of Unix or Windows 95/98/NT, you should have no problems. If you use OS/2,[2] however, you are out of luck. Qt has not been ported to this platform (yet). At the time of this writing, a version for MacOS X is in the works and we have tested the examples against a beta version. The Macintosh version is now also publically available.

Organization of This Book

This book is organized to make finding the information you need as easy as possible. If you have not programmed with Qt before, you should read the first three chapters of this book to grasp the basic concepts. The following chapters and sections are relatively independent and you should be able to jump around and read whatever you are interested in. If your application contains any custom graphics, you will probably want to read Chapter 9. Reading Chapter 4 and Chapter 5 is a very good idea because you can make better use of Qt’s features if you know what is available. Before reading the chapter on Qt Designer, it is a good idea to have at least read these two chapters so that you know about the widgets that the Designer offers you to use, as well as how dialogs are built up in general. To help you set up your own tour through the book, the following list of chapters includes short descriptions of their contents. Of course, if you decide to read through the whole book, I would be more than glad!

Chapter 1 , Introduction

Introduces you to basic Qt concepts. It gives you some information about why people use GUI toolkits in the first place and explains what is special about Qt. You will learn how and where you can get Qt, whether or not you have to pay for it, and where to go if you are stuck with a Qt-related problem.

Chapter 2 , First Steps in Qt Programming

Is a Qt programming primer. We start with a simple “Hello world” example, learn about signals and slots, and finish the chapter by creating a small painting program that lets you scribble on a virtual canvas in various colors.

Chapter 3 , Learning More About Qt

Continues the Qt primer. We develop the painting application into something more useful. By the end of this chapter, you will know how to use files and understand programming menus and other features of Qt.

Chapter 4 , A Guided Tour Through the Simple Widgets

Is a presentation of all simple widgets available in Qt. This chapter helps you pick the right widget for any given task. If an appropriate widget is not listed, you’ll know that you have to develop your own. You will also find explanations of the most useful methods, code examples, and hints for using existing widgets.

Chapter 5 , A Guided Tour Through the Qt Dialog Boxes

Continues the tour through the available GUI elements in Qt by showing which dialogs are available. It also shows you how to program your own dialogs and tab dialogs.

Chapter 6 , Using Layout Managers

Explains how widgets are laid out automatically within their parent window so that their positions are computed at runtime according to their needs. This topic is complex, so I provide several examples to make it easier to understand.

Chapter 7 , Some Thoughts on GUI Design

Provides you with some hints about writing applications that users will like. This chapter includes guidelines about when to use which widget.

Chapter 8 , Container Classes

Explains how to use classes for building up lists, arrays, and dictionaries and explains how to traverse all elements in a container.

Chapter 9 , Graphics

Shows how to create custom graphics, including animations, printing, colors, two-dimensional transformations, and canvases.

Chapter 10 , Text Processing

Has sections on internationalization, working with regular expressions, reading and writing XML documents, checking input into text-entry fields, and working with rich text, a markup system for text with different attributes (not the same as Microsoft’s rich text format). The classes explained here can often reduce the length of your code and ease your programming efforts.

Chapter 11 , Working with Files and Directories

Explains how to access files and directories and maintain portability using the classes that Qt provides. These classes can shield your code from native APIs.

Chapter 12 , Interapplication Communication

Tells you how Qt applications can exchange data with one another, or with other applications. It describes the clipboard and drag-and-drop.

Chapter 13 , Interfacing with the Operating System

Provides information about interfacing with the operating system, including how to work with date and time values, how to load libraries dynamically, and how to start child processes from Qt programs.

Chapter 14 , Writing your Own Widgets

Explains how to write your own widgets.

Chapter 15 , Focus Handling

Explains how to control the way Qt passes the keyboard focus to widgets. This information is not crucial for getting an application up and running, but it is important if you don’t want your users to hate you.

Chapter 16 , Advanced Event Handling

Contains information about advanced event handling, such as filtering the events that go to a widget and sending synthetic events.

Chapter 17 , Advanced Signals and Slots

Builds on the tutorial’s introduction to signals and slots and describes advanced usage of signals and slots. We’ll also talk about actions here that abstract from user interaction patterns.

Chapter 18 , Providing Help

Explains various options for providing help to users of a Qt application.

Chapter 19 , Accessing Databases

Shows you how to interact with relational databases from Qt programs, including retrieving, updating, and displaying the database data.

Chapter 20 , Multithreading

Explains what you have to observe when you want to write multithreaded programs with Qt, as well as the classes that Qt provides for creating multiple threads and synchronizing them.

Chapter 21 , Debugging

Offers hints about Qt that can make debugging easier.

Chapter 22 , Portability

Explains how you can best achieve portability for your Qt programs.

Chapter 23 , Qt Network Programming

Gives examples of using Qt for non-GUI tasks by presenting a little HTTP server program and an FTP downloader created with the help of the network extension in Qt.

Chapter 24 , Interfacing Qt with Other Languages and Libraries

Explains how to interface Qt with other languages and libraries. Its sections include using Qt with Perl, integrating Qt and Xt widgets, using OpenGL in Qt programs, and writing Netscape plug-ins with Qt.

Chapter 25 , Using the Visual C++ IDE for Qt Programs

Provides hints about how to use the Visual C++ IDE (Visual Studio) from Microsoft for writing Qt programs.

Appendix A , Answers to Exercises

Provides complete, commented answers to all exercises in the tutorial.

Conventions Used in This Book

The following typographic conventions appear in this book:

Italic

Used for filenames, directory names, and command names. It is also used to highlight comments in command examples and to define terms the first time they appear.

Constant Width

Used in examples and in regular text to show methods, classes, keywords, objects, properties, operators, variables, function names, types, and the output from commands or programs.

Constant-Width Bold

Used in examples to show the user’s actual input at the terminal.

Constant-Width Italic

Used in examples to show variables for which a context-specific substitution should be made. The variable filename, for example, would be replaced by an actual filename.

Footnotes

Used to attach parenthetical notes which you should not read on your first perusal of this book. The material in the footnote is often advanced information that might confuse you until you have thoroughly mastered the basics.

Comments and Questions

Please address comments and questions concerning this book to the publisher:

O’Reilly & Associates, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (international/local)
(707) 829-0104 (fax)

There is a web page for this book, which lists errata, examples, or any additional information. You can access this page at: http://www.oreilly.com/catalog/prowqt/

To comment or ask technical questions about this book, send email to:

For more information about books, conferences, Resource Centers, and the O’Reilly Network, see the O’Reilly web site at: http://www.oreilly.com

Acknowledgments

A book like this is always a major undertaking. Without the help of many people, this book would never have become a reality.

When it comes to technical content, I owe much to the tremendous guys at Trolltech: Haavard Nord, Eirik Eng, Eirik Aavitsland, Paul Olav Tvete, Arnt Gulbrandsen, Warwick Allison, Matthias Ettrich, Volker Hilsheimer, Reginald Stadlbauer, Patricia Jung, and Jasmin Blanchette have provided me with an unimaginable support and never tired of reading through the various drafts I produced. Haavard Nord deserves special mention because this book was his idea in the first place and he helped convince the people at O’Reilly that it would be a good thing.

Jesper Pedersen and Steffen Hansen, my colleagues at Klarälvdalens Datakonsult AB, also read through the drafts and helped with many questions about Qt. Together with Lutz Rogowski, Karl-Heinz Zimmer, Michel Boyer de la Giroday, and my wife Tanja Dalheimer, this company has a lot of Qt knowledge.

The many people at the companies where we have taught Qt also provided insight into the problems Qt beginners most often face.

Several other people helped improve the quality of this book by reading drafts, correcting errors, and making suggestions: Ashley Winters, author of Perl-Qt; Stefan Taferner and Uwe Thiem from the KDE team; Jörg Fehlmann; Safuat Hamdy from the University of Hamburg; and Chris Schläger of SuSE GmbH.

As always, my colleagues at O’Reilly Germany were very helpful. Elke Hansel, editor of the first edition, and Ariane Hesse, editor of the second edition, got the ball rolling and managed the production process. They also handled the relations with our American colleagues. Since the first edition of this book was our first American-German coproduction—written and produced in Germany and copyedited in Cambridge, Massachusetts—I can imagine that a lot of organizational work was done behind the scenes. Add to this the technical proofreaders in Des Moines (Washington), Norway, Denmark, Sweden, Germany, Austria, Canada, and Namibia, and you can see that this book is truly an international effort.

Of our American colleagues, I have to give special credit to Paula Ferguson. Her expertise and experience with books about GUI programming helped give this book a better structure. If you find this book to be well organized, Paula is largely responsible. Christien and Sarah Jane Shangraw, David Chu, and Ann Schirmer helped by keeping the deadlines, reminding me whenever one was near, and by keeping the production process going.

When an author hands over the final draft of a book to the editor, only part of the work has been done. Lots of people are involved in correcting spelling mistakes, copy editing, setting the page layout, printing, binding, and other important jobs before the book finally hits the stores. As an author, you often don’t even know the names of these production people, but I’d like them to know that I appreciate their work very much. When an author with German as a native language writes a book in English, there is probably more copy editing to do than usual.

Also, a huge “thank you” goes to the KDE developers, especially the leader and founder of the KDE project, Matthias Ettrich. Without this project, I would probably never have delved so deeply into Qt coding. Teaching KDE and Qt programming at various workshops has given me much insight into where people have problems with Qt programming, and I have tried to incorporate this insight into the book.

Several other people out there in Netland helped a great deal, either by asking the right questions or by giving the right answers. For example, Valient Gough of Stellacore provided helpful insight into using Qt for a large graphics-intensive commercial application.

For some reason, authors always list their family last in these acknowledgment sections. I don’t know why this is so, but who am I to break with tradition? So here I go: I cannot really say that my son Jan Lennart, who is five years old now, helped me write the book. However, he taught me that some things are much more important than programming, books, or even computers. Pouring water from one bucket to another for hours, setting up wooden miniature railways, and discussing the necessity of brushing your teeth and whether kindergarten is really over for the day when the staff turns off the lights helped me keep my work in perspective. This has not stopped me from teaching my son, who when he was younger liked to sit on my lap while I typed, how to use XEmacs. He even knows how to get into modes I had never heard of! Lately, though, his interest has shifted to Sesame Street multimedia applications with monsters demonstrating how to count. However, his younger brother, Tim Fredrik, who will be three months old by the time this book appears on the shelves, might help take over the typing soon. Finally, a huge thank you to my wife Tanja, who was as supportive as ever and accepted that there were evenings when I had to write rather than spend time with her. Family support is probably the most underestimated tool of any author.



[1] Qt can either be pronounced cue-tee or cute. Both ways are considered correct.

[2] You should be able to run Qt programs with XFree86 for OS/2, but I have never tried this.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required