《QT高级编程.pdf》由会员分享,可在线阅读,更多相关《QT高级编程.pdf(554页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、Advanced Qt Programming This page intentionally left blank Advanced Qt ProgrammingCreating Great Software with C+and Qt 4Mark SummerfieldUpper Saddle River,NJBostonIndianapolisSanFranciscop New YorkTorontoMontrealLondonMunichParisMadridpCapetownSydneyTokyoSingaporeMexico City Many of the designation
2、s used by manufacturers and sellers to distinguish their products are claimed as trademarks.Where those designations appear in this book,and the publisher was aware of a trademark claim,the designations have been printed with initial capital letters or in all capitals.The author and publisher have t
3、aken care in the preparation of this book,but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions.No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained h
4、erein.The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales,which may include electronic versions and/or custom covers and content particular to your business,training goals,marketing focus,and branding interests.For more information,pleas
5、e contact:U.S.Corporate and Government Sales (800)382-3419 For sales outside the United States,please contact:International Sales Visit us on the Web: of Congress Cataloging-in-Publication DataSummerfield,Mark.Advanced Qt programming:creating great software with C+and Qt 4/Mark Summerfield.p.mcm.Inc
6、ludes bibliographical references and index.ISBN 978-0-321-63590-7(hardcover:alk.paper)1.Qt(Electronic resource)2.Graphical user interfaces(Computer systems)3.C+(Computer program language)I.Title.QA76.9.U83S88 2010 005.113dc222010019289Copyright 2011 Qtrac Ltd.All rights reserved.Printed in the Unite
7、d 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 re
8、garding permissions,write to:Pearson Education,Inc.Rights and Contracts Department 501 Boylston Street,Suite 900 Boston,MA 02116 Fax:(617)671-3447ISBN-13:978-0-321-63590-7ISBN-10:0-321-63590-6Text printed in the United States on recycled paper at Courier in Westford,Massachusetts.First printing,July
9、 2010 This book is dedicated toAnna RebeccaPaterson This page intentionally left blank Contents at a GlanceList of Tables.xiiiForeword.xvIntroduction.1Chapter 1.Hybrid Desktop/Internet Applications.5Chapter 2.Audio and Video.53Chapter 3.Model/View Table Models.87Chapter 4.Model/View Tree Models.129C
10、hapter 5.Model/View Delegates.185Chapter 6.Model/View Views.207Chapter 7.Threading with QtConcurrent.245Chapter 8.Threading with QThread.287Chapter 9.Creating Rich Text Editors.317Chapter 10.Creating Rich Text Documents.359Chapter 11.Creating Graphics/View Windows.389Chapter 12.Creating Graphics/Vie
11、w Scenes.409Chapter 13.The Animation and State Machine Frameworks.469Epilogue.491Selected Bibliography.495Index.499www.qtrac.eu/aqpbook.htmlvii This page intentionally left blank ContentsList of Tables.xiiiForeword.xvIntroduction.1Acknowledgements.3Chapter 1.Hybrid Desktop/Internet Applications.5Int
12、ernet-Aware Widgets.6Using WebKit.21A Generic Web Browser Window Component.22Creating Web Site-Specific Applications.30Embedding Qt Widgets in Web Pages.44Chapter 2.Audio and Video.53Using QSound and QMovie.54The Phonon MultimediaFramework.60Playing Music.64Playing Videos.80Chapter 3.Model/View Tabl
13、e Models.87Qts Model/View Architecture.88Using QStandardItemModels for Tables.90Changing a Table Model through the User Interface.91A QStandardItemModelSubclass for Tables.102A QSortFilterProxyModelto Filter Out Duplicate Rows.107A QSortFilterProxyModel to Filter In Wanted Rows.109Creating CustomTab
14、le Models.113Changing a Table Model through the User Interface.113A CustomQAbstractTableModelSubclass for Tables.116The QAbstractItemModelAPIMethods for Tables.117Methods to Support Saving and Loading Table Items.126ix Chapter 4.Model/View Tree Models.129Using QStandardItemModels for Trees.130Changi
15、ng a Tree Model through the User Interface.131A QStandardItemSubclass for Tree Items.141A QStandardItemModelSubclass for Trees.143Creating CustomTree Models.151Changing a Tree Model through the User Interface.152A CustomItem Class for Tree Items.155A CustomQAbstractItemModelSubclass for Trees.158The
16、 QAbstractItemModelAPIfor Trees.160The QAbstractItemModelAPIfor Drag and Drop.168Methods for Saving and Loading Tree Items.180Chapter 5.Model/View Delegates.185Datatype-Specific Editors.186Datatype-Specific Delegates.188A ReadOnly Column or Row Delegate.188An Editable Column or Row Delegate.193Model
17、-Specific Delegates.201Chapter 6.Model/View Views.207QAbstractItemView Subclasses.208Model-Specific Visualizing Views.224The Visualizer Widget.225The Visualizers AggregatedHeader Widget.232The Visualizers AggregatedView Widget.235Chapter 7.Threading with QtConcurrent.245Executing Functions in Thread
18、s.248Using QtConcurrent:run().252Using QRunnable.257Filtering and Mapping in Threads.261Using QtConcurrent to Filter.270Using QtConcurrent to Filter and Reduce.277Using QtConcurrent to Map.281Chapter 8.Threading with QThread.Processing Independent Items.287Processing Shared Items.302x Chapter 9.Crea
19、ting Rich Text Editors.317Introducing QTextDocument.318CreatingCustomText Editors.320Completion for Line Edits and Comboboxes.320Completion and Syntax Highlightingfor Text Editors.322Completion for Multi-line Editors.323Syntax Highlighting.336A Rich Text Single Line Editor.342Multi-line Rich Text Ed
20、iting.353Chapter 10.Creating Rich Text Documents.359Exported QTextDocument File Quality.361Creating QTextDocuments.364Creating QTextDocuments with HTML.364Creating QTextDocuments with QTextCursor.367Exporting and Printing Documents.371Exporting QTextDocuments.372Exporting in PDF and PostScript Forma
21、t.372Exporting in Open Document Format.373Exporting in HTML Format.374Exporting in SVG Format.375Exporting in Pixmap Formats.375Printing and Previewing QTextDocuments.376Painting Pages.379Painting PDF or PostScript.387Painting SVG.387Painting Pixmaps.388Chapter 11.Creating Graphics/View Windows.389T
22、he Graphics/View Architecture.390Graphics/View Widgets and Layouts.392Introducing Graphics Items.399Chapter 12.Creating Graphics/View Scenes.409Scenes,Items,and Actions.411Creating the Main Window.412Saving,Loading,Printing,and Exporting Scenes.415Saving Scenes.415Loading Scenes.417xi Printing and E
23、xporting Scenes.420ManipulatingGraphics Items.423Adding Items.425Copying,Cutting,and Pasting Items.427ManipulatingSelected Items.430Showing and Hiding the Guideline Grid.435Keeping the User Interface Up to Date.436Enhancing QGraphicsView.439Creatinga Dock Widget Toolbox.440Creating CustomGraphics It
24、ems.447Enhancing QGraphicsTextItem.447Graphics Item Transformations.453Enhancing an Existing Graphics Item.455Creating a CustomGraphics Item from Scratch.459Chapter 13.The Animation and State Machine Frameworks.469Introducing the Animation Framework.469Introducing the State Machine Framework.474Comb
25、ining Animations and State Machines.481Epilogue.491Selected Bibliography.495Index.499xii List of Tables1.1.The Main WebKit Classes.211.2.Qts Global Utility Functions.462.1.The Main Phonon Classes.633.1.The QAbstractItemModelAPI.1183.2.The Qt:ItemDataRole enum.1193.3.The Qt:ItemFlagenum.1194.1.The QA
26、bstractItemModels Drag and Drop API.1595.1.The QStyledItemDelegate API.1946.1.The QAbstractItemView API.2109.1.The QTextCursor API#1.3289.2.The QTextCursor API#2.3299.3.The QTextCursor API#3.3309.4.The QTextCursor:MoveOperationenum.33411.1.The QGraphicsItemAPI(Selected Methods)#1.40311.2.The QGraphi
27、csItemAPI(Selected Methods)#2.40411.3.The QGraphicsItemAPI(Selected Methods)#3.40511.4.The QGraphicsItemAPI(Selected Methods)#4.40611.5.The Qt:ItemSelectionMode enum.40611.6.The QGraphicsItem:GraphicsItemFlagenum#1.40611.7.The QGraphicsItem:GraphicsItemFlagenum#2.407xiii This page intentionally left
28、 blank ForewordWay back in 1991,I sat on a park bench in Trondheim,Norway,together withHaavardNord.Weweredoingournon-militaryservicetogetherattheregionalhospital there,and needed to develop software for the storage and analysis ofultrasound images.The hospital used all sorts of computers and wanted
29、thesystemtowork on Unix,Mac,and Windows.Thiswasa hugechallengeandwescanned the market for available class libraries that could help us.We wereappalled by the quality of what we found.On that park bench we decided tocome up with our own solution to the challenge.We were young,ambitious,and nave.Sick
30、and tired of wasting our time find-ing outhowtousenon-intuitivetoolsandlibraries,wesetoursightsonimprov-ing thesituation.Wewantedtochangetheworldof softwaredevelopmenteverso slightly.Our goal was to make life easier for software developers.To makeit possible to focus on what we all know is the fun s
31、ide of developing software:being creativeandturning out well-writtencode.So,wecreatedthefirstcrudeversions of Qt,and incorporated Trolltech a few years later.I think we achieved at least part of our goal.Qt has had tremendous successsince it was first released in 1995.In 2008 Trolltech was acquired
32、by Nokia and in April 2009 it was time forme to move on.After 15 years and 27 days in the company I was no longer onthe inside.The product is in good hands,and the passion and hard work of the team arethe same as ever.The Trolls at Nokia are making sure that Qt continues to bethe rock solid framewor
33、k you expect.Lars Knoll(of kHTMLWebKitfame)today leads almost 150 dedicated Qt engineers.Nokia has also added theLGPL as a licensing option,making Qt accessible to even more developers.This fall I was invited by Nokia as a guest of honor at the Qt Developer Daysin Munich,Germany.This user conference
34、which also takes place in theU.S.is a fantastic venue for Qt enthusiasts and has been increasing in sizeyear by year.It was great feeling the buzz and talking to Qt users from allover Europe.I spoke to many developers who told me that Qt makes a realdifference in their software work.That makes an ol
35、d hacker feel good.Qt asa good tool and classlibrary isonly half the story behind itssuccess.Youalso need good documentation,tutorials,and books.After all,the goal was tomake life easier for developers.xv That is why I was never in doubt,back in 2003.I was President of Trolltechand Mark Summerfield,
36、the head of documentation,came into my office.Hewanted to write a book about Qt together with Jasmin Blanchette.A reallygood book,written by someone with intimate knowledge of the product andwith a passion for explaining thingsclearly and intuitively.Who wasbetter fitfor the task than the head of Qt
37、 documentation,together with one of the bestQt developers?The end result was a great book about Qt,which has since been updatedand expanded.Mark has now completed another important project.A good book on advanced Qt programming has been missing in the arsenal ofQt programmers.I m very happy that Mar
38、k has written one.He is a fantastictechnical writer with all the necessary background to write authoritativelyabout Qt programming.His focus on detail and ability to express himselfclearly and intuitively have always impressed me.In other words:You are infor a treat!You are holding in your hands(or
39、reading on-screen)an excellent opportunityto expand on your knowledge of all the cool stuff you can do with Qt.Happy programming!Eirik Chambe-EngThe southern Alps,FranceDecember 24,2009xvi IntroductionFor some time I have wanted to write a Qt book that covered topics that weretoo advanced for C+GUI
40、Programming with Qt 4,even though that bookitself has proved quite challenging for some readers.There is also somespecialized materialnot all of it difficultthat I wanted to cover that simplydoes not belong in a first book on Qt programming.Furthermore,in view ofthe sheer size of Qt,no one book can
41、possibly do justice to all that it offers,sothere was clearly room for the presentation of new material.What I ve done in this book is to take a selection of modules and classes froma variety of areas and shown how to make good use of them.The topicschosen reflect both my own interests and also thos
42、e that seem to result in themost discussion on theqt-interest mailing list.Some of the topics are notcovered in any other book,while other topics cover more familiar groundforexample,model/view programming.In all cases,I have tried to provide morecomprehensive coverage than is available elsewhere.So
43、 the purposes of this book are to help Qt programmers deepen and broadentheir Qt knowledge and to increase the repertoire of what they can achieveusing Qt.The“advanced”aspect often refers more to what you will be ableto achieve than to the means of achieving it.This is becauseas alwaysQtinsulatesusa
44、sfaraspossiblefromirrelevantdetailandunderlyingcomplexityto provide easy-to-use APIs that we can use simply and directly to great effect.For example,we will see how to create a music player without having to knowanything about how thingswork under thehood;wewill need toknowonly thehigh-level API tha
45、t Qt provides.On the other hand,even using the high-levelQtConcurrent module,the coverage of threading is necessarily challenging.Thisbook assumesthat readershavea basic competencein C+programming,and at least know how to create basic Qt applicationsfor example,havingread a good Qt 4 book,and having
46、 had some practical experience.Readersarealso assumed to be familiar with Qt s reference documentation,at least as faras being able to navigate it to look up the APIs of classes of interest.In addi-tion,some chaptersassume some basic topic-specific knowledgefor example,Chapter 1assumessome knowledge
47、 of JavaScript and web programming,andthe threading chapters assume a basic understanding of threading and Qt sthreading classes.All these assumptions mean that this book can avoid ex-C+GUI Programming with Qt 4,Second Edition,by Jasmin Blanchette and this author,ISBN 0132354160.1 2Introductionplain
48、ingmanydetailsandclassesthatarealreadyfamiliartoQtprogrammers,such asusing layouts,creating actions,connecting signalsand slots,and so on,leaving the book free to focus on the less familiar material.Of course,no single volume book can realistically do justice to Qt s more than700 public classesalmos
49、t 800 in Qt 4.6and its much more than one millionwords of documentation,so no attempt is made to do so here.Instead thisbook provides explanations and examples of how to use some of Qt s mostpowerful features,complementing the reference documentation rather thanduplicating it.The book s chapters hav
50、e been designed to be as self-contained as possible,soit is not necessary to read the book from beginning to end in chapter order.Tosupport this,where particular techniques are used in more than one chapter,the explanation is given in just one place and cross-references are given else-where.Nonethel