Previous Next

C++ GUI Programming with Qt 4 (Jasmin Blanchette, Mark Summerfield) (z-library.sk, 1lib.sk, z-lib.sk)

Author: Jasmin Blanchette, Mark Summerfield

移动

The Only Official, Best-Practice Guide to Qt 4.3 Programming Using Trolltech's Qt you can build industrial-strength C++ applications that run natively on Windows, Linux/Unix, Mac OS X, and embedded Linux without source code changes. Now, two Trolltech insiders have written a start-to-finish guide to getting outstanding results with the latest version of Qt: Qt 4.3. Packed with realistic examples and in-depth advice, this is the book Trolltech uses to teach Qt to its own new hires. Extensively revised and expanded, it reveals today's best Qt programming patterns for everything from implementing model/view architecture to using Qt 4.3's improved graphics support. You'll find proven solutions for virtually every GUI development task, as well as sophisticated techniques for providing database access, integrating XML, using subclassing, composition, and more. Whether you're new to Qt or upgrading from an older version, this book can help you accomplish everything that Qt 4.3 makes possible. Completely updated throughout, with significant new coverage of databases, XML, and Qtopia embedded programming Covers all Qt 4.2/4.3 changes, including Windows Vista support, native CSS support for widget styling, and SVG file generation Contains separate 2D and 3D chapters, coverage of Qt 4.3's new graphics view classes, and an introduction to QPainter's OpenGL back-end Includes new chapters on look-and-feel customization and application scripting Illustrates Qt 4's model/view architecture, plugin support, layout management, event processing, container classes, and much more Presents advanced techniques covered in no other book—from creating plugins to interfacing with native APIs Includes a new appendix on Qt Jambi, the new Java version of Qt

📄 File Format: PDF
💾 File Size: 12.8 MB
23
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
temp0001.html
📄 Page 2
(This page has no text content)
📄 Page 3
Table of Contents Copyright.................................................................................................................................................1 Series Editor's Note..................................................................................................................................1 Foreword..................................................................................................................................................1 Preface......................................................................................................................................................1 Acknowledgments....................................................................................................................................1 A Brief History of Qt...............................................................................................................................1 Part I: Basic Qt....................................................................................................................................................1 1. Getting Started.....................................................................................................................................1 Hello Qt.............................................................................................................................................1 Part I: Basic Qt....................................................................................................................................................3 1. Getting Started.....................................................................................................................................4 Hello Qt.............................................................................................................................................6 Part I: Basic Qt....................................................................................................................................................7 1. Getting Started.....................................................................................................................................8 Hello Qt...........................................................................................................................................10 Making Connections........................................................................................................................10 Laying Out Widgets........................................................................................................................16 Widget Styles.........................................................................................................................................17 Figure 1.6. Predefined styles...........................................................................................................23 Using the Reference Documentation...............................................................................................24 2. Creating Dialogs................................................................................................................................25 Subclassing QDialog.......................................................................................................................33 2. Creating Dialogs................................................................................................................................40 Subclassing QDialog.......................................................................................................................41 Signals and Slots in Depth...............................................................................................................46 Qt's Meta-Object System.......................................................................................................................47 Rapid Dialog Design.......................................................................................................................47 Shape-Changing Dialogs.................................................................................................................51 Dynamic Dialogs.............................................................................................................................52 Built-in Widget and Dialog Classes................................................................................................52 3. Creating Main Windows....................................................................................................................56 Figure 3.1. The spreadsheet application..........................................................................................61 Subclassing QMainWindow............................................................................................................62 3. Creating Main Windows....................................................................................................................69 Figure 3.1. The spreadsheet application..........................................................................................74 Subclassing QMainWindow............................................................................................................75 Creating Menus and Toolbars.........................................................................................................78 Setting Up the Status Bar................................................................................................................80 Implementing the File Menu...........................................................................................................80 Using Dialogs..................................................................................................................................81 Storing Settings...............................................................................................................................81 Multiple Documents........................................................................................................................82 Splash Screens.................................................................................................................................86 4. Implementing Application Functionality...........................................................................................88 The Central Widget.........................................................................................................................90 4. Implementing Application Functionality...........................................................................................94 The Central Widget.........................................................................................................................98 Subclassing QTableWidget...........................................................................................................105 Storing Data as Items...........................................................................................................................106 temp0001.html i
📄 Page 4
Table of Contents Part I: Basic Qt Loading and Saving.......................................................................................................................108 Implementing the Edit Menu.........................................................................................................108 Implementing the Other Menus.....................................................................................................110 Subclassing QTableWidgetItem....................................................................................................119 5. Creating Custom Widgets................................................................................................................123 Customizing Qt Widgets...................................................................................................................1 5. Creating Custom Widgets....................................................................................................................1 Customizing Qt Widgets...................................................................................................................1 Subclassing QWidget........................................................................................................................1 Integrating Custom Widgets with Qt Designer.................................................................................1 Double Buffering...............................................................................................................................1 Part II: Intermediate Qt.....................................................................................................................................1 6. Layout Management............................................................................................................................1 Laying Out Widgets on a Form.........................................................................................................1 Part II: Intermediate Qt.....................................................................................................................................7 6. Layout Management............................................................................................................................8 Laying Out Widgets on a Form.......................................................................................................12 Part II: Intermediate Qt...................................................................................................................................13 6. Layout Management..........................................................................................................................16 Laying Out Widgets on a Form.......................................................................................................25 Stacked Layouts..............................................................................................................................25 Splitters............................................................................................................................................30 Scrolling Areas................................................................................................................................31 Dock Windows and Toolbars..........................................................................................................35 Multiple Document Interface..........................................................................................................38 7. Event Processing................................................................................................................................40 Reimplementing Event Handlers.....................................................................................................41 7. Event Processing................................................................................................................................46 Reimplementing Event Handlers.....................................................................................................47 Installing Event Filters....................................................................................................................52 Staying Responsive during Intensive Processing............................................................................60 8. 2D Graphics.......................................................................................................................................62 Painting with QPainter....................................................................................................................82 8. 2D Graphics.......................................................................................................................................90 Painting with QPainter....................................................................................................................91 Coordinate System Transformations...............................................................................................96 High-Quality Rendering with QImage............................................................................................96 Item-Based Rendering with Graphics View..................................................................................101 Printing..........................................................................................................................................105 9. Drag and Drop..................................................................................................................................106 Enabling Drag and Drop................................................................................................................107 9. Drag and Drop..................................................................................................................................107 Enabling Drag and Drop................................................................................................................113 Supporting Custom Drag Types....................................................................................................114 Clipboard Handling.......................................................................................................................115 10. Item View Classes..........................................................................................................................121 Figure 10.1. Qt's model/view architecture....................................................................................126 Using the Item View Convenience Classes...................................................................................139 temp0001.html ii
📄 Page 5
Table of Contents Part II: Intermediate Qt 10. Item View Classes..........................................................................................................................144 Figure 10.1. Qt's model/view architecture....................................................................................145 Using the Item View Convenience Classes...................................................................................151 Using Predefined Models..............................................................................................................153 Implementing Custom Models......................................................................................................153 Implementing Custom Delegates..................................................................................................160 11. Container Classes...........................................................................................................................161 Sequential Containers....................................................................................................................164 How Implicit Sharing Works...............................................................................................................166 11. Container Classes...........................................................................................................................173 Sequential Containers....................................................................................................................174 How Implicit Sharing Works...............................................................................................................179 Associative Containers..................................................................................................................180 Generic Algorithms.......................................................................................................................185 Strings, Byte Arrays, and Variants................................................................................................190 12. Input/Output...................................................................................................................................192 Reading and Writing Binary Data.................................................................................................193 12. Input/Output...................................................................................................................................197 Reading and Writing Binary Data.................................................................................................198 Reading and Writing Text.............................................................................................................204 Traversing Directories...................................................................................................................205 Embedding Resources...................................................................................................................211 Inter-Process Communication.......................................................................................................213 13. Databases.......................................................................................................................................219 Connecting and Querying..............................................................................................................225 13. Databases.......................................................................................................................................226 Connecting and Querying..............................................................................................................229 Viewing Tables..............................................................................................................................230 Editing Records Using Forms.......................................................................................................233 Presenting Data in Tabular Forms.................................................................................................239 14. Multithreading...............................................................................................................................245 Creating Threads...........................................................................................................................246 14. Multithreading...............................................................................................................................247 Creating Threads...........................................................................................................................255 Synchronizing Threads..................................................................................................................255 Communicating with the Main Thread.........................................................................................263 Using Qt's Classes in Secondary Threads.....................................................................................266 15. Networking....................................................................................................................................276 Writing FTP Clients......................................................................................................................279 15. Networking....................................................................................................................................280 Writing FTP Clients......................................................................................................................287 Writing HTTP Clients...................................................................................................................288 Writing TCP Client–Server Applications.................................................................................294 Sending and Receiving UDP Datagrams.......................................................................................298 16. XML...............................................................................................................................................302 Reading XML with QXmlStreamReader......................................................................................304 16. XML...............................................................................................................................................305 Reading XML with QXmlStreamReader......................................................................................307 Reading XML with DOM.............................................................................................................308 Reading XML with SAX...............................................................................................................310 Writing XML.................................................................................................................................312 temp0001.html iii
📄 Page 6
Table of Contents Part II: Intermediate Qt 17. Providing Online Help...................................................................................................................315 Tooltips, Status Tips, and "What's This?" Help................................................................................1 17. Providing Online Help.......................................................................................................................1 Tooltips, Status Tips, and "What's This?" Help................................................................................1 Using a Web Browser to Provide Online Help.................................................................................1 Using QTextBrowser as a Simple Help Engine................................................................................1 Using Qt Assistant for Powerful Online Help...................................................................................1 Part III: Advanced Qt........................................................................................................................................1 18. Internationalization............................................................................................................................1 Working with Unicode......................................................................................................................1 Part III: Advanced Qt........................................................................................................................................6 18. Internationalization..........................................................................................................................11 Working with Unicode....................................................................................................................16 Part III: Advanced Qt......................................................................................................................................19 18. Internationalization..........................................................................................................................20 Working with Unicode....................................................................................................................20 Making Applications Translation-Aware........................................................................................33 Dynamic Language Switching........................................................................................................34 Translating Applications.................................................................................................................34 19. Look and Feel Customization..........................................................................................................48 Figure 19.1. The custom styles presented in this chapter................................................................61 Using Qt Style Sheets......................................................................................................................62 19. Look and Feel Customization..........................................................................................................63 Figure 19.1. The custom styles presented in this chapter................................................................68 Using Qt Style Sheets......................................................................................................................68 Subclassing QStyle..........................................................................................................................73 QStyleOption Versioning......................................................................................................................80 20. 3D Graphics.....................................................................................................................................86 Drawing Using OpenGL.................................................................................................................87 20. 3D Graphics.....................................................................................................................................96 Drawing Using OpenGL.................................................................................................................97 Combining OpenGL and QPainter................................................................................................106 Doing Overlays Using Framebuffer Objects.................................................................................109 21. Creating Plugins.............................................................................................................................111 Extending Qt with Plugins............................................................................................................112 21. Creating Plugins.............................................................................................................................121 Extending Qt with Plugins............................................................................................................122 Making Applications Plugin-Aware..............................................................................................131 Writing Application Plugins..........................................................................................................135 22. Application Scripting.....................................................................................................................142 Overview of the ECMAScript Language......................................................................................153 22. Application Scripting.....................................................................................................................154 Overview of the ECMAScript Language......................................................................................158 Extending Qt Applications with Scripts........................................................................................158 Implementing GUI Extensions Using Scripts...............................................................................162 Automating Tasks through Scripting............................................................................................174 23. Platform-Specific Features.............................................................................................................179 Interfacing with Native APIs.........................................................................................................180 temp0001.html iv
📄 Page 7
Table of Contents Part III: Advanced Qt 23. Platform-Specific Features.............................................................................................................182 Interfacing with Native APIs.........................................................................................................183 Using ActiveX on Windows..........................................................................................................185 Handling X11 Session Management.............................................................................................186 24. Embedded Programming...............................................................................................................191 Getting Started with Qt/Embedded Linux.........................................................................................1 24. Embedded Programming...................................................................................................................1 Getting Started with Qt/Embedded Linux.........................................................................................1 Customizing Qt/Embedded Linux.....................................................................................................1 Integrating Qt Applications with Qtopia...........................................................................................1 Using Qtopia APIs.............................................................................................................................1 IV: Appendixes....................................................................................................................................................1 A. Obtaining and Installing Qt.................................................................................................................1 A Note on Licensing..........................................................................................................................1 IV: Appendixes....................................................................................................................................................1 A. Obtaining and Installing Qt.................................................................................................................2 A Note on Licensing..........................................................................................................................2 IV: Appendixes....................................................................................................................................................4 A. Obtaining and Installing Qt.................................................................................................................4 A Note on Licensing..........................................................................................................................4 Installing Qt/Windows......................................................................................................................9 Installing Qt/Mac.............................................................................................................................10 Installing Qt/X11.............................................................................................................................10 B. Building Qt Applications..................................................................................................................15 Figure B.1. The Qt Visual Studio and Eclipse integrations in action.............................................19 Using qmake....................................................................................................................................19 B. Building Qt Applications..................................................................................................................22 Figure B.1. The Qt Visual Studio and Eclipse integrations in action.............................................24 Using qmake....................................................................................................................................25 Using Third-Party Build Tools........................................................................................................28 C. Introduction to Qt Jambi...................................................................................................................30 Getting Started with Qt Jambi.........................................................................................................34 Using Java's Resource System...............................................................................................................41 C. Introduction to Qt Jambi...................................................................................................................42 Getting Started with Qt Jambi.........................................................................................................45 Using Java's Resource System...............................................................................................................46 Using Qt Jambi in the Eclipse IDE.................................................................................................50 Integrating C++ Components with Qt Jambi..................................................................................79 D. Introduction to C++ for Java and C# Programmers..........................................................................80 Getting Started with C++................................................................................................................81 D. Introduction to C++ for Java and C# Programmers..........................................................................81 Getting Started with C++................................................................................................................81 Main Language Differences............................................................................................................81 The Standard C++ Library..............................................................................................................81 About the Authors.................................................................................................................................82 Jasmin Blanchette............................................................................................................................82 About the Authors.................................................................................................................................82 Jasmin Blanchette............................................................................................................................85 temp0001.html v
📄 Page 8
Table of Contents IV: Appendixes Mark Summerfield..........................................................................................................................88 Production.............................................................................................................................................95 Index......................................................................................................................................................99 Index....................................................................................................................................................104 Index....................................................................................................................................................107 Index....................................................................................................................................................108 Index....................................................................................................................................................110 Index....................................................................................................................................................114 Index....................................................................................................................................................115 Index....................................................................................................................................................116 Index....................................................................................................................................................118 Index....................................................................................................................................................122 Index....................................................................................................................................................123 Index....................................................................................................................................................125 Index....................................................................................................................................................131 Index....................................................................................................................................................157 Index....................................................................................................................................................160 Index....................................................................................................................................................173 Index....................................................................................................................................................178 Index....................................................................................................................................................179 Index....................................................................................................................................................181 Index....................................................................................................................................................183 Index....................................................................................................................................................title Index....................................................................................................................................................title Index....................................................................................................................................................title Index....................................................................................................................................................title Index....................................................................................................................................................title Index....................................................................................................................................................title temp0001.html vi
📄 Page 9
Part I: Basic Qt 1. Getting Started Hello Qt• Making Connections• Laying Out Widgets• Using the Reference Documentation• This chapter shows how to combine basic C++ with the functionality provided by Qt to create a few small graphical user interface (GUI) applications. This chapter also introduces two key Qt ideas: "signals and slots" and layouts. In Chapter 2, we will go into more depth, and in Chapter 3, we will start building a more realistic application. If you already know Java or C# but have limited experience with C++, you might want to start by reading the C++ introduction in Appendix D. Hello Qt Let's start with a very simple Qt program. We will first study it line by line, and then see how to compile and run it. 1 #include <QApplication> 2 #include <QLabel> 3 int main(int argc, char *argv[]) 4 { 5 QApplication app(argc, argv); 6 QLabel *label = new QLabel("Hello Qt!"); 7 label->show(); 8 return app.exec(); 9 } Lines 1 and 2 include the definitions of the QApplication and QLabel classes. For every Qt class, there is a header file with the same name (and capitalization) as the class that contains the class's definition. Line 5 creates a QApplication object to manage application-wide resources. The QApplication constructor requires argc and argv because Qt supports a few command-line arguments of its own. Part I: Basic Qt 1
📄 Page 10
Line 6 creates a QLabel widget that displays "Hello Qt!". In Qt and Unix terminology, a widget is a visual element in a user interface. The term stems from "window gadget" and is the equivalent of both "control" and "container" in Windows terminology. Buttons, menus, scroll bars, and frames are all examples of widgets. Widgets can contain other widgets; for example, an application window is usually a widget that contains a QMenuBar, a few QToolBars, a QStatusBar, and some other widgets. Most applications use a QMainWindow or a QDialog as the application window, but Qt is so flexible that any widget can be a window. In this example, the QLabel widget is the application window. Line 7 makes the label visible. Widgets are always created hidden so that we can customize them before showing them, thereby avoiding flicker. Line 8 passes control of the application on to Qt. At this point, the program enters the event loop. This is a kind of stand-by mode where the program waits for user actions such as mouse clicks and key presses. User actions generate events (also called "messages") to which the program can respond, usually by executing one or more functions. For example, when the user clicks a widget, a "mouse press" and a "mouse release" event are generated. In this respect, GUI applications differ drastically from conventional batch programs, which typically process input, produce results, and terminate without human intervention. For simplicity, we don't bother calling delete on the QLabel object at the end of the main() function. This memory leak is harmless in such a small program, since the memory will be reclaimed by the operating system when the program terminates. It is now possible to try the program on your own machine. It should look like the one shown in Figure 1.1. First, you will need to install Qt 4.3.2 (or a later Qt 4 release), a process that is explained in Appendix A. From now on, we will assume that you have a correctly installed copy of Qt 4 and that Qt's bin directory is in your PATH environment variable. (On Windows, this is done automatically by the Qt installation program.) You will also need the program's code in a file called hello.cpp in a directory called hello. You can type in hello.cpp yourself or copy it from the examples that accompany this book, where it is available as examples/chap01/hello/hello.cpp. (All the examples are available from the book's web site, http://www.informit.com/title/0132354160.) Figure 1.1. Hello on Linux From a command prompt, change the directory to hello, and type qmake -project to create a platform-independent project file (hello.pro), and then type qmake hello.pro to create a platform-specific makefile from the project file. (The qmake tool is covered in more detail in Appendix B.) Type make to build the program. Run it by typing hello on Windows, ./hello on Unix, and open hello.app on Mac OS X. To terminate the program, click the close button in the window's title 2 Part I: Basic Qt 2 Part I: Basic Qt
📄 Page 11
bar. If you are using Windows and have installed the Qt Open Source Edition and the MinGW compiler, you will have a shortcut to an MS-DOS Prompt window that has all the environment variables correctly set up for Qt. If you start this window, you can compile Qt applications within it using qmake and make as described previously. The executables produced are put in the application's debug or release folder (e.g., C:\examples\chap01\hello\release\hello.exe). If you are using Microsoft Visual C++ with a commercial version of Qt, you will need to run nmake instead of make. Alternatively, you can create a Visual Studio project file from hello.pro by typing qmake -tp vc hello.pro and then build the program in Visual Studio. If you are using Xcode on Mac OS X, you can generate an Xcode project using the command qmake -spec macx-xcode hello.pro Before we go on to the next example, let's have some fun: Replace the line QLabel *label = new QLabel("Hello Qt!"); with QLabel *label = new QLabel("<h2><i>Hello</i> " "<font color=red>Qt!</font></h2>"); and rebuild the application. When run, it should look like Figure 1.2. As the example illustrates, it's easy to brighten up a Qt application's user interface using some simple HTML-style formatting. Figure 1.2. A label with basic HTML formatting Part I: Basic Qt 3 Part I: Basic Qt 3
📄 Page 12
4 Part I: Basic Qt 4 Part I: Basic Qt
📄 Page 13
Part I: Basic Qt 1. Getting Started Hello Qt• Making Connections• Laying Out Widgets• Using the Reference Documentation• This chapter shows how to combine basic C++ with the functionality provided by Qt to create a few small graphical user interface (GUI) applications. This chapter also introduces two key Qt ideas: "signals and slots" and layouts. In Chapter 2, we will go into more depth, and in Chapter 3, we will start building a more realistic application. If you already know Java or C# but have limited experience with C++, you might want to start by reading the C++ introduction in Appendix D. Hello Qt Let's start with a very simple Qt program. We will first study it line by line, and then see how to compile and run it. 1 #include <QApplication> 2 #include <QLabel> 3 int main(int argc, char *argv[]) 4 { 5 QApplication app(argc, argv); 6 QLabel *label = new QLabel("Hello Qt!"); 7 label->show(); 8 return app.exec(); 9 } Lines 1 and 2 include the definitions of the QApplication and QLabel classes. For every Qt class, there is a header file with the same name (and capitalization) as the class that contains the class's definition. Line 5 creates a QApplication object to manage application-wide resources. The QApplication constructor requires argc and argv because Qt supports a few command-line arguments of its own. Part I: Basic Qt 1
📄 Page 14
Line 6 creates a QLabel widget that displays "Hello Qt!". In Qt and Unix terminology, a widget is a visual element in a user interface. The term stems from "window gadget" and is the equivalent of both "control" and "container" in Windows terminology. Buttons, menus, scroll bars, and frames are all examples of widgets. Widgets can contain other widgets; for example, an application window is usually a widget that contains a QMenuBar, a few QToolBars, a QStatusBar, and some other widgets. Most applications use a QMainWindow or a QDialog as the application window, but Qt is so flexible that any widget can be a window. In this example, the QLabel widget is the application window. Line 7 makes the label visible. Widgets are always created hidden so that we can customize them before showing them, thereby avoiding flicker. Line 8 passes control of the application on to Qt. At this point, the program enters the event loop. This is a kind of stand-by mode where the program waits for user actions such as mouse clicks and key presses. User actions generate events (also called "messages") to which the program can respond, usually by executing one or more functions. For example, when the user clicks a widget, a "mouse press" and a "mouse release" event are generated. In this respect, GUI applications differ drastically from conventional batch programs, which typically process input, produce results, and terminate without human intervention. For simplicity, we don't bother calling delete on the QLabel object at the end of the main() function. This memory leak is harmless in such a small program, since the memory will be reclaimed by the operating system when the program terminates. It is now possible to try the program on your own machine. It should look like the one shown in Figure 1.1. First, you will need to install Qt 4.3.2 (or a later Qt 4 release), a process that is explained in Appendix A. From now on, we will assume that you have a correctly installed copy of Qt 4 and that Qt's bin directory is in your PATH environment variable. (On Windows, this is done automatically by the Qt installation program.) You will also need the program's code in a file called hello.cpp in a directory called hello. You can type in hello.cpp yourself or copy it from the examples that accompany this book, where it is available as examples/chap01/hello/hello.cpp. (All the examples are available from the book's web site, http://www.informit.com/title/0132354160.) Figure 1.1. Hello on Linux From a command prompt, change the directory to hello, and type qmake -project to create a platform-independent project file (hello.pro), and then type qmake hello.pro to create a platform-specific makefile from the project file. (The qmake tool is covered in more detail in Appendix B.) Type make to build the program. Run it by typing hello on Windows, ./hello on Unix, and open hello.app on Mac OS X. To terminate the program, click the close button in the window's title 2 Part I: Basic Qt 2 Part I: Basic Qt
📄 Page 15
bar. If you are using Windows and have installed the Qt Open Source Edition and the MinGW compiler, you will have a shortcut to an MS-DOS Prompt window that has all the environment variables correctly set up for Qt. If you start this window, you can compile Qt applications within it using qmake and make as described previously. The executables produced are put in the application's debug or release folder (e.g., C:\examples\chap01\hello\release\hello.exe). If you are using Microsoft Visual C++ with a commercial version of Qt, you will need to run nmake instead of make. Alternatively, you can create a Visual Studio project file from hello.pro by typing qmake -tp vc hello.pro and then build the program in Visual Studio. If you are using Xcode on Mac OS X, you can generate an Xcode project using the command qmake -spec macx-xcode hello.pro Before we go on to the next example, let's have some fun: Replace the line QLabel *label = new QLabel("Hello Qt!"); with QLabel *label = new QLabel("<h2><i>Hello</i> " "<font color=red>Qt!</font></h2>"); and rebuild the application. When run, it should look like Figure 1.2. As the example illustrates, it's easy to brighten up a Qt application's user interface using some simple HTML-style formatting. Figure 1.2. A label with basic HTML formatting Part I: Basic Qt 3 Part I: Basic Qt 3
📄 Page 16
4 Part I: Basic Qt 4 Part I: Basic Qt
📄 Page 17
Part I: Basic Qt 1. Getting Started Hello Qt• Making Connections• Laying Out Widgets• Using the Reference Documentation• This chapter shows how to combine basic C++ with the functionality provided by Qt to create a few small graphical user interface (GUI) applications. This chapter also introduces two key Qt ideas: "signals and slots" and layouts. In Chapter 2, we will go into more depth, and in Chapter 3, we will start building a more realistic application. If you already know Java or C# but have limited experience with C++, you might want to start by reading the C++ introduction in Appendix D. Hello Qt Let's start with a very simple Qt program. We will first study it line by line, and then see how to compile and run it. 1 #include <QApplication> 2 #include <QLabel> 3 int main(int argc, char *argv[]) 4 { 5 QApplication app(argc, argv); 6 QLabel *label = new QLabel("Hello Qt!"); 7 label->show(); 8 return app.exec(); 9 } Lines 1 and 2 include the definitions of the QApplication and QLabel classes. For every Qt class, there is a header file with the same name (and capitalization) as the class that contains the class's definition. Line 5 creates a QApplication object to manage application-wide resources. The QApplication constructor requires argc and argv because Qt supports a few command-line arguments of its own. Part I: Basic Qt 1
📄 Page 18
Line 6 creates a QLabel widget that displays "Hello Qt!". In Qt and Unix terminology, a widget is a visual element in a user interface. The term stems from "window gadget" and is the equivalent of both "control" and "container" in Windows terminology. Buttons, menus, scroll bars, and frames are all examples of widgets. Widgets can contain other widgets; for example, an application window is usually a widget that contains a QMenuBar, a few QToolBars, a QStatusBar, and some other widgets. Most applications use a QMainWindow or a QDialog as the application window, but Qt is so flexible that any widget can be a window. In this example, the QLabel widget is the application window. Line 7 makes the label visible. Widgets are always created hidden so that we can customize them before showing them, thereby avoiding flicker. Line 8 passes control of the application on to Qt. At this point, the program enters the event loop. This is a kind of stand-by mode where the program waits for user actions such as mouse clicks and key presses. User actions generate events (also called "messages") to which the program can respond, usually by executing one or more functions. For example, when the user clicks a widget, a "mouse press" and a "mouse release" event are generated. In this respect, GUI applications differ drastically from conventional batch programs, which typically process input, produce results, and terminate without human intervention. For simplicity, we don't bother calling delete on the QLabel object at the end of the main() function. This memory leak is harmless in such a small program, since the memory will be reclaimed by the operating system when the program terminates. It is now possible to try the program on your own machine. It should look like the one shown in Figure 1.1. First, you will need to install Qt 4.3.2 (or a later Qt 4 release), a process that is explained in Appendix A. From now on, we will assume that you have a correctly installed copy of Qt 4 and that Qt's bin directory is in your PATH environment variable. (On Windows, this is done automatically by the Qt installation program.) You will also need the program's code in a file called hello.cpp in a directory called hello. You can type in hello.cpp yourself or copy it from the examples that accompany this book, where it is available as examples/chap01/hello/hello.cpp. (All the examples are available from the book's web site, http://www.informit.com/title/0132354160.) Figure 1.1. Hello on Linux From a command prompt, change the directory to hello, and type qmake -project to create a platform-independent project file (hello.pro), and then type qmake hello.pro to create a platform-specific makefile from the project file. (The qmake tool is covered in more detail in Appendix B.) Type make to build the program. Run it by typing hello on Windows, ./hello on Unix, and open hello.app on Mac OS X. To terminate the program, click the close button in the window's title 2 Part I: Basic Qt 2 Part I: Basic Qt
📄 Page 19
bar. If you are using Windows and have installed the Qt Open Source Edition and the MinGW compiler, you will have a shortcut to an MS-DOS Prompt window that has all the environment variables correctly set up for Qt. If you start this window, you can compile Qt applications within it using qmake and make as described previously. The executables produced are put in the application's debug or release folder (e.g., C:\examples\chap01\hello\release\hello.exe). If you are using Microsoft Visual C++ with a commercial version of Qt, you will need to run nmake instead of make. Alternatively, you can create a Visual Studio project file from hello.pro by typing qmake -tp vc hello.pro and then build the program in Visual Studio. If you are using Xcode on Mac OS X, you can generate an Xcode project using the command qmake -spec macx-xcode hello.pro Before we go on to the next example, let's have some fun: Replace the line QLabel *label = new QLabel("Hello Qt!"); with QLabel *label = new QLabel("<h2><i>Hello</i> " "<font color=red>Qt!</font></h2>"); and rebuild the application. When run, it should look like Figure 1.2. As the example illustrates, it's easy to brighten up a Qt application's user interface using some simple HTML-style formatting. Figure 1.2. A label with basic HTML formatting Making Connections The second example shows how to respond to user actions. The application consists of a button that the user can click to quit. The source code is very similar to Hello, except that we are using a QPushButton instead of a QLabel as our main widget, and we are connecting a user action (clicking a button) to a piece of code. This application's source code is in the book's examples, in the file examples/ chap01/quit/quit.cpp; the running application is shown in Figure 1.3. Here's the contents of the file: Part I: Basic Qt 3 Part I: Basic Qt 3
📄 Page 20
1 #include <QApplication> 2 #include <QPushButton> 3 int main(int argc, char *argv[]) 4 { 5 QApplication app(argc, argv); 6 QPushButton *button = new QPushButton("Quit"); 7 QObject::connect(button, SIGNAL(clicked()), 8 &app, SLOT(quit())); 9 button->show(); 10 return app.exec(); 11 } Figure 1.3. The Quit application Qt's widgets emit signals to indicate that a user action or a change of state has occurred.[*] For instance, QPushButton emits a clicked() signal when the user clicks the button. A signal can be connected to a function (called a slot in that context) so that when the signal is emitted, the slot is automatically executed. In our example, we connect the button's clicked() signal to the QApplication object's quit() slot. The SIGNAL() and SLOT() macros are part of the syntax. [*] Qt signals are unrelated to Unix signals. In this book, we are only concerned with Qt signals. We will now build the application. We assume that you have created a directory called quit containing quit.cpp. Run qmake in the quit directory to generate the project file, and then run it again to generate a makefile, as follows: qmake -project qmake quit.pro Now build the application, and run it. If you click Quit, or press Space (which presses the button), the application will terminate. Laying Out Widgets In this section, we will create a small example application that demonstrates how to use layouts to manage the geometry of widgets in a window and how to use signals and slots to synchronize two widgets. The application—shown in Figure 1.4—asks for the user's age, which the user can enter by manipulating either a spin box or a slider. 4 Part I: Basic Qt 4 Part I: Basic Qt
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now

Recommended for You

Loading recommended books...
Failed to load, please try again later
Back to List