The Book of Qt 4 to Be Indispensable
Total Page:16
File Type:pdf, Size:1020Kb
THETHE BOOKBOOK ofof QtQt 4.4. FROMFROM THETHE BASICSBASICS THROUGHTHROUGH APPLICATIONAPPLICATION THETHE DESIGN.DESIGN. BOOK of QtQt 44 THE ART OF BUILDING Qt APPLICATIONS Cross-platform development is a kind of holy grail, and • Data visualization using Qt’s model/view concept Trolltech’s Qt toolkit may well be the most promising • The QtSql module and the graphics library Arthur solution yet to this development challenge. Qt is widely DANIEL MOLKENTIN used for the development of GUI applications as well • File handling, XML, processes, and network connections as console tools and servers, and it’s especially appeal- • Databases and threading ing to programmers who need to write cross-platform Qt 4 applications to run on Linux/Unix, Mac, and Windows • Event handling and using drag and drop Qt 4 machines without having to rewrite for each platform. • Internationalization and debugging The Book of ™ Qt 4 offers an in-depth explanation of Qt As well as lots of useful hints on how to use Qt’s data- 4 that goes beyond the common focus on C++ program- types, containers, and algorithms and how to develop ming. Author Daniel Molkentin uses practical examples user-friendly applications. to explain features like the signal/slot concept and the event system, as he guides you through developing Whether you’re already a Qt developer or you’re just applications with and without Qt’s graphical GUI builder, considering Qt for cross-platform development, you’ll Qt Designer. And as a core KDE developer, Molkentin’s find The Book of Qt 4 to be indispensable. head is full of real-world problems and solutions that he ABOUT THE AUTHOR peppers liberally throughout The Book of Qt 4, making it a resource that you’ll consult time and again. Daniel “danimo” Molkentin has been a core developer with the KDE project since 2000, and he’s the co-author You’ll find coverage of: of the PIM application Kontact, among other applications. • Tools for creating dialogs He was actively involved in the development of Qt 4 as a beta tester, and he worked with the initial port of KDE to • GUI design with the Qt Designer the new Qt version. • Widget layout and dialog construction MOLKENTIN THE FINEST IN GEEK ENTERTAINMENT™ $54.95 ($65.95 CDN) PROGRAMMING SHELVE IN: www.nostarch.com “I LAY FLAT.” This book uses RepKover —a durable binding that won’t snap shut. ® Printed on recycled paper The Book of Qt 4 Daniel Molkentin TheBook of Qt 4 TheArt of BuildingQtApplications ® Munich SanFrancisco The Book of Qt 4: The ArtofBuildingQtApplications. Copyright " c 2007OpenSource PressGmbH Allrightsreserved.Nopartofthisworkmaybe reproducedortransmittedinanyform or byanymeans, electronic or mechanical, includingphotocopying, recording, or byanyinformationstorageorretrieval system,without theprior writtenpermission of thecopyright ownerand thepublisher. Printedonrecycled paperinthe United States of America. 12345678910—10090807 No Starch Pressand theNoStarch Presslogo areregisteredtrademarksofNoStarch Press, Inc. Otherproduct and companynamesmentioned herein maybe thetrademarksoftheir respectiveowners.Ratherthanuse atrademark symbol witheveryoccurrence of atrademarked name,weare usingthe namesonlyin an editorialfashionand to the benefit of thetrademark owner, withnointention of infringement of thetrademark. Publisher: William Pollock Cover Design:Octopod Studios U.S. editionpublishedbyNo Starch Press, Inc. 555 De HaroStreet,Suite 250,San Francisco, CA 94107 phone: 415.863.9900;fax:415.863.9950;[email protected];http://www.nostarch.com Original edition " c 2006OpenSource PressGmbH PublishedbyOpenSource PressGmbH, Munich, Germany Publisher: Dr.Markus Wirtz Original ISBN 978-3-937514-12-3 For informationontranslations, pleasecontact OpenSource PressGmbH, Amalienstr.45Rg, 80799 M unche¨ n, Germany phone+49.89.28755562; fax+49.89.28755563; [email protected];http://www.opensourcepress.de Theinformationinthisbook is distributed on an “AsIs” basis, without warranty.While everyprecaution hasbeen takeninthe preparationofthiswork, neitherthe author norOpenSource PressGmbHnor No Starch Press, Inc. shall haveanyliabilityto anyperson or entitywithrespect to anyloss or damage caused or allegedtobecaused directly or indirectlybytheinformationcontained in it. LibraryofCongressCataloging-in-Publication Data Molkentin, Daniel [Qt4, Einf¨uhrung in die Applikationsentwicklung.English] The book of Qt4: the art of building Qtapplications/byDaniel Molkentin.-- 1st ed. p. cm. Includesindex. ISBN-13978-1-59327-147-3 ISBN-101-59327-147-6 1.Qt(Electronic resource)2.Graphicaluserinterfaces(Computersystems) 3. Application software--Development. I.Title.QA76.9.U83M62132007 005.4’37--dc22 2007013181 Contents Introduction 19 Preparations23 1Basics, Tools, andFirst Code 25 1.1Our FirstQtProgram .......................... 25 1.1.1CompilingaQtProgram ................... 27 1.2Layouts,Object Hierarchy,and MemoryManagement ........ 29 1.2.1Howto ArrangeWidgets Automatically........... 29 1.2.2MemoryManagement in Object Hierarchies........ 31 1.2.3Other LayoutTypes...................... 33 1.3Signals andSlots ............................ 35 1.3.1The SimplestCase: ASlotResponds to aSignal...... 35 1.3.2Signals CarryingAdditional Information andHowThey AreProcessed. ........................ 36 1.4BaseClassesinQt........................... 39 1.4.1ClassesDerived from QObject ................ 39 1.4.2QString andOther Classesnot Derived from QObject ... 40 1.4.3The Qt InheritanceHierarchy................ 41 1.5QtataGlance ............................. 42 1.5.1The Qt Libraries........................ 42 1.5.2Toolsand Utilities...................... 47 1.5.3Examples andDemos ..................... 58 1.6Howto Use theDocumentation................... 59 5 Contents 2The ToolsNeeded to Create Dialogs61 2.1What’sthe DifferenceBetween Dialogsand Widgets?....... 62 2.1.1Inheriting from QObject ................... 64 2.1.2MoreComplexLayouts .................... 65 2.1.3IncreasingUsability..................... 68 2.1.4ImplementingSlots ..................... 70 2.2SeparationofGUI andProcessing Logic............... 74 2.2.1AlternativeDesign...................... 74 2.2.2Declaring andSending OutSignals ............. 76 2.2.3Using Your OwnSignals ................... 79 3GUI Design Using theQtDesigner81 3.1Dialogs “ByMouseClick” ....................... 81 3.1.1Making Layouts With theDesigner............. 84 3.1.2The PropertyEditor. ..................... 85 3.1.3The Preview.......................... 88 3.1.4Signal/SlotConnections ................... 88 3.1.5The TabSequence...................... 89 3.1.6Shortcuts andBuddies .................... 90 3.2Integrating Designer-generated FilesintoYourQtProject ..... 91 3.2.1Using Designer-generated ClassesasHelperClasses.... 92 3.2.2AlwaysHavingDesigner-generated Widgets Available ... 94 3.2.3MultipleInheritance..................... 95 3.3Automatic Signal/SlotConnections .................. 97 3.4Including Derived Classesinthe Designer .............. 99 3.5The Resource Editor .......................... 99 4Developing aGUI Application BasedonaMain Window 101 4.1The Anatomyof theMainWindow.................. 101 4.2DerivingfromQMainWindow..................... 103 4.3CreatingaMain Windowwiththe Qt Designer........... 106 4.3.1Adding Menu Bars ...................... 107 4.3.2RecyclingActions in theToolbar.............. 108 6 Contents 4.3.3Integrating theMainWindowwithYourSourceCode ... 110 4.4Making theMostofthe Status Bar.................. 118 4.4.1TemporaryMessages..................... 120 4.4.2NormalMessages. ...................... 120 4.4.3Permanent Messages. .................... 121 4.5Toolbars ................................ 125 4.6HowDo ActionsWork? ........................ 126 4.6.1Howto InstantiateQAction Manually............ 127 4.6.2Selectable Actions...................... 128 4.6.3Grouped Actions....................... 128 4.7DockWindows............................. 130 4.7.1Positioning Dock Windows. ................. 131 4.7.2ADock Windowfor OurEditor............... 133 4.8SavingPreferences ........................... 136 4.8.1Extending CuteEdit. ..................... 139 5Laying OutWidgets 141 5.1ManualLayout............................. 141 5.2Automatic Layout........................... 143 5.2.1Horizontaland Vertical Layout............... 144 5.2.2GridLayout.......................... 148 5.2.3Nested Layouts ........................ 149 5.3Splitter ................................. 150 5.3.1BehaviorDuringSizeChanges ................ 150 5.3.2SavingSplitter Positionsand Determining theWidgetSize151 5.3.3Defining RelativeSizes .................... 152 5.3.4CustomizingHandles ..................... 153 5.3.5Layoutfor LanguagesWritten from RighttoLeft..... 156 5.4StackedLayouts ............................ 157 5.4.1The Alternative: Stacked Widgets .............. 157 5.4.2WhentoUse Stacked Layouts andWidgets ......... 157 7 Contents 6Dialogs161 6.1Modal Dialogs............................. 161 6.2Non-modal Dialogs.......................... 163 6.2.1UsabilityProblems ...................... 163 6.3Semi-modal Dialogs.......................... 164 6.4Avoiding Bloated Dialogs....................... 164 6.5Ready-made DialogsinQt...................... 166 6.5.1Message Dialogs....................... 166 6.5.2Error MessagesThatAre OnlyVisible Once ......... 174 6.5.3File SelectionDialogs ..................... 175 6.5.4Input Dialogs......................... 179 6.5.5FontSelection Dialog .................... 182 6.5.6Color Selectionand Printing Dialog ............. 183 7Events, Drag andDrop, andthe