《面向对象程序设计英文教学课件:15 Qt & Thread》由会员分享,可在线阅读,更多相关《面向对象程序设计英文教学课件:15 Qt & Thread(32页珍藏版)》请在金锄头文库上搜索。
1、Object-Oriented Programming & C+Object-Oriented Programming & C+College of Computer Science, CQU15 Qt & ThreadObject-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & Thread2OutlineTheIntroductionforQt“Helloworld”basedonQtSignal&SlotResourcefileDrawinginQtDoublebuffering
2、AnimationMulti-threadObject-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadReferencehttp:/qt-project.org/dochttp:/en.wikipedia.org/wiki/Qt_(framework)#UI_environments3Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadAbo
3、ut QtQtisacross-platformapplicationframeworkthatiswidelyusedfordevelopingapplicationsoftwarethatcanberunonvarioussoftwareandhardwareplatformswithlittleornochangeinthecodebase,whilehavingthepowerandspeedofnativeapplications.4Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thre
4、ad15 Qt & ThreadQt ModulesQtCore contains core non-GUI classes, including theeventloopandQtssignalandslotmechanism,platformindependentabstractions,andsoon.QtGuicontainsmostGUIclasses;includingmanytableandsophisticated2Dcanvaswidget.QtOpenGL contains classes that enable the useofOpenGLinrendering3Dgr
5、aphics.QtSqlcontainsclassesthatintegratewithopen-sourceandproprietarySQLdatabases.5Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadGetting Started with Qt CreatorQtCreatoristheintegratedsoftwaredevelopmentenvironmentthatsupportsbothtraditionalC+application
6、development,aswellasdevelopmentusingtheQtprojectslibraries.Downloading Qt Creator On Ubuntu, Qt Creator is just a “sudo apt-get install qtcreator” command away. Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadYour first applicationHelloWorldConsoleCreatea“
7、QtConsoleApplication”bywizardtool.HelloWorldGuiCreatea“QtWidgetApplication”bywizardtool.InQtDesign,Addalabel“Helloworld!”Addabutton“exitButton”Addaslotfunctionfor“exitButton”ResourcefileCode: resourceFileDemoCode: helloGuiCode: helloConsoleObject-Oriented Programming & C+Object-Oriented Programming
8、& C+15 Qt & Thread15 Qt & ThreadSignals and SlotsIn software systems, there is often the need to couple differentobjects.Ideally,thiscouplingshouldbeloose,thatis,notdependentonthesystemscompile-timeconfiguration.Thisisespeciallyobviouswhenyouconsideruserinterfaces.Example: a button press may adjust
9、the contents of a textwidgetorcausesomethingtoappearordisappear.Qtofferssignalsandslots.Thesendingcomponentgeneratesasignal(theobjectemitsasignal), which recipient objects may receive in a slot for thepurpose.Any object that inherits fromQObject can emit signals orprovideslotsforconnectiontosignals.
10、Thecommunicationbetweenasignalanditsslotsisoneway.Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadSignalsandSlots9Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadExample: Counter#ifndef COUNTER_H#define COUNTER_H
11、#include class Counter : public QObject Q_OBJECTpublic: Counter(); int getValue() const;signals: void valueChanged(int newValue);public slots: void setValue(int newValue); void increment(); void decrement();private: int m_value;#endif / COUNTER_Hclass CounterObject-Oriented Programming & C+Object-Or
12、iented Programming & C+15 Qt & Thread15 Qt & ThreadExample: CounterCode: signalSlotDemoObject-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadDrawing in QtWheretodraw?Whattouse?Howtodraw?Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thre
13、ad15 Qt & ThreadWhere to draw?QPaintDeviceQWidgetTheQWidgetclassisthebaseclassofalluserinterfaceobjects.Thewidgetistheatomoftheuserinterface:itreceivesmouse,keyboardandothereventsfromthewindowsystem,andpaintsarepresentationofitselfonthescreen.QImageTheQImageclassprovidesahardware-independentimagerep
14、resentationthatallowsdirectaccesstothepixeldata,andcanbeusedasapaintdevice.QImageisdesignedandoptimizedforI/O,andfordirectpixelaccessandmanipulation.QPixmapTheQPixmapclassisanoff-screenimagerepresentationthatcanbeusedasapaintdevice.QPixmapisdesignedandoptimizedforshowingimagesonscreen.QPrinterTheQPr
15、interclassisapaintdevicethatpaintsonaprinter.Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadWhat to use?QPainterThe QPainter class performs low-level painting on widgets andotherpaintdevices.Itcandraweverythingfromsimplelinestocomplexshapeslikepiesandchor
16、ds.Itcanalsodrawalignedtextandpixmaps.QPaintercanoperateonanyobjectthatinheritstheQPaintDeviceclass.Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadQPainterdrawPoint(intx,inty)drawPoints(constQPointArray&a,intindex,intnpoints)drawLine(intx1,inty1,intx2,int
17、y2)drawLines(constQPointArray&a)Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadQPainterdrawPolyLine(constQPointArray&a,intindex,intnpoints)drawPolygon(constQPointArray&a,boolwinding,intindex,intnpoints)drawRect(intx,inty,intw,inth)drawRoundRect(intx,inty,
18、intw,inth,intxRnd,intyRnd)drawEllipse(intx,inty,intw,inth)Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadQPainterdrawArc(intx,inty,intw,inth,inta,intalen)drawChord(intx,inty,intw,inth,inta,intalen)drawPie(intx,inty,intw,inth,inta,intalen)drawText(constQPo
19、int&p,constQString&,intpos,intlen,TextDirectiondir=Auto)drawPixmap(intx,inty,constQPixmap&pixmap,intsx,intsy,intsw,intsh)Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadQPaintersetPen()QPen(constQColor&color,uintwidth=0,PenStylestyle=SolidLine)Object-Orien
20、ted Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadQPaintersetBrush()Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadHow to draw?The common use of QPainter is inside a widgets paint event:Construct and customize the painter. Th
21、en draw. Remember todestroytheQPainterobjectafterdrawing.void SimpleExampleWidget:paintEvent(QPaintEvent *) QPainter painter(this); painter.setPen(Qt:blue); painter.setFont(QFont(Arial, 30); painter.drawText(rect(), Qt:AlignCenter, Qt); Object-Oriented Programming & C+Object-Oriented Programming & C
22、+15 Qt & Thread15 Qt & ThreadDrawing DemoCode: animationDemoObject-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadDouble BufferingWhenmanyimageobjectsaredrewonthepainterofthewindowatthesametime,theflasheffectwouldhappen.Bitmapcouldbeusedtoremovethiseffectbydrawi
23、nginmemory.Firstly,QPixmapobjectshouldbeamemberinaclassderivedfromQMainWindow;Secondly, QPainter object should be created related to theQPixmapobject,andthenthoseimageobjectscouldbedrewontheQPainterobject;At last, Bitmap can be copy to the window in paintEvent()function.Object-Oriented Programming &
24、 C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadCode: doubleBufferingDemoObject-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadAnimationGraphicsViewFrameworkQGraphicsSceneQGraphicsItemQGraphicsViewCode: graphicsviewAnimationDemoObject-Oriented Pro
25、gramming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadThreadThreadsareaboutdoingthingsinparallel,justlikeprocesses.ProcessesWhileyouaremakingcalculationsonaspreadsheet,theremayalsobe a media player running on the same desktop playing yourfavoritesong.Here is an example of two proc
26、esses working in parallel: onerunningthespreadsheetprogram;onerunningamediaplayer.Multitaskingisawellknowntermforprocesses.ThreadsAcloserlookatthemediaplayerrevealsthatthereareagainthingsgoingoninparallelwithinonesingleprocess.Whilethemediaplayerissendingmusictotheaudiodriver,theuserinterfacewithall
27、itsbellsandwhistlesisbeingconstantlyupdated.Thisiswhatthreadsareforconcurrencywithinonesingleprocess.Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadThreadHowisconcurrencyimplemented?ParallelworkonsinglecoreCPUsisanillusion.For processes, the illusion is p
28、roduced by interrupting theprocessorsworkononeprocessafteraveryshorttime.Thentheprocessormovesontothenextprocess.Just as one CPU can power two or more processes, it is alsopossibletolettheCPUrunontwodifferentcodesegmentsofonesingleprocess.ThecurrenttrendinCPUdesignistohaveseveralcores.Aprogramwithmu
29、ltiplethreadscanbeassignedtomultiplecores.Asaresult,distributingworktomorethanonethreadcanmakeaprogramrunmuchfasteronmulticoreCPUs.26Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadGUI Thread & Worker ThreadEachprogramhasonethreadwhenitisstarted.Thisthread
30、iscalledthe main thread (also known as the GUI thread in Qtapplications).TheQtGUImustruninthisthread.Allwidgetsandseveralrelatedclasses,forexampleQPixmap,dontworkinsecondarythreads.A secondary thread is commonly referred to as a worker threadbecauseitisusedtooffloadprocessingworkfromthemainthread.Th
31、erearebasicallytwousecasesforthreads:Makeprocessingfasterbymakinguseofmulticoreprocessors.KeeptheGUIthreadorothertimecriticalthreadsresponsivebyoffloading long lasting processing or blocking calls to otherthreads.27Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt &
32、 ThreadHow to create a thread In QtAclassderivedfromQThreadcancreateanewthreadinaprocess.ThevirtualfunctionRun()shouldbeoverloadedforimplementthespecificwork.28Code: multiThreadDemoObject-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadSimultaneous Access to Data
33、Unlikeprocesses,threadssharethesameaddressspace.Iftwothreadshaveapointertothesameobject,itispossiblethatboththreadswillaccessthatobjectatthesametimeandthiscanpotentiallydestroytheobjectsintegrity.Itseasytoimaginethemanythingsthatcangowrongwhentwomethodsofthesameobjectareexecutedsimultaneously.Simult
34、aneousexecutionofoperationsononeobjectmustbeprevented.29Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadUsing a Mutex to Protect the Integrity of DataAmutexisanobjectthathaslock()andunlock()methodsandremembersifitisalreadylocked.Amutexisdesignedtobecalledf
35、rommultiplethreads.lock()returnsimmediatelyifthemutexisnotlocked.Thenextcallfromanotherthreadwillfindthemutexinalockedstateandthenlock()willblockthethreaduntiltheotherthreadcallsunlock().Thisfunctionalitycanmakesurethatacodesectionwillbeexecutedbyonlyonethreadatatime.30Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadSynchronization- other methodQmutexQMutexLockerQReadWriteLockQReadLocker和QWriteLockerQSemaphore31Object-Oriented Programming & C+Object-Oriented Programming & C+15 Qt & Thread15 Qt & ThreadSynchronization 32