You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

qcustomplot.cpp 923 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278
  1. /***************************************************************************
  2. ** **
  3. ** QCustomPlot, an easy to use, modern plotting widget for Qt **
  4. ** Copyright (C) 2011-2015 Emanuel Eichhammer **
  5. ** **
  6. ** This program is free software: you can redistribute it and/or modify **
  7. ** it under the terms of the GNU General Public License as published by **
  8. ** the Free Software Foundation, either version 3 of the License, or **
  9. ** (at your option) any later version. **
  10. ** **
  11. ** This program is distributed in the hope that it will be useful, **
  12. ** but WITHOUT ANY WARRANTY; without even the implied warranty of **
  13. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the **
  14. ** GNU General Public License for more details. **
  15. ** **
  16. ** You should have received a copy of the GNU General Public License **
  17. ** along with this program. If not, see http://www.gnu.org/licenses/. **
  18. ** **
  19. ****************************************************************************
  20. ** Author: Emanuel Eichhammer **
  21. ** Website/Contact: http://www.qcustomplot.com/ **
  22. ** Date: 22.12.15 **
  23. ** Version: 1.3.2 **
  24. ****************************************************************************/
  25. #include "qcustomplot.h"
  26. ////////////////////////////////////////////////////////////////////////////////////////////////////
  27. //////////////////// QCPPainter
  28. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29. /*! \class QCPPainter
  30. \brief QPainter subclass used internally
  31. This QPainter subclass is used to provide some extended functionality e.g. for tweaking position
  32. consistency between antialiased and non-antialiased painting. Further it provides workarounds
  33. for QPainter quirks.
  34. \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and
  35. restore. So while it is possible to pass a QCPPainter instance to a function that expects a
  36. QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because
  37. it will call the base class implementations of the functions actually hidden by QCPPainter).
  38. */
  39. /*!
  40. Creates a new QCPPainter instance and sets default values
  41. */
  42. QCPPainter::QCPPainter() : QPainter(), mModes(pmDefault), mIsAntialiasing(false)
  43. {
  44. // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet
  45. // and a call to begin() will follow
  46. }
  47. /*!
  48. Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just
  49. like the analogous QPainter constructor, begins painting on \a device immediately.
  50. Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5.
  51. */
  52. QCPPainter::QCPPainter(QPaintDevice* device)
  53. : QPainter(device), mModes(pmDefault), mIsAntialiasing(false)
  54. {
  55. #if QT_VERSION < QT_VERSION_CHECK( \
  56. 5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't
  57. // set. So we set it to get consistency across Qt versions.
  58. if (isActive())
  59. setRenderHint(QPainter::NonCosmeticDefaultPen);
  60. #endif
  61. }
  62. QCPPainter::~QCPPainter()
  63. {}
  64. /*!
  65. Sets the pen of the painter and applies certain fixes to it, depending on the mode of this
  66. QCPPainter.
  67. \note this function hides the non-virtual base class implementation.
  68. */
  69. void QCPPainter::setPen(const QPen& pen)
  70. {
  71. QPainter::setPen(pen);
  72. if (mModes.testFlag(pmNonCosmetic))
  73. makeNonCosmetic();
  74. }
  75. /*! \overload
  76. Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of
  77. this QCPPainter.
  78. \note this function hides the non-virtual base class implementation.
  79. */
  80. void QCPPainter::setPen(const QColor& color)
  81. {
  82. QPainter::setPen(color);
  83. if (mModes.testFlag(pmNonCosmetic))
  84. makeNonCosmetic();
  85. }
  86. /*! \overload
  87. Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of
  88. this QCPPainter.
  89. \note this function hides the non-virtual base class implementation.
  90. */
  91. void QCPPainter::setPen(Qt::PenStyle penStyle)
  92. {
  93. QPainter::setPen(penStyle);
  94. if (mModes.testFlag(pmNonCosmetic))
  95. makeNonCosmetic();
  96. }
  97. /*! \overload
  98. Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when
  99. antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to
  100. integer coordinates and then passes it to the original drawLine.
  101. \note this function hides the non-virtual base class implementation.
  102. */
  103. void QCPPainter::drawLine(const QLineF& line)
  104. {
  105. if (mIsAntialiasing || mModes.testFlag(pmVectorized))
  106. QPainter::drawLine(line);
  107. else
  108. QPainter::drawLine(line.toLine());
  109. }
  110. /*!
  111. Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint
  112. with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between
  113. antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate
  114. systems for AA/Non-AA painting).
  115. */
  116. void QCPPainter::setAntialiasing(bool enabled)
  117. {
  118. setRenderHint(QPainter::Antialiasing, enabled);
  119. if (mIsAntialiasing != enabled) {
  120. mIsAntialiasing = enabled;
  121. if (!mModes.testFlag(
  122. pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs
  123. {
  124. if (mIsAntialiasing)
  125. translate(0.5, 0.5);
  126. else
  127. translate(-0.5, -0.5);
  128. }
  129. }
  130. }
  131. /*!
  132. Sets the mode of the painter. This controls whether the painter shall adjust its
  133. fixes/workarounds optimized for certain output devices.
  134. */
  135. void QCPPainter::setModes(QCPPainter::PainterModes modes)
  136. {
  137. mModes = modes;
  138. }
  139. /*!
  140. Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a
  141. device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5,
  142. all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that
  143. behaviour.
  144. The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets
  145. the render hint as appropriate.
  146. \note this function hides the non-virtual base class implementation.
  147. */
  148. bool QCPPainter::begin(QPaintDevice* device)
  149. {
  150. bool result = QPainter::begin(device);
  151. #if QT_VERSION < QT_VERSION_CHECK( \
  152. 5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't
  153. // set. So we set it to get consistency across Qt versions.
  154. if (result)
  155. setRenderHint(QPainter::NonCosmeticDefaultPen);
  156. #endif
  157. return result;
  158. }
  159. /*! \overload
  160. Sets the mode of the painter. This controls whether the painter shall adjust its
  161. fixes/workarounds optimized for certain output devices.
  162. */
  163. void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled)
  164. {
  165. if (!enabled && mModes.testFlag(mode))
  166. mModes &= ~mode;
  167. else if (enabled && !mModes.testFlag(mode))
  168. mModes |= mode;
  169. }
  170. /*!
  171. Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to
  172. QPainter, the save/restore functions are reimplemented to also save/restore those members.
  173. \note this function hides the non-virtual base class implementation.
  174. \see restore
  175. */
  176. void QCPPainter::save()
  177. {
  178. mAntialiasingStack.push(mIsAntialiasing);
  179. QPainter::save();
  180. }
  181. /*!
  182. Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to
  183. QPainter, the save/restore functions are reimplemented to also save/restore those members.
  184. \note this function hides the non-virtual base class implementation.
  185. \see save
  186. */
  187. void QCPPainter::restore()
  188. {
  189. if (!mAntialiasingStack.isEmpty())
  190. mIsAntialiasing = mAntialiasingStack.pop();
  191. else
  192. qDebug() << Q_FUNC_INFO << "Unbalanced save/restore";
  193. QPainter::restore();
  194. }
  195. /*!
  196. Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen
  197. overrides when the \ref pmNonCosmetic mode is set.
  198. */
  199. void QCPPainter::makeNonCosmetic()
  200. {
  201. if (qFuzzyIsNull(pen().widthF())) {
  202. QPen p = pen();
  203. p.setWidth(1);
  204. QPainter::setPen(p);
  205. }
  206. }
  207. ////////////////////////////////////////////////////////////////////////////////////////////////////
  208. //////////////////// QCPScatterStyle
  209. ////////////////////////////////////////////////////////////////////////////////////////////////////
  210. /*! \class QCPScatterStyle
  211. \brief Represents the visual appearance of scatter points
  212. This class holds information about shape, color and size of scatter points. In plottables like
  213. QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
  214. QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
  215. A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
  216. fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
  217. be controlled with \ref setSize.
  218. \section QCPScatterStyle-defining Specifying a scatter style
  219. You can set all these configurations either by calling the respective functions on an instance:
  220. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1
  221. Or you can use one of the various constructors that take different parameter combinations, making
  222. it easy to specify a scatter style in a single call, like so:
  223. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2
  224. \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
  225. There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
  226. QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
  227. isPenDefined will return false. It leads to scatter points that inherit the pen from the
  228. plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the
  229. line color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes it
  230. very convenient to set up typical scatter settings:
  231. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation
  232. Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
  233. because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
  234. into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
  235. constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
  236. ScatterShape, where actually a QCPScatterStyle is expected.
  237. \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
  238. QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
  239. For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
  240. setCustomPath function or call the constructor that takes a painter path. The scatter shape will
  241. automatically be set to \ref ssCustom.
  242. For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
  243. constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
  244. Note that \ref setSize does not influence the appearance of the pixmap.
  245. */
  246. /* start documentation of inline functions */
  247. /*! \fn bool QCPScatterStyle::isNone() const
  248. Returns whether the scatter shape is \ref ssNone.
  249. \see setShape
  250. */
  251. /*! \fn bool QCPScatterStyle::isPenDefined() const
  252. Returns whether a pen has been defined for this scatter style.
  253. The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those are
  254. \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen is
  255. left undefined, the scatter color will be inherited from the plottable that uses this scatter
  256. style.
  257. \see setPen
  258. */
  259. /* end documentation of inline functions */
  260. /*!
  261. Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
  262. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  263. from the plottable that uses this scatter style.
  264. */
  265. QCPScatterStyle::QCPScatterStyle()
  266. : mSize(6), mShape(ssNone), mPen(Qt::NoPen), mBrush(Qt::NoBrush), mPenDefined(false)
  267. {}
  268. /*!
  269. Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
  270. brush is defined.
  271. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  272. from the plottable that uses this scatter style.
  273. */
  274. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size)
  275. : mSize(size), mShape(shape), mPen(Qt::NoPen), mBrush(Qt::NoBrush), mPenDefined(false)
  276. {}
  277. /*!
  278. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  279. and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
  280. */
  281. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor& color, double size)
  282. : mSize(size), mShape(shape), mPen(QPen(color)), mBrush(Qt::NoBrush), mPenDefined(true)
  283. {}
  284. /*!
  285. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  286. the brush color to \a fill (with a solid pattern), and size to \a size.
  287. */
  288. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor& color, const QColor& fill,
  289. double size)
  290. : mSize(size), mShape(shape), mPen(QPen(color)), mBrush(QBrush(fill)), mPenDefined(true)
  291. {}
  292. /*!
  293. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
  294. brush to \a brush, and size to \a size.
  295. \warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as
  296. \a pen and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding
  297. call\n <tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n doesn't
  298. necessarily lead C++ to use this constructor in some cases, but might mistake <tt>Qt::NoPen</tt>
  299. for a QColor and use the \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const
  300. QColor &fill, double size) constructor instead (which will lead to an unexpected look of the
  301. scatter points). To prevent this, be more explicit with the parameter types. For example, use
  302. <tt>QBrush(Qt::blue)</tt> instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler
  303. that this constructor is wanted.
  304. */
  305. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen& pen, const QBrush& brush,
  306. double size)
  307. : mSize(size), mShape(shape), mPen(pen), mBrush(brush), mPenDefined(pen.style() != Qt::NoPen)
  308. {}
  309. /*!
  310. Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
  311. is set to \ref ssPixmap.
  312. */
  313. QCPScatterStyle::QCPScatterStyle(const QPixmap& pixmap)
  314. : mSize(5)
  315. , mShape(ssPixmap)
  316. , mPen(Qt::NoPen)
  317. , mBrush(Qt::NoBrush)
  318. , mPixmap(pixmap)
  319. , mPenDefined(false)
  320. {}
  321. /*!
  322. Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
  323. scatter shape is set to \ref ssCustom.
  324. The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
  325. different meaning than for built-in scatter points: The custom path will be drawn scaled by a
  326. factor of \a size/6.0. Since the default \a size is 6, the custom path will appear at a its
  327. natural size by default. To double the size of the path for example, set \a size to 12.
  328. */
  329. QCPScatterStyle::QCPScatterStyle(const QPainterPath& customPath, const QPen& pen,
  330. const QBrush& brush, double size)
  331. : mSize(size)
  332. , mShape(ssCustom)
  333. , mPen(pen)
  334. , mBrush(brush)
  335. , mCustomPath(customPath)
  336. , mPenDefined(pen.style() != Qt::NoPen)
  337. {}
  338. /*!
  339. Sets the size (pixel diameter) of the drawn scatter points to \a size.
  340. \see setShape
  341. */
  342. void QCPScatterStyle::setSize(double size)
  343. {
  344. mSize = size;
  345. }
  346. /*!
  347. Sets the shape to \a shape.
  348. Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
  349. ssPixmap and \ref ssCustom, respectively.
  350. \see setSize
  351. */
  352. void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
  353. {
  354. mShape = shape;
  355. }
  356. /*!
  357. Sets the pen that will be used to draw scatter points to \a pen.
  358. If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
  359. a call to this function, even if \a pen is <tt>Qt::NoPen</tt>.
  360. \see setBrush
  361. */
  362. void QCPScatterStyle::setPen(const QPen& pen)
  363. {
  364. mPenDefined = true;
  365. mPen = pen;
  366. }
  367. /*!
  368. Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
  369. shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
  370. \see setPen
  371. */
  372. void QCPScatterStyle::setBrush(const QBrush& brush)
  373. {
  374. mBrush = brush;
  375. }
  376. /*!
  377. Sets the pixmap that will be drawn as scatter point to \a pixmap.
  378. Note that \ref setSize does not influence the appearance of the pixmap.
  379. The scatter shape is automatically set to \ref ssPixmap.
  380. */
  381. void QCPScatterStyle::setPixmap(const QPixmap& pixmap)
  382. {
  383. setShape(ssPixmap);
  384. mPixmap = pixmap;
  385. }
  386. /*!
  387. Sets the custom shape that will be drawn as scatter point to \a customPath.
  388. The scatter shape is automatically set to \ref ssCustom.
  389. */
  390. void QCPScatterStyle::setCustomPath(const QPainterPath& customPath)
  391. {
  392. setShape(ssCustom);
  393. mCustomPath = customPath;
  394. }
  395. /*!
  396. Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
  397. undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
  398. This function is used by plottables (or any class that wants to draw scatters) just before a
  399. number of scatters with this style shall be drawn with the \a painter.
  400. \see drawShape
  401. */
  402. void QCPScatterStyle::applyTo(QCPPainter* painter, const QPen& defaultPen) const
  403. {
  404. painter->setPen(mPenDefined ? mPen : defaultPen);
  405. painter->setBrush(mBrush);
  406. }
  407. /*!
  408. Draws the scatter shape with \a painter at position \a pos.
  409. This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
  410. called before scatter points are drawn with \ref drawShape.
  411. \see applyTo
  412. */
  413. void QCPScatterStyle::drawShape(QCPPainter* painter, QPointF pos) const
  414. {
  415. drawShape(painter, pos.x(), pos.y());
  416. }
  417. /*! \overload
  418. Draws the scatter shape with \a painter at position \a x and \a y.
  419. */
  420. void QCPScatterStyle::drawShape(QCPPainter* painter, double x, double y) const
  421. {
  422. double w = mSize / 2.0;
  423. switch (mShape) {
  424. case ssNone:
  425. break;
  426. case ssDot: {
  427. painter->drawLine(QPointF(x, y), QPointF(x + 0.0001, y));
  428. break;
  429. }
  430. case ssCross: {
  431. painter->drawLine(QLineF(x - w, y - w, x + w, y + w));
  432. painter->drawLine(QLineF(x - w, y + w, x + w, y - w));
  433. break;
  434. }
  435. case ssPlus: {
  436. painter->drawLine(QLineF(x - w, y, x + w, y));
  437. painter->drawLine(QLineF(x, y + w, x, y - w));
  438. break;
  439. }
  440. case ssCircle: {
  441. painter->drawEllipse(QPointF(x, y), w, w);
  442. break;
  443. }
  444. case ssDisc: {
  445. QBrush b = painter->brush();
  446. painter->setBrush(painter->pen().color());
  447. painter->drawEllipse(QPointF(x, y), w, w);
  448. painter->setBrush(b);
  449. break;
  450. }
  451. case ssSquare: {
  452. painter->drawRect(QRectF(x - w, y - w, mSize, mSize));
  453. break;
  454. }
  455. case ssDiamond: {
  456. painter->drawLine(QLineF(x - w, y, x, y - w));
  457. painter->drawLine(QLineF(x, y - w, x + w, y));
  458. painter->drawLine(QLineF(x + w, y, x, y + w));
  459. painter->drawLine(QLineF(x, y + w, x - w, y));
  460. break;
  461. }
  462. case ssStar: {
  463. painter->drawLine(QLineF(x - w, y, x + w, y));
  464. painter->drawLine(QLineF(x, y + w, x, y - w));
  465. painter->drawLine(QLineF(x - w * 0.707, y - w * 0.707, x + w * 0.707, y + w * 0.707));
  466. painter->drawLine(QLineF(x - w * 0.707, y + w * 0.707, x + w * 0.707, y - w * 0.707));
  467. break;
  468. }
  469. case ssTriangle: {
  470. painter->drawLine(QLineF(x - w, y + 0.755 * w, x + w, y + 0.755 * w));
  471. painter->drawLine(QLineF(x + w, y + 0.755 * w, x, y - 0.977 * w));
  472. painter->drawLine(QLineF(x, y - 0.977 * w, x - w, y + 0.755 * w));
  473. break;
  474. }
  475. case ssTriangleInverted: {
  476. painter->drawLine(QLineF(x - w, y - 0.755 * w, x + w, y - 0.755 * w));
  477. painter->drawLine(QLineF(x + w, y - 0.755 * w, x, y + 0.977 * w));
  478. painter->drawLine(QLineF(x, y + 0.977 * w, x - w, y - 0.755 * w));
  479. break;
  480. }
  481. case ssCrossSquare: {
  482. painter->drawLine(QLineF(x - w, y - w, x + w * 0.95, y + w * 0.95));
  483. painter->drawLine(QLineF(x - w, y + w * 0.95, x + w * 0.95, y - w));
  484. painter->drawRect(QRectF(x - w, y - w, mSize, mSize));
  485. break;
  486. }
  487. case ssPlusSquare: {
  488. painter->drawLine(QLineF(x - w, y, x + w * 0.95, y));
  489. painter->drawLine(QLineF(x, y + w, x, y - w));
  490. painter->drawRect(QRectF(x - w, y - w, mSize, mSize));
  491. break;
  492. }
  493. case ssCrossCircle: {
  494. painter->drawLine(QLineF(x - w * 0.707, y - w * 0.707, x + w * 0.670, y + w * 0.670));
  495. painter->drawLine(QLineF(x - w * 0.707, y + w * 0.670, x + w * 0.670, y - w * 0.707));
  496. painter->drawEllipse(QPointF(x, y), w, w);
  497. break;
  498. }
  499. case ssPlusCircle: {
  500. painter->drawLine(QLineF(x - w, y, x + w, y));
  501. painter->drawLine(QLineF(x, y + w, x, y - w));
  502. painter->drawEllipse(QPointF(x, y), w, w);
  503. break;
  504. }
  505. case ssPeace: {
  506. painter->drawLine(QLineF(x, y - w, x, y + w));
  507. painter->drawLine(QLineF(x, y, x - w * 0.707, y + w * 0.707));
  508. painter->drawLine(QLineF(x, y, x + w * 0.707, y + w * 0.707));
  509. painter->drawEllipse(QPointF(x, y), w, w);
  510. break;
  511. }
  512. case ssPixmap: {
  513. painter->drawPixmap(x - mPixmap.width() * 0.5, y - mPixmap.height() * 0.5, mPixmap);
  514. break;
  515. }
  516. case ssCustom: {
  517. QTransform oldTransform = painter->transform();
  518. painter->translate(x, y);
  519. painter->scale(mSize / 6.0, mSize / 6.0);
  520. painter->drawPath(mCustomPath);
  521. painter->setTransform(oldTransform);
  522. break;
  523. }
  524. }
  525. }
  526. ////////////////////////////////////////////////////////////////////////////////////////////////////
  527. //////////////////// QCPLayer
  528. ////////////////////////////////////////////////////////////////////////////////////////////////////
  529. /*! \class QCPLayer
  530. \brief A layer that may contain objects, to control the rendering order
  531. The Layering system of QCustomPlot is the mechanism to control the rendering order of the
  532. elements inside the plot.
  533. It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of
  534. one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer,
  535. QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers
  536. bottom to top and successively draws the layerables of the layers.
  537. A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base
  538. class from which almost all visible objects derive, like axes, grids, graphs, items, etc.
  539. Initially, QCustomPlot has five layers: "background", "grid", "main", "axes" and "legend" (in
  540. that order). The top two layers "axes" and "legend" contain the default axes and legend, so they
  541. will be drawn on top. In the middle, there is the "main" layer. It is initially empty and set as
  542. the current layer (see QCustomPlot::setCurrentLayer). This means, all new plottables, items etc.
  543. are created on this layer by default. Then comes the "grid" layer which contains the QCPGrid
  544. instances (which belong tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background
  545. shall be drawn behind everything else, thus the default QCPAxisRect instance is placed on the
  546. "background" layer. Of course, the layer affiliation of the individual objects can be changed as
  547. required (\ref QCPLayerable::setLayer).
  548. Controlling the ordering of objects is easy: Create a new layer in the position you want it to
  549. be, e.g. above "main", with QCustomPlot::addLayer. Then set the current layer with
  550. QCustomPlot::setCurrentLayer to that new layer and finally create the objects normally. They will
  551. be placed on the new layer automatically, due to the current layer setting. Alternatively you
  552. could have also ignored the current layer setting and just moved the objects with
  553. QCPLayerable::setLayer to the desired layer after creating them.
  554. It is also possible to move whole layers. For example, If you want the grid to be shown in front
  555. of all plottables/items on the "main" layer, just move it above "main" with
  556. QCustomPlot::moveLayer.
  557. The rendering order within one layer is simply by order of creation or insertion. The item
  558. created last (or added last to the layer), is drawn on top of all other objects on that layer.
  559. When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below
  560. the deleted layer, see QCustomPlot::removeLayer.
  561. */
  562. /* start documentation of inline functions */
  563. /*! \fn QList<QCPLayerable*> QCPLayer::children() const
  564. Returns a list of all layerables on this layer. The order corresponds to the rendering order:
  565. layerables with higher indices are drawn above layerables with lower indices.
  566. */
  567. /*! \fn int QCPLayer::index() const
  568. Returns the index this layer has in the QCustomPlot. The index is the integer number by which this
  569. layer can be accessed via \ref QCustomPlot::layer.
  570. Layers with higher indices will be drawn above layers with lower indices.
  571. */
  572. /* end documentation of inline functions */
  573. /*!
  574. Creates a new QCPLayer instance.
  575. Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead.
  576. \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot.
  577. This check is only performed by \ref QCustomPlot::addLayer.
  578. */
  579. QCPLayer::QCPLayer(QCustomPlot* parentPlot, const QString& layerName)
  580. : QObject(parentPlot)
  581. , mParentPlot(parentPlot)
  582. , mName(layerName)
  583. , mIndex(-1)
  584. , // will be set to a proper value by the QCustomPlot layer creation function
  585. mVisible(true)
  586. {
  587. // Note: no need to make sure layerName is unique, because layer
  588. // management is done with QCustomPlot functions.
  589. }
  590. QCPLayer::~QCPLayer()
  591. {
  592. // If child layerables are still on this layer, detach them, so they don't try to reach back to
  593. // this then invalid layer once they get deleted/moved themselves. This only happens when layers
  594. // are deleted directly, like in the QCustomPlot destructor. (The regular layer removal
  595. // procedure for the user is to call QCustomPlot::removeLayer, which moves all layerables off
  596. // this layer before deleting it.)
  597. while (!mChildren.isEmpty())
  598. mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild()
  599. if (mParentPlot->currentLayer() == this)
  600. qDebug() << Q_FUNC_INFO
  601. << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been "
  602. "set to a valid layer or 0 beforehand.";
  603. }
  604. /*!
  605. Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this
  606. layer will be invisible.
  607. This function doesn't change the visibility property of the layerables (\ref
  608. QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the
  609. visibility of the parent layer into account.
  610. */
  611. void QCPLayer::setVisible(bool visible)
  612. {
  613. mVisible = visible;
  614. }
  615. /*! \internal
  616. Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will
  617. be prepended to the list, i.e. be drawn beneath the other layerables already in the list.
  618. This function does not change the \a mLayer member of \a layerable to this layer. (Use
  619. QCPLayerable::setLayer to change the layer of an object, not this function.)
  620. \see removeChild
  621. */
  622. void QCPLayer::addChild(QCPLayerable* layerable, bool prepend)
  623. {
  624. if (!mChildren.contains(layerable)) {
  625. if (prepend)
  626. mChildren.prepend(layerable);
  627. else
  628. mChildren.append(layerable);
  629. } else
  630. qDebug() << Q_FUNC_INFO << "layerable is already child of this layer"
  631. << reinterpret_cast<quintptr>(layerable);
  632. }
  633. /*! \internal
  634. Removes the \a layerable from the list of this layer.
  635. This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer
  636. to change the layer of an object, not this function.)
  637. \see addChild
  638. */
  639. void QCPLayer::removeChild(QCPLayerable* layerable)
  640. {
  641. if (!mChildren.removeOne(layerable))
  642. qDebug() << Q_FUNC_INFO << "layerable is not child of this layer"
  643. << reinterpret_cast<quintptr>(layerable);
  644. }
  645. ////////////////////////////////////////////////////////////////////////////////////////////////////
  646. //////////////////// QCPLayerable
  647. ////////////////////////////////////////////////////////////////////////////////////////////////////
  648. /*! \class QCPLayerable
  649. \brief Base class for all drawable objects
  650. This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid
  651. etc.
  652. Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking
  653. the layers accordingly.
  654. For details about the layering mechanism, see the QCPLayer documentation.
  655. */
  656. /* start documentation of inline functions */
  657. /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const
  658. Returns the parent layerable of this layerable. The parent layerable is used to provide
  659. visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables
  660. only get drawn if their parent layerables are visible, too.
  661. Note that a parent layerable is not necessarily also the QObject parent for memory management.
  662. Further, a layerable doesn't always have a parent layerable, so this function may return 0.
  663. A parent layerable is set implicitly with when placed inside layout elements and doesn't need to
  664. be set manually by the user.
  665. */
  666. /* end documentation of inline functions */
  667. /* start documentation of pure virtual functions */
  668. /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0
  669. \internal
  670. This function applies the default antialiasing setting to the specified \a painter, using the
  671. function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when
  672. \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing
  673. setting may be specified individually, this function should set the antialiasing state of the
  674. most prominent entity. In this case however, the \ref draw function usually calls the specialized
  675. versions of this function before drawing each entity, effectively overriding the setting of the
  676. default antialiasing hint.
  677. <b>First example:</b> QCPGraph has multiple entities that have an antialiasing setting: The graph
  678. line, fills, scatters and error bars. Those can be configured via QCPGraph::setAntialiased,
  679. QCPGraph::setAntialiasedFill, QCPGraph::setAntialiasedScatters etc. Consequently, there isn't
  680. only the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's
  681. antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and
  682. QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw
  683. calls the respective specialized applyAntialiasingHint function.
  684. <b>Second example:</b> QCPItemLine consists only of a line so there is only one antialiasing
  685. setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by
  686. all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the
  687. respective layerable subclass.) Consequently it only has the normal
  688. QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to
  689. care about setting any antialiasing states, because the default antialiasing hint is already set
  690. on the painter when the \ref draw function is called, and that's the state it wants to draw the
  691. line with.
  692. */
  693. /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0
  694. \internal
  695. This function draws the layerable with the specified \a painter. It is only called by
  696. QCustomPlot, if the layerable is visible (\ref setVisible).
  697. Before this function is called, the painter's antialiasing state is set via \ref
  698. applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was
  699. set to \ref clipRect.
  700. */
  701. /* end documentation of pure virtual functions */
  702. /* start documentation of signals */
  703. /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer);
  704. This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to
  705. a different layer.
  706. \see setLayer
  707. */
  708. /* end documentation of signals */
  709. /*!
  710. Creates a new QCPLayerable instance.
  711. Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the
  712. derived classes.
  713. If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a
  714. targetLayer is an empty string, it places itself on the current layer of the plot (see \ref
  715. QCustomPlot::setCurrentLayer).
  716. It is possible to provide 0 as \a plot. In that case, you should assign a parent plot at a later
  717. time with \ref initializeParentPlot.
  718. The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable
  719. parents are mainly used to control visibility in a hierarchy of layerables. This means a
  720. layerable is only drawn, if all its ancestor layerables are also visible. Note that \a
  721. parentLayerable does not become the QObject-parent (for memory management) of this layerable, \a
  722. plot does. It is not uncommon to set the QObject-parent to something else in the constructors of
  723. QCPLayerable subclasses, to guarantee a working destruction hierarchy.
  724. */
  725. QCPLayerable::QCPLayerable(QCustomPlot* plot, QString targetLayer, QCPLayerable* parentLayerable)
  726. : QObject(plot)
  727. , mVisible(true)
  728. , mParentPlot(plot)
  729. , mParentLayerable(parentLayerable)
  730. , mLayer(0)
  731. , mAntialiased(true)
  732. {
  733. if (mParentPlot) {
  734. if (targetLayer.isEmpty())
  735. setLayer(mParentPlot->currentLayer());
  736. else if (!setLayer(targetLayer))
  737. qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer
  738. << "failed.";
  739. }
  740. }
  741. QCPLayerable::~QCPLayerable()
  742. {
  743. if (mLayer) {
  744. mLayer->removeChild(this);
  745. mLayer = 0;
  746. }
  747. }
  748. /*!
  749. Sets the visibility of this layerable object. If an object is not visible, it will not be drawn
  750. on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not
  751. possible.
  752. */
  753. void QCPLayerable::setVisible(bool on)
  754. {
  755. mVisible = on;
  756. }
  757. /*!
  758. Sets the \a layer of this layerable object. The object will be placed on top of the other objects
  759. already on \a layer.
  760. If \a layer is 0, this layerable will not be on any layer and thus not appear in the plot (or
  761. interact/receive events).
  762. Returns true if the layer of this layerable was successfully changed to \a layer.
  763. */
  764. bool QCPLayerable::setLayer(QCPLayer* layer)
  765. {
  766. return moveToLayer(layer, false);
  767. }
  768. /*! \overload
  769. Sets the layer of this layerable object by name
  770. Returns true on success, i.e. if \a layerName is a valid layer name.
  771. */
  772. bool QCPLayerable::setLayer(const QString& layerName)
  773. {
  774. if (!mParentPlot) {
  775. qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
  776. return false;
  777. }
  778. if (QCPLayer* layer = mParentPlot->layer(layerName)) {
  779. return setLayer(layer);
  780. } else {
  781. qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName;
  782. return false;
  783. }
  784. }
  785. /*!
  786. Sets whether this object will be drawn antialiased or not.
  787. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
  788. QCustomPlot::setNotAntialiasedElements.
  789. */
  790. void QCPLayerable::setAntialiased(bool enabled)
  791. {
  792. mAntialiased = enabled;
  793. }
  794. /*!
  795. Returns whether this layerable is visible, taking the visibility of the layerable parent and the
  796. visibility of the layer this layerable is on into account. This is the method that is consulted
  797. to decide whether a layerable shall be drawn or not.
  798. If this layerable has a direct layerable parent (usually set via hierarchies implemented in
  799. subclasses, like in the case of QCPLayoutElement), this function returns true only if this
  800. layerable has its visibility set to true and the parent layerable's \ref realVisibility returns
  801. true.
  802. If this layerable doesn't have a direct layerable parent, returns the state of this layerable's
  803. visibility.
  804. */
  805. bool QCPLayerable::realVisibility() const
  806. {
  807. return mVisible && (!mLayer || mLayer->visible())
  808. && (!mParentLayerable || mParentLayerable.data()->realVisibility());
  809. }
  810. /*!
  811. This function is used to decide whether a click hits a layerable object or not.
  812. \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the
  813. shortest pixel distance of this point to the object. If the object is either invisible or the
  814. distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the
  815. object is not selectable, -1.0 is returned, too.
  816. If the object is represented not by single lines but by an area like a \ref QCPItemText or the
  817. bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In
  818. these cases this function thus returns a constant value greater zero but still below the parent
  819. plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99).
  820. Providing a constant value for area objects allows selecting line objects even when they are
  821. obscured by such area objects, by clicking close to the lines (i.e. closer than
  822. 0.99*selectionTolerance).
  823. The actual setting of the selection state is not done by this function. This is handled by the
  824. parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified
  825. via the selectEvent/deselectEvent methods.
  826. \a details is an optional output parameter. Every layerable subclass may place any information
  827. in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot
  828. decides on the basis of this selectTest call, that the object was successfully selected. The
  829. subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part
  830. objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked
  831. is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be
  832. placed in \a details. So in the subsequent \ref selectEvent, the decision which part was
  833. selected doesn't have to be done a second time for a single selection operation.
  834. You may pass 0 as \a details to indicate that you are not interested in those selection details.
  835. \see selectEvent, deselectEvent, QCustomPlot::setInteractions
  836. */
  837. double QCPLayerable::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  838. {
  839. Q_UNUSED(pos)
  840. Q_UNUSED(onlySelectable)
  841. Q_UNUSED(details)
  842. return -1.0;
  843. }
  844. /*! \internal
  845. Sets the parent plot of this layerable. Use this function once to set the parent plot if you have
  846. passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to
  847. another one.
  848. Note that, unlike when passing a non-null parent plot in the constructor, this function does not
  849. make \a parentPlot the QObject-parent of this layerable. If you want this, call
  850. QObject::setParent(\a parentPlot) in addition to this function.
  851. Further, you will probably want to set a layer (\ref setLayer) after calling this function, to
  852. make the layerable appear on the QCustomPlot.
  853. The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized
  854. so they can react accordingly (e.g. also initialize the parent plot of child layerables, like
  855. QCPLayout does).
  856. */
  857. void QCPLayerable::initializeParentPlot(QCustomPlot* parentPlot)
  858. {
  859. if (mParentPlot) {
  860. qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized";
  861. return;
  862. }
  863. if (!parentPlot)
  864. qDebug() << Q_FUNC_INFO << "called with parentPlot zero";
  865. mParentPlot = parentPlot;
  866. parentPlotInitialized(mParentPlot);
  867. }
  868. /*! \internal
  869. Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable
  870. does not become the QObject-parent (for memory management) of this layerable.
  871. The parent layerable has influence on the return value of the \ref realVisibility method. Only
  872. layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be
  873. drawn.
  874. \see realVisibility
  875. */
  876. void QCPLayerable::setParentLayerable(QCPLayerable* parentLayerable)
  877. {
  878. mParentLayerable = parentLayerable;
  879. }
  880. /*! \internal
  881. Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to
  882. the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is
  883. false, the object will be appended.
  884. Returns true on success, i.e. if \a layer is a valid layer.
  885. */
  886. bool QCPLayerable::moveToLayer(QCPLayer* layer, bool prepend)
  887. {
  888. if (layer && !mParentPlot) {
  889. qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
  890. return false;
  891. }
  892. if (layer && layer->parentPlot() != mParentPlot) {
  893. qDebug() << Q_FUNC_INFO << "layer" << layer->name()
  894. << "is not in same QCustomPlot as this layerable";
  895. return false;
  896. }
  897. QCPLayer* oldLayer = mLayer;
  898. if (mLayer)
  899. mLayer->removeChild(this);
  900. mLayer = layer;
  901. if (mLayer)
  902. mLayer->addChild(this, prepend);
  903. if (mLayer != oldLayer)
  904. emit layerChanged(mLayer);
  905. return true;
  906. }
  907. /*! \internal
  908. Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a
  909. localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref
  910. QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is
  911. controlled via \a overrideElement.
  912. */
  913. void QCPLayerable::applyAntialiasingHint(QCPPainter* painter, bool localAntialiased,
  914. QCP::AntialiasedElement overrideElement) const
  915. {
  916. if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement))
  917. painter->setAntialiasing(false);
  918. else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement))
  919. painter->setAntialiasing(true);
  920. else
  921. painter->setAntialiasing(localAntialiased);
  922. }
  923. /*! \internal
  924. This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting
  925. of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the
  926. parent plot is set at a later time.
  927. For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any
  928. QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level
  929. element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To
  930. propagate the parent plot to all the children of the hierarchy, the top level element then uses
  931. this function to pass the parent plot on to its child elements.
  932. The default implementation does nothing.
  933. \see initializeParentPlot
  934. */
  935. void QCPLayerable::parentPlotInitialized(QCustomPlot* parentPlot)
  936. {
  937. Q_UNUSED(parentPlot)
  938. }
  939. /*! \internal
  940. Returns the selection category this layerable shall belong to. The selection category is used in
  941. conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and
  942. which aren't.
  943. Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref
  944. QCP::iSelectOther. This is what the default implementation returns.
  945. \see QCustomPlot::setInteractions
  946. */
  947. QCP::Interaction QCPLayerable::selectionCategory() const
  948. {
  949. return QCP::iSelectOther;
  950. }
  951. /*! \internal
  952. Returns the clipping rectangle of this layerable object. By default, this is the viewport of the
  953. parent QCustomPlot. Specific subclasses may reimplement this function to provide different
  954. clipping rects.
  955. The returned clipping rect is set on the painter before the draw function of the respective
  956. object is called.
  957. */
  958. QRect QCPLayerable::clipRect() const
  959. {
  960. if (mParentPlot)
  961. return mParentPlot->viewport();
  962. else
  963. return QRect();
  964. }
  965. /*! \internal
  966. This event is called when the layerable shall be selected, as a consequence of a click by the
  967. user. Subclasses should react to it by setting their selection state appropriately. The default
  968. implementation does nothing.
  969. \a event is the mouse event that caused the selection. \a additive indicates, whether the user
  970. was holding the multi-select-modifier while performing the selection (see \ref
  971. QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled
  972. (i.e. become selected when unselected and unselected when selected).
  973. Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e.
  974. returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot).
  975. The \a details data you output from \ref selectTest is fed back via \a details here. You may
  976. use it to transport any kind of information from the selectTest to the possibly subsequent
  977. selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable
  978. that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need
  979. to do the calculation again to find out which part was actually clicked.
  980. \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must
  981. set the value either to true or false, depending on whether the selection state of this layerable
  982. was actually changed. For layerables that only are selectable as a whole and not in parts, this
  983. is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the
  984. selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the
  985. layerable was previously unselected and now is switched to the selected state.
  986. \see selectTest, deselectEvent
  987. */
  988. void QCPLayerable::selectEvent(QMouseEvent* event, bool additive, const QVariant& details,
  989. bool* selectionStateChanged)
  990. {
  991. Q_UNUSED(event)
  992. Q_UNUSED(additive)
  993. Q_UNUSED(details)
  994. Q_UNUSED(selectionStateChanged)
  995. }
  996. /*! \internal
  997. This event is called when the layerable shall be deselected, either as consequence of a user
  998. interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by
  999. unsetting their selection appropriately.
  1000. just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must
  1001. return true or false when the selection state of this layerable has changed or not changed,
  1002. respectively.
  1003. \see selectTest, selectEvent
  1004. */
  1005. void QCPLayerable::deselectEvent(bool* selectionStateChanged)
  1006. {
  1007. Q_UNUSED(selectionStateChanged)
  1008. }
  1009. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1010. //////////////////// QCPRange
  1011. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1012. /*! \class QCPRange
  1013. \brief Represents the range an axis is encompassing.
  1014. contains a \a lower and \a upper double value and provides convenience input, output and
  1015. modification functions.
  1016. \see QCPAxis::setRange
  1017. */
  1018. /*!
  1019. Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller
  1020. intervals would cause errors due to the 11-bit exponent of double precision numbers,
  1021. corresponding to a minimum magnitude of roughly 1e-308.
  1022. \see validRange, maxRange
  1023. */
  1024. const double QCPRange::minRange = 1e-280;
  1025. /*!
  1026. Maximum values (negative and positive) the range will accept in range-changing functions.
  1027. Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers,
  1028. corresponding to a maximum magnitude of roughly 1e308.
  1029. Since the number of planck-volumes in the entire visible universe is only ~1e183, this should
  1030. be enough.
  1031. \see validRange, minRange
  1032. */
  1033. const double QCPRange::maxRange = 1e250;
  1034. /*!
  1035. Constructs a range with \a lower and \a upper set to zero.
  1036. */
  1037. QCPRange::QCPRange() : lower(0), upper(0)
  1038. {}
  1039. /*! \overload
  1040. Constructs a range with the specified \a lower and \a upper values.
  1041. */
  1042. QCPRange::QCPRange(double lower, double upper) : lower(lower), upper(upper)
  1043. {
  1044. normalize();
  1045. }
  1046. /*!
  1047. Returns the size of the range, i.e. \a upper-\a lower
  1048. */
  1049. double QCPRange::size() const
  1050. {
  1051. return upper - lower;
  1052. }
  1053. /*!
  1054. Returns the center of the range, i.e. (\a upper+\a lower)*0.5
  1055. */
  1056. double QCPRange::center() const
  1057. {
  1058. return (upper + lower) * 0.5;
  1059. }
  1060. /*!
  1061. Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values
  1062. are swapped.
  1063. */
  1064. void QCPRange::normalize()
  1065. {
  1066. if (lower > upper)
  1067. qSwap(lower, upper);
  1068. }
  1069. /*!
  1070. Expands this range such that \a otherRange is contained in the new range. It is assumed that both
  1071. this range and \a otherRange are normalized (see \ref normalize).
  1072. If \a otherRange is already inside the current range, this function does nothing.
  1073. \see expanded
  1074. */
  1075. void QCPRange::expand(const QCPRange& otherRange)
  1076. {
  1077. if (lower > otherRange.lower)
  1078. lower = otherRange.lower;
  1079. if (upper < otherRange.upper)
  1080. upper = otherRange.upper;
  1081. }
  1082. /*!
  1083. Returns an expanded range that contains this and \a otherRange. It is assumed that both this
  1084. range and \a otherRange are normalized (see \ref normalize).
  1085. \see expand
  1086. */
  1087. QCPRange QCPRange::expanded(const QCPRange& otherRange) const
  1088. {
  1089. QCPRange result = *this;
  1090. result.expand(otherRange);
  1091. return result;
  1092. }
  1093. /*!
  1094. Returns a sanitized version of the range. Sanitized means for logarithmic scales, that
  1095. the range won't span the positive and negative sign domain, i.e. contain zero. Further
  1096. \a lower will always be numerically smaller (or equal) to \a upper.
  1097. If the original range does span positive and negative sign domains or contains zero,
  1098. the returned range will try to approximate the original range as good as possible.
  1099. If the positive interval of the original range is wider than the negative interval, the
  1100. returned range will only contain the positive interval, with lower bound set to \a rangeFac or
  1101. \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative
  1102. interval is wider than the positive interval, this time by changing the \a upper bound.
  1103. */
  1104. QCPRange QCPRange::sanitizedForLogScale() const
  1105. {
  1106. double rangeFac = 1e-3;
  1107. QCPRange sanitizedRange(lower, upper);
  1108. sanitizedRange.normalize();
  1109. // can't have range spanning negative and positive values in log plot, so change range to fix it
  1110. // if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1))
  1111. if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0) {
  1112. // case lower is 0
  1113. if (rangeFac < sanitizedRange.upper * rangeFac)
  1114. sanitizedRange.lower = rangeFac;
  1115. else
  1116. sanitizedRange.lower = sanitizedRange.upper * rangeFac;
  1117. } // else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1))
  1118. else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0) {
  1119. // case upper is 0
  1120. if (-rangeFac > sanitizedRange.lower * rangeFac)
  1121. sanitizedRange.upper = -rangeFac;
  1122. else
  1123. sanitizedRange.upper = sanitizedRange.lower * rangeFac;
  1124. } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) {
  1125. // find out whether negative or positive interval is wider to decide which sign domain will
  1126. // be chosen
  1127. if (-sanitizedRange.lower > sanitizedRange.upper) {
  1128. // negative is wider, do same as in case upper is 0
  1129. if (-rangeFac > sanitizedRange.lower * rangeFac)
  1130. sanitizedRange.upper = -rangeFac;
  1131. else
  1132. sanitizedRange.upper = sanitizedRange.lower * rangeFac;
  1133. } else {
  1134. // positive is wider, do same as in case lower is 0
  1135. if (rangeFac < sanitizedRange.upper * rangeFac)
  1136. sanitizedRange.lower = rangeFac;
  1137. else
  1138. sanitizedRange.lower = sanitizedRange.upper * rangeFac;
  1139. }
  1140. }
  1141. // due to normalization, case lower>0 && upper<0 should never occur, because that implies
  1142. // upper<lower
  1143. return sanitizedRange;
  1144. }
  1145. /*!
  1146. Returns a sanitized version of the range. Sanitized means for linear scales, that
  1147. \a lower will always be numerically smaller (or equal) to \a upper.
  1148. */
  1149. QCPRange QCPRange::sanitizedForLinScale() const
  1150. {
  1151. QCPRange sanitizedRange(lower, upper);
  1152. sanitizedRange.normalize();
  1153. return sanitizedRange;
  1154. }
  1155. /*!
  1156. Returns true when \a value lies within or exactly on the borders of the range.
  1157. */
  1158. bool QCPRange::contains(double value) const
  1159. {
  1160. return value >= lower && value <= upper;
  1161. }
  1162. /*!
  1163. Checks, whether the specified range is within valid bounds, which are defined
  1164. as QCPRange::maxRange and QCPRange::minRange.
  1165. A valid range means:
  1166. \li range bounds within -maxRange and maxRange
  1167. \li range size above minRange
  1168. \li range size below maxRange
  1169. */
  1170. bool QCPRange::validRange(double lower, double upper)
  1171. {
  1172. return (lower > -maxRange && upper < maxRange && qAbs(lower - upper) > minRange
  1173. && qAbs(lower - upper) < maxRange && !(lower > 0 && qIsInf(upper / lower))
  1174. && !(upper < 0 && qIsInf(lower / upper)));
  1175. }
  1176. /*!
  1177. \overload
  1178. Checks, whether the specified range is within valid bounds, which are defined
  1179. as QCPRange::maxRange and QCPRange::minRange.
  1180. A valid range means:
  1181. \li range bounds within -maxRange and maxRange
  1182. \li range size above minRange
  1183. \li range size below maxRange
  1184. */
  1185. bool QCPRange::validRange(const QCPRange& range)
  1186. {
  1187. return (range.lower > -maxRange && range.upper < maxRange
  1188. && qAbs(range.lower - range.upper) > minRange
  1189. && qAbs(range.lower - range.upper) < maxRange
  1190. && !(range.lower > 0 && qIsInf(range.upper / range.lower))
  1191. && !(range.upper < 0 && qIsInf(range.lower / range.upper)));
  1192. }
  1193. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1194. //////////////////// QCPMarginGroup
  1195. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1196. /*! \class QCPMarginGroup
  1197. \brief A margin group allows synchronization of margin sides if working with multiple layout
  1198. elements.
  1199. QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that
  1200. they will all have the same size, based on the largest required margin in the group.
  1201. \n
  1202. \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup"
  1203. \n
  1204. In certain situations it is desirable that margins at specific sides are synchronized across
  1205. layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will
  1206. provide a cleaner look to the user if the left and right margins of the two axis rects are of the
  1207. same size. The left axis of the top axis rect will then be at the same horizontal position as the
  1208. left axis of the lower axis rect, making them appear aligned. The same applies for the right
  1209. axes. This is what QCPMarginGroup makes possible.
  1210. To add/remove a specific side of a layout element to/from a margin group, use the \ref
  1211. QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call
  1212. \ref clear, or just delete the margin group.
  1213. \section QCPMarginGroup-example Example
  1214. First create a margin group:
  1215. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1
  1216. Then set this group on the layout element sides:
  1217. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-2
  1218. Here, we've used the first two axis rects of the plot and synchronized their left margins with
  1219. each other and their right margins with each other.
  1220. */
  1221. /* start documentation of inline functions */
  1222. /*! \fn QList<QCPLayoutElement*> QCPMarginGroup::elements(QCP::MarginSide side) const
  1223. Returns a list of all layout elements that have their margin \a side associated with this margin
  1224. group.
  1225. */
  1226. /* end documentation of inline functions */
  1227. /*!
  1228. Creates a new QCPMarginGroup instance in \a parentPlot.
  1229. */
  1230. QCPMarginGroup::QCPMarginGroup(QCustomPlot* parentPlot)
  1231. : QObject(parentPlot), mParentPlot(parentPlot)
  1232. {
  1233. mChildren.insert(QCP::msLeft, QList<QCPLayoutElement*>());
  1234. mChildren.insert(QCP::msRight, QList<QCPLayoutElement*>());
  1235. mChildren.insert(QCP::msTop, QList<QCPLayoutElement*>());
  1236. mChildren.insert(QCP::msBottom, QList<QCPLayoutElement*>());
  1237. }
  1238. QCPMarginGroup::~QCPMarginGroup()
  1239. {
  1240. clear();
  1241. }
  1242. /*!
  1243. Returns whether this margin group is empty. If this function returns true, no layout elements use
  1244. this margin group to synchronize margin sides.
  1245. */
  1246. bool QCPMarginGroup::isEmpty() const
  1247. {
  1248. QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*>> it(mChildren);
  1249. while (it.hasNext()) {
  1250. it.next();
  1251. if (!it.value().isEmpty())
  1252. return false;
  1253. }
  1254. return true;
  1255. }
  1256. /*!
  1257. Clears this margin group. The synchronization of the margin sides that use this margin group is
  1258. lifted and they will use their individual margin sizes again.
  1259. */
  1260. void QCPMarginGroup::clear()
  1261. {
  1262. // make all children remove themselves from this margin group:
  1263. QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*>> it(mChildren);
  1264. while (it.hasNext()) {
  1265. it.next();
  1266. const QList<QCPLayoutElement*> elements = it.value();
  1267. for (int i = elements.size() - 1; i >= 0; --i)
  1268. elements.at(i)->setMarginGroup(it.key(),
  1269. 0); // removes itself from mChildren via removeChild
  1270. }
  1271. }
  1272. /*! \internal
  1273. Returns the synchronized common margin for \a side. This is the margin value that will be used by
  1274. the layout element on the respective side, if it is part of this margin group.
  1275. The common margin is calculated by requesting the automatic margin (\ref
  1276. QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin
  1277. group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into
  1278. account, too.)
  1279. */
  1280. int QCPMarginGroup::commonMargin(QCP::MarginSide side) const
  1281. {
  1282. // query all automatic margins of the layout elements in this margin group side and find
  1283. // maximum:
  1284. int result = 0;
  1285. const QList<QCPLayoutElement*> elements = mChildren.value(side);
  1286. for (int i = 0; i < elements.size(); ++i) {
  1287. if (!elements.at(i)->autoMargins().testFlag(side))
  1288. continue;
  1289. int m = qMax(elements.at(i)->calculateAutoMargin(side),
  1290. QCP::getMarginValue(elements.at(i)->minimumMargins(), side));
  1291. if (m > result)
  1292. result = m;
  1293. }
  1294. return result;
  1295. }
  1296. /*! \internal
  1297. Adds \a element to the internal list of child elements, for the margin \a side.
  1298. This function does not modify the margin group property of \a element.
  1299. */
  1300. void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement* element)
  1301. {
  1302. if (!mChildren[side].contains(element))
  1303. mChildren[side].append(element);
  1304. else
  1305. qDebug() << Q_FUNC_INFO << "element is already child of this margin group side"
  1306. << reinterpret_cast<quintptr>(element);
  1307. }
  1308. /*! \internal
  1309. Removes \a element from the internal list of child elements, for the margin \a side.
  1310. This function does not modify the margin group property of \a element.
  1311. */
  1312. void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement* element)
  1313. {
  1314. if (!mChildren[side].removeOne(element))
  1315. qDebug() << Q_FUNC_INFO << "element is not child of this margin group side"
  1316. << reinterpret_cast<quintptr>(element);
  1317. }
  1318. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1319. //////////////////// QCPLayoutElement
  1320. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1321. /*! \class QCPLayoutElement
  1322. \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system".
  1323. This is an abstract base class. As such, it can't be instantiated directly, rather use one of its
  1324. subclasses.
  1325. A Layout element is a rectangular object which can be placed in layouts. It has an outer rect
  1326. (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference
  1327. between outer and inner rect is called its margin. The margin can either be set to automatic or
  1328. manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be
  1329. set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic,
  1330. the layout element subclass will control the value itself (via \ref calculateAutoMargin).
  1331. Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level
  1332. layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref
  1333. QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested.
  1334. Thus in QCustomPlot one can divide layout elements into two categories: The ones that are
  1335. invisible by themselves, because they don't draw anything. Their only purpose is to manage the
  1336. position and size of other layout elements. This category of layout elements usually use
  1337. QCPLayout as base class. Then there is the category of layout elements which actually draw
  1338. something. For example, QCPAxisRect, QCPLegend and QCPPlotTitle are of this category. This does
  1339. not necessarily mean that the latter category can't have child layout elements. QCPLegend for
  1340. instance, actually derives from QCPLayoutGrid and the individual legend items are child layout
  1341. elements in the grid layout.
  1342. */
  1343. /* start documentation of inline functions */
  1344. /*! \fn QCPLayout *QCPLayoutElement::layout() const
  1345. Returns the parent layout of this layout element.
  1346. */
  1347. /*! \fn QRect QCPLayoutElement::rect() const
  1348. Returns the inner rect of this layout element. The inner rect is the outer rect (\ref
  1349. setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins).
  1350. In some cases, the area between outer and inner rect is left blank. In other cases the margin
  1351. area is used to display peripheral graphics while the main content is in the inner rect. This is
  1352. where automatic margin calculation becomes interesting because it allows the layout element to
  1353. adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect
  1354. draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if
  1355. \ref setAutoMargins is enabled) according to the space required by the labels of the axes.
  1356. */
  1357. /*! \fn virtual void QCPLayoutElement::mousePressEvent(QMouseEvent *event)
  1358. This event is called, if the mouse was pressed while being inside the outer rect of this layout
  1359. element.
  1360. */
  1361. /*! \fn virtual void QCPLayoutElement::mouseMoveEvent(QMouseEvent *event)
  1362. This event is called, if the mouse is moved inside the outer rect of this layout element.
  1363. */
  1364. /*! \fn virtual void QCPLayoutElement::mouseReleaseEvent(QMouseEvent *event)
  1365. This event is called, if the mouse was previously pressed inside the outer rect of this layout
  1366. element and is now released.
  1367. */
  1368. /*! \fn virtual void QCPLayoutElement::mouseDoubleClickEvent(QMouseEvent *event)
  1369. This event is called, if the mouse is double-clicked inside the outer rect of this layout
  1370. element.
  1371. */
  1372. /*! \fn virtual void QCPLayoutElement::wheelEvent(QWheelEvent *event)
  1373. This event is called, if the mouse wheel is scrolled while the cursor is inside the rect of this
  1374. layout element.
  1375. */
  1376. /* end documentation of inline functions */
  1377. /*!
  1378. Creates an instance of QCPLayoutElement and sets default values.
  1379. */
  1380. QCPLayoutElement::QCPLayoutElement(QCustomPlot* parentPlot)
  1381. : QCPLayerable(parentPlot)
  1382. , // parenthood is changed as soon as layout element gets inserted into a layout (except for top
  1383. // level layout)
  1384. mParentLayout(0)
  1385. , mMinimumSize()
  1386. , mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)
  1387. , mRect(0, 0, 0, 0)
  1388. , mOuterRect(0, 0, 0, 0)
  1389. , mMargins(0, 0, 0, 0)
  1390. , mMinimumMargins(0, 0, 0, 0)
  1391. , mAutoMargins(QCP::msAll)
  1392. {}
  1393. QCPLayoutElement::~QCPLayoutElement()
  1394. {
  1395. setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any
  1396. // unregister at layout:
  1397. if (qobject_cast<QCPLayout*>(
  1398. mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to
  1399. // call clear() in its dtor and this dtor is called by QObject dtor
  1400. mParentLayout->take(this);
  1401. }
  1402. /*!
  1403. Sets the outer rect of this layout element. If the layout element is inside a layout, the layout
  1404. sets the position and size of this layout element using this function.
  1405. Calling this function externally has no effect, since the layout will overwrite any changes to
  1406. the outer rect upon the next replot.
  1407. The layout element will adapt its inner \ref rect by applying the margins inward to the outer
  1408. rect.
  1409. \see rect
  1410. */
  1411. void QCPLayoutElement::setOuterRect(const QRect& rect)
  1412. {
  1413. if (mOuterRect != rect) {
  1414. mOuterRect = rect;
  1415. mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(),
  1416. -mMargins.bottom());
  1417. }
  1418. }
  1419. /*!
  1420. Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all
  1421. sides, this function is used to manually set the margin on those sides. Sides that are still set
  1422. to be handled automatically are ignored and may have any value in \a margins.
  1423. The margin is the distance between the outer rect (controlled by the parent layout via \ref
  1424. setOuterRect) and the inner \ref rect (which usually contains the main content of this layout
  1425. element).
  1426. \see setAutoMargins
  1427. */
  1428. void QCPLayoutElement::setMargins(const QMargins& margins)
  1429. {
  1430. if (mMargins != margins) {
  1431. mMargins = margins;
  1432. mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(),
  1433. -mMargins.bottom());
  1434. }
  1435. }
  1436. /*!
  1437. If \ref setAutoMargins is enabled on some or all margins, this function is used to provide
  1438. minimum values for those margins.
  1439. The minimum values are not enforced on margin sides that were set to be under manual control via
  1440. \ref setAutoMargins.
  1441. \see setAutoMargins
  1442. */
  1443. void QCPLayoutElement::setMinimumMargins(const QMargins& margins)
  1444. {
  1445. if (mMinimumMargins != margins) {
  1446. mMinimumMargins = margins;
  1447. }
  1448. }
  1449. /*!
  1450. Sets on which sides the margin shall be calculated automatically. If a side is calculated
  1451. automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is
  1452. set to be controlled manually, the value may be specified with \ref setMargins.
  1453. Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref
  1454. setMarginGroup), to synchronize (align) it with other layout elements in the plot.
  1455. \see setMinimumMargins, setMargins
  1456. */
  1457. void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides)
  1458. {
  1459. mAutoMargins = sides;
  1460. }
  1461. /*!
  1462. Sets the minimum size for the inner \ref rect of this layout element. A parent layout tries to
  1463. respect the \a size here by changing row/column sizes in the layout accordingly.
  1464. If the parent layout size is not sufficient to satisfy all minimum size constraints of its child
  1465. layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot
  1466. propagates the layout's size constraints to the outside by setting its own minimum QWidget size
  1467. accordingly, so violations of \a size should be exceptions.
  1468. */
  1469. void QCPLayoutElement::setMinimumSize(const QSize& size)
  1470. {
  1471. if (mMinimumSize != size) {
  1472. mMinimumSize = size;
  1473. if (mParentLayout)
  1474. mParentLayout->sizeConstraintsChanged();
  1475. }
  1476. }
  1477. /*! \overload
  1478. Sets the minimum size for the inner \ref rect of this layout element.
  1479. */
  1480. void QCPLayoutElement::setMinimumSize(int width, int height)
  1481. {
  1482. setMinimumSize(QSize(width, height));
  1483. }
  1484. /*!
  1485. Sets the maximum size for the inner \ref rect of this layout element. A parent layout tries to
  1486. respect the \a size here by changing row/column sizes in the layout accordingly.
  1487. */
  1488. void QCPLayoutElement::setMaximumSize(const QSize& size)
  1489. {
  1490. if (mMaximumSize != size) {
  1491. mMaximumSize = size;
  1492. if (mParentLayout)
  1493. mParentLayout->sizeConstraintsChanged();
  1494. }
  1495. }
  1496. /*! \overload
  1497. Sets the maximum size for the inner \ref rect of this layout element.
  1498. */
  1499. void QCPLayoutElement::setMaximumSize(int width, int height)
  1500. {
  1501. setMaximumSize(QSize(width, height));
  1502. }
  1503. /*!
  1504. Sets the margin \a group of the specified margin \a sides.
  1505. Margin groups allow synchronizing specified margins across layout elements, see the documentation
  1506. of \ref QCPMarginGroup.
  1507. To unset the margin group of \a sides, set \a group to 0.
  1508. Note that margin groups only work for margin sides that are set to automatic (\ref
  1509. setAutoMargins).
  1510. */
  1511. void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup* group)
  1512. {
  1513. QVector<QCP::MarginSide> sideVector;
  1514. if (sides.testFlag(QCP::msLeft))
  1515. sideVector.append(QCP::msLeft);
  1516. if (sides.testFlag(QCP::msRight))
  1517. sideVector.append(QCP::msRight);
  1518. if (sides.testFlag(QCP::msTop))
  1519. sideVector.append(QCP::msTop);
  1520. if (sides.testFlag(QCP::msBottom))
  1521. sideVector.append(QCP::msBottom);
  1522. for (int i = 0; i < sideVector.size(); ++i) {
  1523. QCP::MarginSide side = sideVector.at(i);
  1524. if (marginGroup(side) != group) {
  1525. QCPMarginGroup* oldGroup = marginGroup(side);
  1526. if (oldGroup) // unregister at old group
  1527. oldGroup->removeChild(side, this);
  1528. if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and
  1529. // register there
  1530. {
  1531. mMarginGroups.remove(side);
  1532. } else // setting to a new group
  1533. {
  1534. mMarginGroups[side] = group;
  1535. group->addChild(side, this);
  1536. }
  1537. }
  1538. }
  1539. }
  1540. /*!
  1541. Updates the layout element and sub-elements. This function is automatically called before every
  1542. replot by the parent layout element. It is called multiple times, once for every \ref
  1543. UpdatePhase. The phases are run through in the order of the enum values. For details about what
  1544. happens at the different phases, see the documentation of \ref UpdatePhase.
  1545. Layout elements that have child elements should call the \ref update method of their child
  1546. elements, and pass the current \a phase unchanged.
  1547. The default implementation executes the automatic margin mechanism in the \ref upMargins phase.
  1548. Subclasses should make sure to call the base class implementation.
  1549. */
  1550. void QCPLayoutElement::update(UpdatePhase phase)
  1551. {
  1552. if (phase == upMargins) {
  1553. if (mAutoMargins != QCP::msNone) {
  1554. // set the margins of this layout element according to automatic margin calculation,
  1555. // either directly or via a margin group:
  1556. QMargins newMargins = mMargins;
  1557. QList<QCP::MarginSide> allMarginSides = QList<QCP::MarginSide>()
  1558. << QCP::msLeft << QCP::msRight << QCP::msTop
  1559. << QCP::msBottom;
  1560. foreach (QCP::MarginSide side, allMarginSides) {
  1561. if (mAutoMargins.testFlag(
  1562. side)) // this side's margin shall be calculated automatically
  1563. {
  1564. if (mMarginGroups.contains(side))
  1565. QCP::setMarginValue(newMargins, side,
  1566. mMarginGroups[side]->commonMargin(
  1567. side)); // this side is part of a margin group, so
  1568. // get the margin value from that group
  1569. else
  1570. QCP::setMarginValue(
  1571. newMargins, side,
  1572. calculateAutoMargin(side)); // this side is not part of a group, so
  1573. // calculate the value directly
  1574. // apply minimum margin restrictions:
  1575. if (QCP::getMarginValue(newMargins, side)
  1576. < QCP::getMarginValue(mMinimumMargins, side))
  1577. QCP::setMarginValue(newMargins, side,
  1578. QCP::getMarginValue(mMinimumMargins, side));
  1579. }
  1580. }
  1581. setMargins(newMargins);
  1582. }
  1583. }
  1584. }
  1585. /*!
  1586. Returns the minimum size this layout element (the inner \ref rect) may be compressed to.
  1587. if a minimum size (\ref setMinimumSize) was not set manually, parent layouts consult this
  1588. function to determine the minimum allowed size of this layout element. (A manual minimum size is
  1589. considered set if it is non-zero.)
  1590. */
  1591. QSize QCPLayoutElement::minimumSizeHint() const
  1592. {
  1593. return mMinimumSize;
  1594. }
  1595. /*!
  1596. Returns the maximum size this layout element (the inner \ref rect) may be expanded to.
  1597. if a maximum size (\ref setMaximumSize) was not set manually, parent layouts consult this
  1598. function to determine the maximum allowed size of this layout element. (A manual maximum size is
  1599. considered set if it is smaller than Qt's QWIDGETSIZE_MAX.)
  1600. */
  1601. QSize QCPLayoutElement::maximumSizeHint() const
  1602. {
  1603. return mMaximumSize;
  1604. }
  1605. /*!
  1606. Returns a list of all child elements in this layout element. If \a recursive is true, all
  1607. sub-child elements are included in the list, too.
  1608. \warning There may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may
  1609. have empty cells which yield 0 at the respective index.)
  1610. */
  1611. QList<QCPLayoutElement*> QCPLayoutElement::elements(bool recursive) const
  1612. {
  1613. Q_UNUSED(recursive)
  1614. return QList<QCPLayoutElement*>();
  1615. }
  1616. /*!
  1617. Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer
  1618. rect, this method returns a value corresponding to 0.99 times the parent plot's selection
  1619. tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is
  1620. true, -1.0 is returned.
  1621. See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
  1622. QCPLayoutElement subclasses may reimplement this method to provide more specific selection test
  1623. behaviour.
  1624. */
  1625. double QCPLayoutElement::selectTest(const QPointF& pos, bool onlySelectable,
  1626. QVariant* details) const
  1627. {
  1628. Q_UNUSED(details)
  1629. if (onlySelectable)
  1630. return -1;
  1631. if (QRectF(mOuterRect).contains(pos)) {
  1632. if (mParentPlot)
  1633. return mParentPlot->selectionTolerance() * 0.99;
  1634. else {
  1635. qDebug() << Q_FUNC_INFO << "parent plot not defined";
  1636. return -1;
  1637. }
  1638. } else
  1639. return -1;
  1640. }
  1641. /*! \internal
  1642. propagates the parent plot initialization to all child elements, by calling \ref
  1643. QCPLayerable::initializeParentPlot on them.
  1644. */
  1645. void QCPLayoutElement::parentPlotInitialized(QCustomPlot* parentPlot)
  1646. {
  1647. foreach (QCPLayoutElement* el, elements(false)) {
  1648. if (!el->parentPlot())
  1649. el->initializeParentPlot(parentPlot);
  1650. }
  1651. }
  1652. /*! \internal
  1653. Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a
  1654. side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the
  1655. returned value will not be smaller than the specified minimum margin.
  1656. The default implementation just returns the respective manual margin (\ref setMargins) or the
  1657. minimum margin, whichever is larger.
  1658. */
  1659. int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side)
  1660. {
  1661. return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side));
  1662. }
  1663. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1664. //////////////////// QCPLayout
  1665. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1666. /*! \class QCPLayout
  1667. \brief The abstract base class for layouts
  1668. This is an abstract base class for layout elements whose main purpose is to define the position
  1669. and size of other child layout elements. In most cases, layouts don't draw anything themselves
  1670. (but there are exceptions to this, e.g. QCPLegend).
  1671. QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts.
  1672. QCPLayout introduces a common interface for accessing and manipulating the child elements. Those
  1673. functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref
  1674. simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions
  1675. to this interface which are more specialized to the form of the layout. For example, \ref
  1676. QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid
  1677. more conveniently.
  1678. Since this is an abstract base class, you can't instantiate it directly. Rather use one of its
  1679. subclasses like QCPLayoutGrid or QCPLayoutInset.
  1680. For a general introduction to the layout system, see the dedicated documentation page \ref
  1681. thelayoutsystem "The Layout System".
  1682. */
  1683. /* start documentation of pure virtual functions */
  1684. /*! \fn virtual int QCPLayout::elementCount() const = 0
  1685. Returns the number of elements/cells in the layout.
  1686. \see elements, elementAt
  1687. */
  1688. /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0
  1689. Returns the element in the cell with the given \a index. If \a index is invalid, returns 0.
  1690. Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g.
  1691. QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check
  1692. whether a cell is empty or not.
  1693. \see elements, elementCount, takeAt
  1694. */
  1695. /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0
  1696. Removes the element with the given \a index from the layout and returns it.
  1697. If the \a index is invalid or the cell with that index is empty, returns 0.
  1698. Note that some layouts don't remove the respective cell right away but leave an empty cell after
  1699. successful removal of the layout element. To collapse empty cells, use \ref simplify.
  1700. \see elementAt, take
  1701. */
  1702. /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0
  1703. Removes the specified \a element from the layout and returns true on success.
  1704. If the \a element isn't in this layout, returns false.
  1705. Note that some layouts don't remove the respective cell right away but leave an empty cell after
  1706. successful removal of the layout element. To collapse empty cells, use \ref simplify.
  1707. \see takeAt
  1708. */
  1709. /* end documentation of pure virtual functions */
  1710. /*!
  1711. Creates an instance of QCPLayout and sets default values. Note that since QCPLayout
  1712. is an abstract base class, it can't be instantiated directly.
  1713. */
  1714. QCPLayout::QCPLayout()
  1715. {}
  1716. /*!
  1717. First calls the QCPLayoutElement::update base class implementation to update the margins on this
  1718. layout.
  1719. Then calls \ref updateLayout which subclasses reimplement to reposition and resize their cells.
  1720. Finally, \ref update is called on all child elements.
  1721. */
  1722. void QCPLayout::update(UpdatePhase phase)
  1723. {
  1724. QCPLayoutElement::update(phase);
  1725. // set child element rects according to layout:
  1726. if (phase == upLayout)
  1727. updateLayout();
  1728. // propagate update call to child elements:
  1729. const int elCount = elementCount();
  1730. for (int i = 0; i < elCount; ++i) {
  1731. if (QCPLayoutElement* el = elementAt(i))
  1732. el->update(phase);
  1733. }
  1734. }
  1735. /* inherits documentation from base class */
  1736. QList<QCPLayoutElement*> QCPLayout::elements(bool recursive) const
  1737. {
  1738. const int c = elementCount();
  1739. QList<QCPLayoutElement*> result;
  1740. #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
  1741. result.reserve(c);
  1742. #endif
  1743. for (int i = 0; i < c; ++i)
  1744. result.append(elementAt(i));
  1745. if (recursive) {
  1746. for (int i = 0; i < c; ++i) {
  1747. if (result.at(i))
  1748. result << result.at(i)->elements(recursive);
  1749. }
  1750. }
  1751. return result;
  1752. }
  1753. /*!
  1754. Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the
  1755. default implementation does nothing.
  1756. Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit
  1757. simplification while QCPLayoutGrid does.
  1758. */
  1759. void QCPLayout::simplify()
  1760. {}
  1761. /*!
  1762. Removes and deletes the element at the provided \a index. Returns true on success. If \a index is
  1763. invalid or points to an empty cell, returns false.
  1764. This function internally uses \ref takeAt to remove the element from the layout and then deletes
  1765. the returned element. Note that some layouts don't remove the respective cell right away but leave
  1766. an empty cell after successful removal of the layout element. To collapse empty cells, use \ref
  1767. simplify.
  1768. \see remove, takeAt
  1769. */
  1770. bool QCPLayout::removeAt(int index)
  1771. {
  1772. if (QCPLayoutElement* el = takeAt(index)) {
  1773. delete el;
  1774. return true;
  1775. } else
  1776. return false;
  1777. }
  1778. /*!
  1779. Removes and deletes the provided \a element. Returns true on success. If \a element is not in the
  1780. layout, returns false.
  1781. This function internally uses \ref takeAt to remove the element from the layout and then deletes
  1782. the element. Note that some layouts don't remove the respective cell right away but leave an
  1783. empty cell after successful removal of the layout element. To collapse empty cells, use \ref
  1784. simplify.
  1785. \see removeAt, take
  1786. */
  1787. bool QCPLayout::remove(QCPLayoutElement* element)
  1788. {
  1789. if (take(element)) {
  1790. delete element;
  1791. return true;
  1792. } else
  1793. return false;
  1794. }
  1795. /*!
  1796. Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure
  1797. all empty cells are collapsed.
  1798. \see remove, removeAt
  1799. */
  1800. void QCPLayout::clear()
  1801. {
  1802. for (int i = elementCount() - 1; i >= 0; --i) {
  1803. if (elementAt(i))
  1804. removeAt(i);
  1805. }
  1806. simplify();
  1807. }
  1808. /*!
  1809. Subclasses call this method to report changed (minimum/maximum) size constraints.
  1810. If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref
  1811. sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of
  1812. QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout,
  1813. it may update itself and resize cells accordingly.
  1814. */
  1815. void QCPLayout::sizeConstraintsChanged() const
  1816. {
  1817. if (QWidget* w = qobject_cast<QWidget*>(parent()))
  1818. w->updateGeometry();
  1819. else if (QCPLayout* l = qobject_cast<QCPLayout*>(parent()))
  1820. l->sizeConstraintsChanged();
  1821. }
  1822. /*! \internal
  1823. Subclasses reimplement this method to update the position and sizes of the child elements/cells
  1824. via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing.
  1825. The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay
  1826. within that rect.
  1827. \ref getSectionSizes may help with the reimplementation of this function.
  1828. \see update
  1829. */
  1830. void QCPLayout::updateLayout()
  1831. {}
  1832. /*! \internal
  1833. Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the
  1834. \ref QCPLayerable::parentLayerable and the QObject parent to this layout.
  1835. Further, if \a el didn't previously have a parent plot, calls \ref
  1836. QCPLayerable::initializeParentPlot on \a el to set the paret plot.
  1837. This method is used by subclass specific methods that add elements to the layout. Note that this
  1838. method only changes properties in \a el. The removal from the old layout and the insertion into
  1839. the new layout must be done additionally.
  1840. */
  1841. void QCPLayout::adoptElement(QCPLayoutElement* el)
  1842. {
  1843. if (el) {
  1844. el->mParentLayout = this;
  1845. el->setParentLayerable(this);
  1846. el->setParent(this);
  1847. if (!el->parentPlot())
  1848. el->initializeParentPlot(mParentPlot);
  1849. } else
  1850. qDebug() << Q_FUNC_INFO << "Null element passed";
  1851. }
  1852. /*! \internal
  1853. Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout
  1854. and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent
  1855. QCustomPlot.
  1856. This method is used by subclass specific methods that remove elements from the layout (e.g. \ref
  1857. take or \ref takeAt). Note that this method only changes properties in \a el. The removal from
  1858. the old layout must be done additionally.
  1859. */
  1860. void QCPLayout::releaseElement(QCPLayoutElement* el)
  1861. {
  1862. if (el) {
  1863. el->mParentLayout = 0;
  1864. el->setParentLayerable(0);
  1865. el->setParent(mParentPlot);
  1866. // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent
  1867. // plot
  1868. } else
  1869. qDebug() << Q_FUNC_INFO << "Null element passed";
  1870. }
  1871. /*! \internal
  1872. This is a helper function for the implementation of \ref updateLayout in subclasses.
  1873. It calculates the sizes of one-dimensional sections with provided constraints on maximum section
  1874. sizes, minimum section sizes, relative stretch factors and the final total size of all sections.
  1875. The QVector entries refer to the sections. Thus all QVectors must have the same size.
  1876. \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size
  1877. imposed, set all vector values to Qt's QWIDGETSIZE_MAX.
  1878. \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size
  1879. imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than
  1880. \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words,
  1881. not exceeding the allowed total size is taken to be more important than not going below minimum
  1882. section sizes.)
  1883. \a stretchFactors give the relative proportions of the sections to each other. If all sections
  1884. shall be scaled equally, set all values equal. If the first section shall be double the size of
  1885. each individual other section, set the first number of \a stretchFactors to double the value of
  1886. the other individual values (e.g. {2, 1, 1, 1}).
  1887. \a totalSize is the value that the final section sizes will add up to. Due to rounding, the
  1888. actual sum may differ slightly. If you want the section sizes to sum up to exactly that value,
  1889. you could distribute the remaining difference on the sections.
  1890. The return value is a QVector containing the section sizes.
  1891. */
  1892. QVector<int> QCPLayout::getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes,
  1893. QVector<double> stretchFactors, int totalSize) const
  1894. {
  1895. if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size()) {
  1896. qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes
  1897. << stretchFactors;
  1898. return QVector<int>();
  1899. }
  1900. if (stretchFactors.isEmpty())
  1901. return QVector<int>();
  1902. int sectionCount = stretchFactors.size();
  1903. QVector<double> sectionSizes(sectionCount);
  1904. // if provided total size is forced smaller than total minimum size, ignore minimum sizes
  1905. // (squeeze sections):
  1906. int minSizeSum = 0;
  1907. for (int i = 0; i < sectionCount; ++i)
  1908. minSizeSum += minSizes.at(i);
  1909. if (totalSize < minSizeSum) {
  1910. // new stretch factors are minimum sizes and minimum sizes are set to zero:
  1911. for (int i = 0; i < sectionCount; ++i) {
  1912. stretchFactors[i] = minSizes.at(i);
  1913. minSizes[i] = 0;
  1914. }
  1915. }
  1916. QList<int> minimumLockedSections;
  1917. QList<int> unfinishedSections;
  1918. for (int i = 0; i < sectionCount; ++i)
  1919. unfinishedSections.append(i);
  1920. double freeSize = totalSize;
  1921. int outerIterations = 0;
  1922. while (!unfinishedSections.isEmpty()
  1923. && outerIterations < sectionCount * 2) // the iteration check ist just a failsafe in case
  1924. // something really strange happens
  1925. {
  1926. ++outerIterations;
  1927. int innerIterations = 0;
  1928. while (!unfinishedSections.isEmpty()
  1929. && innerIterations < sectionCount * 2) // the iteration check ist just a failsafe in
  1930. // case something really strange happens
  1931. {
  1932. ++innerIterations;
  1933. // find section that hits its maximum next:
  1934. int nextId = -1;
  1935. double nextMax = 1e12;
  1936. for (int i = 0; i < unfinishedSections.size(); ++i) {
  1937. int secId = unfinishedSections.at(i);
  1938. double hitsMaxAt =
  1939. (maxSizes.at(secId) - sectionSizes.at(secId)) / stretchFactors.at(secId);
  1940. if (hitsMaxAt < nextMax) {
  1941. nextMax = hitsMaxAt;
  1942. nextId = secId;
  1943. }
  1944. }
  1945. // check if that maximum is actually within the bounds of the total size (i.e. can we
  1946. // stretch all remaining sections so far that the found section actually hits its
  1947. // maximum, without exceeding the total size when we add up all sections)
  1948. double stretchFactorSum = 0;
  1949. for (int i = 0; i < unfinishedSections.size(); ++i)
  1950. stretchFactorSum += stretchFactors.at(unfinishedSections.at(i));
  1951. double nextMaxLimit = freeSize / stretchFactorSum;
  1952. if (nextMax < nextMaxLimit) // next maximum is actually hit, move forward to that point
  1953. // and fix the size of that section
  1954. {
  1955. for (int i = 0; i < unfinishedSections.size(); ++i) {
  1956. sectionSizes[unfinishedSections.at(i)] +=
  1957. nextMax
  1958. * stretchFactors.at(unfinishedSections.at(i)); // increment all sections
  1959. freeSize -= nextMax * stretchFactors.at(unfinishedSections.at(i));
  1960. }
  1961. unfinishedSections.removeOne(
  1962. nextId); // exclude the section that is now at maximum from further changes
  1963. } else // next maximum isn't hit, just distribute rest of free space on remaining
  1964. // sections
  1965. {
  1966. for (int i = 0; i < unfinishedSections.size(); ++i)
  1967. sectionSizes[unfinishedSections.at(i)] +=
  1968. nextMaxLimit
  1969. * stretchFactors.at(unfinishedSections.at(i)); // increment all sections
  1970. unfinishedSections.clear();
  1971. }
  1972. }
  1973. if (innerIterations == sectionCount * 2)
  1974. qDebug()
  1975. << Q_FUNC_INFO
  1976. << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:"
  1977. << maxSizes << minSizes << stretchFactors << totalSize;
  1978. // now check whether the resulting section sizes violate minimum restrictions:
  1979. bool foundMinimumViolation = false;
  1980. for (int i = 0; i < sectionSizes.size(); ++i) {
  1981. if (minimumLockedSections.contains(i))
  1982. continue;
  1983. if (sectionSizes.at(i) < minSizes.at(i)) // section violates minimum
  1984. {
  1985. sectionSizes[i] = minSizes.at(i); // set it to minimum
  1986. foundMinimumViolation = true; // make sure we repeat the whole optimization process
  1987. minimumLockedSections.append(i);
  1988. }
  1989. }
  1990. if (foundMinimumViolation) {
  1991. freeSize = totalSize;
  1992. for (int i = 0; i < sectionCount; ++i) {
  1993. if (!minimumLockedSections.contains(
  1994. i)) // only put sections that haven't hit their minimum back into the pool
  1995. unfinishedSections.append(i);
  1996. else
  1997. freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from
  1998. // available space in next round
  1999. }
  2000. // reset all section sizes to zero that are in unfinished sections (all others have been
  2001. // set to their minimum):
  2002. for (int i = 0; i < unfinishedSections.size(); ++i)
  2003. sectionSizes[unfinishedSections.at(i)] = 0;
  2004. }
  2005. }
  2006. if (outerIterations == sectionCount * 2)
  2007. qDebug() << Q_FUNC_INFO
  2008. << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:"
  2009. << maxSizes << minSizes << stretchFactors << totalSize;
  2010. QVector<int> result(sectionCount);
  2011. for (int i = 0; i < sectionCount; ++i)
  2012. result[i] = qRound(sectionSizes.at(i));
  2013. return result;
  2014. }
  2015. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2016. //////////////////// QCPLayoutGrid
  2017. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2018. /*! \class QCPLayoutGrid
  2019. \brief A layout that arranges child elements in a grid
  2020. Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor,
  2021. \ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing).
  2022. Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or
  2023. column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref
  2024. hasElement, that element can be retrieved with \ref element. If rows and columns that only have
  2025. empty cells shall be removed, call \ref simplify. Removal of elements is either done by just
  2026. adding the element to a different layout or by using the QCPLayout interface \ref take or \ref
  2027. remove.
  2028. Row and column insertion can be performed with \ref insertRow and \ref insertColumn.
  2029. */
  2030. /*!
  2031. Creates an instance of QCPLayoutGrid and sets default values.
  2032. */
  2033. QCPLayoutGrid::QCPLayoutGrid() : mColumnSpacing(5), mRowSpacing(5)
  2034. {}
  2035. QCPLayoutGrid::~QCPLayoutGrid()
  2036. {
  2037. // clear all child layout elements. This is important because only the specific layouts know how
  2038. // to handle removing elements (clear calls virtual removeAt method to do that).
  2039. clear();
  2040. }
  2041. /*!
  2042. Returns the element in the cell in \a row and \a column.
  2043. Returns 0 if either the row/column is invalid or if the cell is empty. In those cases, a qDebug
  2044. message is printed. To check whether a cell exists and isn't empty, use \ref hasElement.
  2045. \see addElement, hasElement
  2046. */
  2047. QCPLayoutElement* QCPLayoutGrid::element(int row, int column) const
  2048. {
  2049. if (row >= 0 && row < mElements.size()) {
  2050. if (column >= 0 && column < mElements.first().size()) {
  2051. if (QCPLayoutElement* result = mElements.at(row).at(column))
  2052. return result;
  2053. else
  2054. qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row
  2055. << "Column:" << column;
  2056. } else
  2057. qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column;
  2058. } else
  2059. qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column;
  2060. return 0;
  2061. }
  2062. /*!
  2063. Returns the number of rows in the layout.
  2064. \see columnCount
  2065. */
  2066. int QCPLayoutGrid::rowCount() const
  2067. {
  2068. return mElements.size();
  2069. }
  2070. /*!
  2071. Returns the number of columns in the layout.
  2072. \see rowCount
  2073. */
  2074. int QCPLayoutGrid::columnCount() const
  2075. {
  2076. if (mElements.size() > 0)
  2077. return mElements.first().size();
  2078. else
  2079. return 0;
  2080. }
  2081. /*!
  2082. Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it
  2083. is first removed from there. If \a row or \a column don't exist yet, the layout is expanded
  2084. accordingly.
  2085. Returns true if the element was added successfully, i.e. if the cell at \a row and \a column
  2086. didn't already have an element.
  2087. \see element, hasElement, take, remove
  2088. */
  2089. bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement* element)
  2090. {
  2091. if (element) {
  2092. if (!hasElement(row, column)) {
  2093. if (element->layout()) // remove from old layout first
  2094. element->layout()->take(element);
  2095. expandTo(row + 1, column + 1);
  2096. mElements[row][column] = element;
  2097. adoptElement(element);
  2098. return true;
  2099. } else
  2100. qDebug() << Q_FUNC_INFO
  2101. << "There is already an element in the specified row/column:" << row << column;
  2102. } else
  2103. qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column;
  2104. return false;
  2105. }
  2106. /*!
  2107. Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't
  2108. empty.
  2109. \see element
  2110. */
  2111. bool QCPLayoutGrid::hasElement(int row, int column)
  2112. {
  2113. if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount())
  2114. return mElements.at(row).at(column);
  2115. else
  2116. return false;
  2117. }
  2118. /*!
  2119. Sets the stretch \a factor of \a column.
  2120. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  2121. their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
  2122. QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
  2123. The default stretch factor of newly created rows/columns is 1.
  2124. \see setColumnStretchFactors, setRowStretchFactor
  2125. */
  2126. void QCPLayoutGrid::setColumnStretchFactor(int column, double factor)
  2127. {
  2128. if (column >= 0 && column < columnCount()) {
  2129. if (factor > 0)
  2130. mColumnStretchFactors[column] = factor;
  2131. else
  2132. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
  2133. } else
  2134. qDebug() << Q_FUNC_INFO << "Invalid column:" << column;
  2135. }
  2136. /*!
  2137. Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount.
  2138. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  2139. their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
  2140. QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
  2141. The default stretch factor of newly created rows/columns is 1.
  2142. \see setColumnStretchFactor, setRowStretchFactors
  2143. */
  2144. void QCPLayoutGrid::setColumnStretchFactors(const QList<double>& factors)
  2145. {
  2146. if (factors.size() == mColumnStretchFactors.size()) {
  2147. mColumnStretchFactors = factors;
  2148. for (int i = 0; i < mColumnStretchFactors.size(); ++i) {
  2149. if (mColumnStretchFactors.at(i) <= 0) {
  2150. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:"
  2151. << mColumnStretchFactors.at(i);
  2152. mColumnStretchFactors[i] = 1;
  2153. }
  2154. }
  2155. } else
  2156. qDebug() << Q_FUNC_INFO
  2157. << "Column count not equal to passed stretch factor count:" << factors;
  2158. }
  2159. /*!
  2160. Sets the stretch \a factor of \a row.
  2161. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  2162. their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
  2163. QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
  2164. The default stretch factor of newly created rows/columns is 1.
  2165. \see setColumnStretchFactors, setRowStretchFactor
  2166. */
  2167. void QCPLayoutGrid::setRowStretchFactor(int row, double factor)
  2168. {
  2169. if (row >= 0 && row < rowCount()) {
  2170. if (factor > 0)
  2171. mRowStretchFactors[row] = factor;
  2172. else
  2173. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
  2174. } else
  2175. qDebug() << Q_FUNC_INFO << "Invalid row:" << row;
  2176. }
  2177. /*!
  2178. Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount.
  2179. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  2180. their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref
  2181. QCPLayoutElement::setMaximumSize), regardless of the stretch factor.
  2182. The default stretch factor of newly created rows/columns is 1.
  2183. \see setRowStretchFactor, setColumnStretchFactors
  2184. */
  2185. void QCPLayoutGrid::setRowStretchFactors(const QList<double>& factors)
  2186. {
  2187. if (factors.size() == mRowStretchFactors.size()) {
  2188. mRowStretchFactors = factors;
  2189. for (int i = 0; i < mRowStretchFactors.size(); ++i) {
  2190. if (mRowStretchFactors.at(i) <= 0) {
  2191. qDebug() << Q_FUNC_INFO
  2192. << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at(i);
  2193. mRowStretchFactors[i] = 1;
  2194. }
  2195. }
  2196. } else
  2197. qDebug() << Q_FUNC_INFO << "Row count not equal to passed stretch factor count:" << factors;
  2198. }
  2199. /*!
  2200. Sets the gap that is left blank between columns to \a pixels.
  2201. \see setRowSpacing
  2202. */
  2203. void QCPLayoutGrid::setColumnSpacing(int pixels)
  2204. {
  2205. mColumnSpacing = pixels;
  2206. }
  2207. /*!
  2208. Sets the gap that is left blank between rows to \a pixels.
  2209. \see setColumnSpacing
  2210. */
  2211. void QCPLayoutGrid::setRowSpacing(int pixels)
  2212. {
  2213. mRowSpacing = pixels;
  2214. }
  2215. /*!
  2216. Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid
  2217. row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1.
  2218. If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount,
  2219. this function does nothing in that dimension.
  2220. Newly created cells are empty, new rows and columns have the stretch factor 1.
  2221. Note that upon a call to \ref addElement, the layout is expanded automatically to contain the
  2222. specified row and column, using this function.
  2223. \see simplify
  2224. */
  2225. void QCPLayoutGrid::expandTo(int newRowCount, int newColumnCount)
  2226. {
  2227. // add rows as necessary:
  2228. while (rowCount() < newRowCount) {
  2229. mElements.append(QList<QCPLayoutElement*>());
  2230. mRowStretchFactors.append(1);
  2231. }
  2232. // go through rows and expand columns as necessary:
  2233. int newColCount = qMax(columnCount(), newColumnCount);
  2234. for (int i = 0; i < rowCount(); ++i) {
  2235. while (mElements.at(i).size() < newColCount)
  2236. mElements[i].append(0);
  2237. }
  2238. while (mColumnStretchFactors.size() < newColCount)
  2239. mColumnStretchFactors.append(1);
  2240. }
  2241. /*!
  2242. Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex
  2243. range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom).
  2244. \see insertColumn
  2245. */
  2246. void QCPLayoutGrid::insertRow(int newIndex)
  2247. {
  2248. if (mElements.isEmpty()
  2249. || mElements.first().isEmpty()) // if grid is completely empty, add first cell
  2250. {
  2251. expandTo(1, 1);
  2252. return;
  2253. }
  2254. if (newIndex < 0)
  2255. newIndex = 0;
  2256. if (newIndex > rowCount())
  2257. newIndex = rowCount();
  2258. mRowStretchFactors.insert(newIndex, 1);
  2259. QList<QCPLayoutElement*> newRow;
  2260. for (int col = 0; col < columnCount(); ++col)
  2261. newRow.append((QCPLayoutElement*)0);
  2262. mElements.insert(newIndex, newRow);
  2263. }
  2264. /*!
  2265. Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a
  2266. newIndex range from 0 (inserts a row at the left) to \a rowCount (appends a row at the right).
  2267. \see insertRow
  2268. */
  2269. void QCPLayoutGrid::insertColumn(int newIndex)
  2270. {
  2271. if (mElements.isEmpty()
  2272. || mElements.first().isEmpty()) // if grid is completely empty, add first cell
  2273. {
  2274. expandTo(1, 1);
  2275. return;
  2276. }
  2277. if (newIndex < 0)
  2278. newIndex = 0;
  2279. if (newIndex > columnCount())
  2280. newIndex = columnCount();
  2281. mColumnStretchFactors.insert(newIndex, 1);
  2282. for (int row = 0; row < rowCount(); ++row)
  2283. mElements[row].insert(newIndex, (QCPLayoutElement*)0);
  2284. }
  2285. /* inherits documentation from base class */
  2286. void QCPLayoutGrid::updateLayout()
  2287. {
  2288. QVector<int> minColWidths, minRowHeights, maxColWidths, maxRowHeights;
  2289. getMinimumRowColSizes(&minColWidths, &minRowHeights);
  2290. getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
  2291. int totalRowSpacing = (rowCount() - 1) * mRowSpacing;
  2292. int totalColSpacing = (columnCount() - 1) * mColumnSpacing;
  2293. QVector<int> colWidths =
  2294. getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(),
  2295. mRect.width() - totalColSpacing);
  2296. QVector<int> rowHeights =
  2297. getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(),
  2298. mRect.height() - totalRowSpacing);
  2299. // go through cells and set rects accordingly:
  2300. int yOffset = mRect.top();
  2301. for (int row = 0; row < rowCount(); ++row) {
  2302. if (row > 0)
  2303. yOffset += rowHeights.at(row - 1) + mRowSpacing;
  2304. int xOffset = mRect.left();
  2305. for (int col = 0; col < columnCount(); ++col) {
  2306. if (col > 0)
  2307. xOffset += colWidths.at(col - 1) + mColumnSpacing;
  2308. if (mElements.at(row).at(col))
  2309. mElements.at(row).at(col)->setOuterRect(
  2310. QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row)));
  2311. }
  2312. }
  2313. }
  2314. /* inherits documentation from base class */
  2315. int QCPLayoutGrid::elementCount() const
  2316. {
  2317. return rowCount() * columnCount();
  2318. }
  2319. /* inherits documentation from base class */
  2320. QCPLayoutElement* QCPLayoutGrid::elementAt(int index) const
  2321. {
  2322. if (index >= 0 && index < elementCount())
  2323. return mElements.at(index / columnCount()).at(index % columnCount());
  2324. else
  2325. return 0;
  2326. }
  2327. /* inherits documentation from base class */
  2328. QCPLayoutElement* QCPLayoutGrid::takeAt(int index)
  2329. {
  2330. if (QCPLayoutElement* el = elementAt(index)) {
  2331. releaseElement(el);
  2332. mElements[index / columnCount()][index % columnCount()] = 0;
  2333. return el;
  2334. } else {
  2335. qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
  2336. return 0;
  2337. }
  2338. }
  2339. /* inherits documentation from base class */
  2340. bool QCPLayoutGrid::take(QCPLayoutElement* element)
  2341. {
  2342. if (element) {
  2343. for (int i = 0; i < elementCount(); ++i) {
  2344. if (elementAt(i) == element) {
  2345. takeAt(i);
  2346. return true;
  2347. }
  2348. }
  2349. qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
  2350. } else
  2351. qDebug() << Q_FUNC_INFO << "Can't take null element";
  2352. return false;
  2353. }
  2354. /* inherits documentation from base class */
  2355. QList<QCPLayoutElement*> QCPLayoutGrid::elements(bool recursive) const
  2356. {
  2357. QList<QCPLayoutElement*> result;
  2358. int colC = columnCount();
  2359. int rowC = rowCount();
  2360. #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
  2361. result.reserve(colC * rowC);
  2362. #endif
  2363. for (int row = 0; row < rowC; ++row) {
  2364. for (int col = 0; col < colC; ++col) {
  2365. result.append(mElements.at(row).at(col));
  2366. }
  2367. }
  2368. if (recursive) {
  2369. int c = result.size();
  2370. for (int i = 0; i < c; ++i) {
  2371. if (result.at(i))
  2372. result << result.at(i)->elements(recursive);
  2373. }
  2374. }
  2375. return result;
  2376. }
  2377. /*!
  2378. Simplifies the layout by collapsing rows and columns which only contain empty cells.
  2379. */
  2380. void QCPLayoutGrid::simplify()
  2381. {
  2382. // remove rows with only empty cells:
  2383. for (int row = rowCount() - 1; row >= 0; --row) {
  2384. bool hasElements = false;
  2385. for (int col = 0; col < columnCount(); ++col) {
  2386. if (mElements.at(row).at(col)) {
  2387. hasElements = true;
  2388. break;
  2389. }
  2390. }
  2391. if (!hasElements) {
  2392. mRowStretchFactors.removeAt(row);
  2393. mElements.removeAt(row);
  2394. if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't
  2395. // happen below because also columnCount changed to 0 now)
  2396. mColumnStretchFactors.clear();
  2397. }
  2398. }
  2399. // remove columns with only empty cells:
  2400. for (int col = columnCount() - 1; col >= 0; --col) {
  2401. bool hasElements = false;
  2402. for (int row = 0; row < rowCount(); ++row) {
  2403. if (mElements.at(row).at(col)) {
  2404. hasElements = true;
  2405. break;
  2406. }
  2407. }
  2408. if (!hasElements) {
  2409. mColumnStretchFactors.removeAt(col);
  2410. for (int row = 0; row < rowCount(); ++row)
  2411. mElements[row].removeAt(col);
  2412. }
  2413. }
  2414. }
  2415. /* inherits documentation from base class */
  2416. QSize QCPLayoutGrid::minimumSizeHint() const
  2417. {
  2418. QVector<int> minColWidths, minRowHeights;
  2419. getMinimumRowColSizes(&minColWidths, &minRowHeights);
  2420. QSize result(0, 0);
  2421. for (int i = 0; i < minColWidths.size(); ++i)
  2422. result.rwidth() += minColWidths.at(i);
  2423. for (int i = 0; i < minRowHeights.size(); ++i)
  2424. result.rheight() += minRowHeights.at(i);
  2425. result.rwidth() +=
  2426. qMax(0, columnCount() - 1) * mColumnSpacing + mMargins.left() + mMargins.right();
  2427. result.rheight() += qMax(0, rowCount() - 1) * mRowSpacing + mMargins.top() + mMargins.bottom();
  2428. return result;
  2429. }
  2430. /* inherits documentation from base class */
  2431. QSize QCPLayoutGrid::maximumSizeHint() const
  2432. {
  2433. QVector<int> maxColWidths, maxRowHeights;
  2434. getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
  2435. QSize result(0, 0);
  2436. for (int i = 0; i < maxColWidths.size(); ++i)
  2437. result.setWidth(qMin(result.width() + maxColWidths.at(i), QWIDGETSIZE_MAX));
  2438. for (int i = 0; i < maxRowHeights.size(); ++i)
  2439. result.setHeight(qMin(result.height() + maxRowHeights.at(i), QWIDGETSIZE_MAX));
  2440. result.rwidth() +=
  2441. qMax(0, columnCount() - 1) * mColumnSpacing + mMargins.left() + mMargins.right();
  2442. result.rheight() += qMax(0, rowCount() - 1) * mRowSpacing + mMargins.top() + mMargins.bottom();
  2443. return result;
  2444. }
  2445. /*! \internal
  2446. Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights
  2447. respectively.
  2448. The minimum height of a row is the largest minimum height of any element in that row. The minimum
  2449. width of a column is the largest minimum width of any element in that column.
  2450. This is a helper function for \ref updateLayout.
  2451. \see getMaximumRowColSizes
  2452. */
  2453. void QCPLayoutGrid::getMinimumRowColSizes(QVector<int>* minColWidths,
  2454. QVector<int>* minRowHeights) const
  2455. {
  2456. *minColWidths = QVector<int>(columnCount(), 0);
  2457. *minRowHeights = QVector<int>(rowCount(), 0);
  2458. for (int row = 0; row < rowCount(); ++row) {
  2459. for (int col = 0; col < columnCount(); ++col) {
  2460. if (mElements.at(row).at(col)) {
  2461. QSize minHint = mElements.at(row).at(col)->minimumSizeHint();
  2462. QSize min = mElements.at(row).at(col)->minimumSize();
  2463. QSize final(min.width() > 0 ? min.width() : minHint.width(),
  2464. min.height() > 0 ? min.height() : minHint.height());
  2465. if (minColWidths->at(col) < final.width())
  2466. (*minColWidths)[col] = final.width();
  2467. if (minRowHeights->at(row) < final.height())
  2468. (*minRowHeights)[row] = final.height();
  2469. }
  2470. }
  2471. }
  2472. }
  2473. /*! \internal
  2474. Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights
  2475. respectively.
  2476. The maximum height of a row is the smallest maximum height of any element in that row. The
  2477. maximum width of a column is the smallest maximum width of any element in that column.
  2478. This is a helper function for \ref updateLayout.
  2479. \see getMinimumRowColSizes
  2480. */
  2481. void QCPLayoutGrid::getMaximumRowColSizes(QVector<int>* maxColWidths,
  2482. QVector<int>* maxRowHeights) const
  2483. {
  2484. *maxColWidths = QVector<int>(columnCount(), QWIDGETSIZE_MAX);
  2485. *maxRowHeights = QVector<int>(rowCount(), QWIDGETSIZE_MAX);
  2486. for (int row = 0; row < rowCount(); ++row) {
  2487. for (int col = 0; col < columnCount(); ++col) {
  2488. if (mElements.at(row).at(col)) {
  2489. QSize maxHint = mElements.at(row).at(col)->maximumSizeHint();
  2490. QSize max = mElements.at(row).at(col)->maximumSize();
  2491. QSize final(max.width() < QWIDGETSIZE_MAX ? max.width() : maxHint.width(),
  2492. max.height() < QWIDGETSIZE_MAX ? max.height() : maxHint.height());
  2493. if (maxColWidths->at(col) > final.width())
  2494. (*maxColWidths)[col] = final.width();
  2495. if (maxRowHeights->at(row) > final.height())
  2496. (*maxRowHeights)[row] = final.height();
  2497. }
  2498. }
  2499. }
  2500. }
  2501. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2502. //////////////////// QCPLayoutInset
  2503. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2504. /*! \class QCPLayoutInset
  2505. \brief A layout that places child elements aligned to the border or arbitrarily positioned
  2506. Elements are placed either aligned to the border or at arbitrary position in the area of the
  2507. layout. Which placement applies is controlled with the \ref InsetPlacement (\ref
  2508. setInsetPlacement).
  2509. Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or
  2510. addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset
  2511. placement will default to \ref ipBorderAligned and the element will be aligned according to the
  2512. \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at
  2513. arbitrary position and size, defined by \a rect.
  2514. The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively.
  2515. This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout.
  2516. */
  2517. /* start documentation of inline functions */
  2518. /*! \fn virtual void QCPLayoutInset::simplify()
  2519. The QCPInsetLayout does not need simplification since it can never have empty cells due to its
  2520. linear index structure. This method does nothing.
  2521. */
  2522. /* end documentation of inline functions */
  2523. /*!
  2524. Creates an instance of QCPLayoutInset and sets default values.
  2525. */
  2526. QCPLayoutInset::QCPLayoutInset()
  2527. {}
  2528. QCPLayoutInset::~QCPLayoutInset()
  2529. {
  2530. // clear all child layout elements. This is important because only the specific layouts know how
  2531. // to handle removing elements (clear calls virtual removeAt method to do that).
  2532. clear();
  2533. }
  2534. /*!
  2535. Returns the placement type of the element with the specified \a index.
  2536. */
  2537. QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const
  2538. {
  2539. if (elementAt(index))
  2540. return mInsetPlacement.at(index);
  2541. else {
  2542. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2543. return ipFree;
  2544. }
  2545. }
  2546. /*!
  2547. Returns the alignment of the element with the specified \a index. The alignment only has a
  2548. meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned.
  2549. */
  2550. Qt::Alignment QCPLayoutInset::insetAlignment(int index) const
  2551. {
  2552. if (elementAt(index))
  2553. return mInsetAlignment.at(index);
  2554. else {
  2555. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2556. return 0;
  2557. }
  2558. }
  2559. /*!
  2560. Returns the rect of the element with the specified \a index. The rect only has a
  2561. meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree.
  2562. */
  2563. QRectF QCPLayoutInset::insetRect(int index) const
  2564. {
  2565. if (elementAt(index))
  2566. return mInsetRect.at(index);
  2567. else {
  2568. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2569. return QRectF();
  2570. }
  2571. }
  2572. /*!
  2573. Sets the inset placement type of the element with the specified \a index to \a placement.
  2574. \see InsetPlacement
  2575. */
  2576. void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement)
  2577. {
  2578. if (elementAt(index))
  2579. mInsetPlacement[index] = placement;
  2580. else
  2581. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2582. }
  2583. /*!
  2584. If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function
  2585. is used to set the alignment of the element with the specified \a index to \a alignment.
  2586. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
  2587. Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
  2588. alignment flags will be ignored.
  2589. */
  2590. void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment)
  2591. {
  2592. if (elementAt(index))
  2593. mInsetAlignment[index] = alignment;
  2594. else
  2595. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2596. }
  2597. /*!
  2598. If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the
  2599. position and size of the element with the specified \a index to \a rect.
  2600. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
  2601. will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
  2602. corner of the layout, with 35% width and height of the parent layout.
  2603. Note that the minimum and maximum sizes of the embedded element (\ref
  2604. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced.
  2605. */
  2606. void QCPLayoutInset::setInsetRect(int index, const QRectF& rect)
  2607. {
  2608. if (elementAt(index))
  2609. mInsetRect[index] = rect;
  2610. else
  2611. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  2612. }
  2613. /* inherits documentation from base class */
  2614. void QCPLayoutInset::updateLayout()
  2615. {
  2616. for (int i = 0; i < mElements.size(); ++i) {
  2617. QRect insetRect;
  2618. QSize finalMinSize, finalMaxSize;
  2619. QSize minSizeHint = mElements.at(i)->minimumSizeHint();
  2620. QSize maxSizeHint = mElements.at(i)->maximumSizeHint();
  2621. finalMinSize.setWidth(mElements.at(i)->minimumSize().width() > 0
  2622. ? mElements.at(i)->minimumSize().width()
  2623. : minSizeHint.width());
  2624. finalMinSize.setHeight(mElements.at(i)->minimumSize().height() > 0
  2625. ? mElements.at(i)->minimumSize().height()
  2626. : minSizeHint.height());
  2627. finalMaxSize.setWidth(mElements.at(i)->maximumSize().width() < QWIDGETSIZE_MAX
  2628. ? mElements.at(i)->maximumSize().width()
  2629. : maxSizeHint.width());
  2630. finalMaxSize.setHeight(mElements.at(i)->maximumSize().height() < QWIDGETSIZE_MAX
  2631. ? mElements.at(i)->maximumSize().height()
  2632. : maxSizeHint.height());
  2633. if (mInsetPlacement.at(i) == ipFree) {
  2634. insetRect = QRect(rect().x() + rect().width() * mInsetRect.at(i).x(),
  2635. rect().y() + rect().height() * mInsetRect.at(i).y(),
  2636. rect().width() * mInsetRect.at(i).width(),
  2637. rect().height() * mInsetRect.at(i).height());
  2638. if (insetRect.size().width() < finalMinSize.width())
  2639. insetRect.setWidth(finalMinSize.width());
  2640. if (insetRect.size().height() < finalMinSize.height())
  2641. insetRect.setHeight(finalMinSize.height());
  2642. if (insetRect.size().width() > finalMaxSize.width())
  2643. insetRect.setWidth(finalMaxSize.width());
  2644. if (insetRect.size().height() > finalMaxSize.height())
  2645. insetRect.setHeight(finalMaxSize.height());
  2646. } else if (mInsetPlacement.at(i) == ipBorderAligned) {
  2647. insetRect.setSize(finalMinSize);
  2648. Qt::Alignment al = mInsetAlignment.at(i);
  2649. if (al.testFlag(Qt::AlignLeft))
  2650. insetRect.moveLeft(rect().x());
  2651. else if (al.testFlag(Qt::AlignRight))
  2652. insetRect.moveRight(rect().x() + rect().width());
  2653. else
  2654. insetRect.moveLeft(rect().x() + rect().width() * 0.5
  2655. - finalMinSize.width() * 0.5); // default to Qt::AlignHCenter
  2656. if (al.testFlag(Qt::AlignTop))
  2657. insetRect.moveTop(rect().y());
  2658. else if (al.testFlag(Qt::AlignBottom))
  2659. insetRect.moveBottom(rect().y() + rect().height());
  2660. else
  2661. insetRect.moveTop(rect().y() + rect().height() * 0.5
  2662. - finalMinSize.height() * 0.5); // default to Qt::AlignVCenter
  2663. }
  2664. mElements.at(i)->setOuterRect(insetRect);
  2665. }
  2666. }
  2667. /* inherits documentation from base class */
  2668. int QCPLayoutInset::elementCount() const
  2669. {
  2670. return mElements.size();
  2671. }
  2672. /* inherits documentation from base class */
  2673. QCPLayoutElement* QCPLayoutInset::elementAt(int index) const
  2674. {
  2675. if (index >= 0 && index < mElements.size())
  2676. return mElements.at(index);
  2677. else
  2678. return 0;
  2679. }
  2680. /* inherits documentation from base class */
  2681. QCPLayoutElement* QCPLayoutInset::takeAt(int index)
  2682. {
  2683. if (QCPLayoutElement* el = elementAt(index)) {
  2684. releaseElement(el);
  2685. mElements.removeAt(index);
  2686. mInsetPlacement.removeAt(index);
  2687. mInsetAlignment.removeAt(index);
  2688. mInsetRect.removeAt(index);
  2689. return el;
  2690. } else {
  2691. qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
  2692. return 0;
  2693. }
  2694. }
  2695. /* inherits documentation from base class */
  2696. bool QCPLayoutInset::take(QCPLayoutElement* element)
  2697. {
  2698. if (element) {
  2699. for (int i = 0; i < elementCount(); ++i) {
  2700. if (elementAt(i) == element) {
  2701. takeAt(i);
  2702. return true;
  2703. }
  2704. }
  2705. qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
  2706. } else
  2707. qDebug() << Q_FUNC_INFO << "Can't take null element";
  2708. return false;
  2709. }
  2710. /*!
  2711. The inset layout is sensitive to events only at areas where its (visible) child elements are
  2712. sensitive. If the selectTest method of any of the child elements returns a positive number for \a
  2713. pos, this method returns a value corresponding to 0.99 times the parent plot's selection
  2714. tolerance. The inset layout is not selectable itself by default. So if \a onlySelectable is true,
  2715. -1.0 is returned.
  2716. See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
  2717. */
  2718. double QCPLayoutInset::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  2719. {
  2720. Q_UNUSED(details)
  2721. if (onlySelectable)
  2722. return -1;
  2723. for (int i = 0; i < mElements.size(); ++i) {
  2724. // inset layout shall only return positive selectTest, if actually an inset object is at pos
  2725. // else it would block the entire underlying QCPAxisRect with its surface.
  2726. if (mElements.at(i)->realVisibility()
  2727. && mElements.at(i)->selectTest(pos, onlySelectable) >= 0)
  2728. return mParentPlot->selectionTolerance() * 0.99;
  2729. }
  2730. return -1;
  2731. }
  2732. /*!
  2733. Adds the specified \a element to the layout as an inset aligned at the border (\ref
  2734. setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a
  2735. alignment.
  2736. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
  2737. Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
  2738. alignment flags will be ignored.
  2739. \see addElement(QCPLayoutElement *element, const QRectF &rect)
  2740. */
  2741. void QCPLayoutInset::addElement(QCPLayoutElement* element, Qt::Alignment alignment)
  2742. {
  2743. if (element) {
  2744. if (element->layout()) // remove from old layout first
  2745. element->layout()->take(element);
  2746. mElements.append(element);
  2747. mInsetPlacement.append(ipBorderAligned);
  2748. mInsetAlignment.append(alignment);
  2749. mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4));
  2750. adoptElement(element);
  2751. } else
  2752. qDebug() << Q_FUNC_INFO << "Can't add null element";
  2753. }
  2754. /*!
  2755. Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref
  2756. setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a
  2757. rect.
  2758. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
  2759. will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
  2760. corner of the layout, with 35% width and height of the parent layout.
  2761. \see addElement(QCPLayoutElement *element, Qt::Alignment alignment)
  2762. */
  2763. void QCPLayoutInset::addElement(QCPLayoutElement* element, const QRectF& rect)
  2764. {
  2765. if (element) {
  2766. if (element->layout()) // remove from old layout first
  2767. element->layout()->take(element);
  2768. mElements.append(element);
  2769. mInsetPlacement.append(ipFree);
  2770. mInsetAlignment.append(Qt::AlignRight | Qt::AlignTop);
  2771. mInsetRect.append(rect);
  2772. adoptElement(element);
  2773. } else
  2774. qDebug() << Q_FUNC_INFO << "Can't add null element";
  2775. }
  2776. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2777. //////////////////// QCPLineEnding
  2778. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2779. /*! \class QCPLineEnding
  2780. \brief Handles the different ending decorations for line-like items
  2781. \image html QCPLineEnding.png "The various ending styles currently supported"
  2782. For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine
  2783. has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail.
  2784. The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can
  2785. be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of
  2786. the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item.
  2787. For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite
  2788. directions, e.g. "outward". This can be changed by \ref setInverted, which would make the
  2789. respective arrow point inward.
  2790. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a
  2791. QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g.
  2792. \snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead
  2793. */
  2794. /*!
  2795. Creates a QCPLineEnding instance with default values (style \ref esNone).
  2796. */
  2797. QCPLineEnding::QCPLineEnding() : mStyle(esNone), mWidth(8), mLength(10), mInverted(false)
  2798. {}
  2799. /*!
  2800. Creates a QCPLineEnding instance with the specified values.
  2801. */
  2802. QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length,
  2803. bool inverted)
  2804. : mStyle(style), mWidth(width), mLength(length), mInverted(inverted)
  2805. {}
  2806. /*!
  2807. Sets the style of the ending decoration.
  2808. */
  2809. void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style)
  2810. {
  2811. mStyle = style;
  2812. }
  2813. /*!
  2814. Sets the width of the ending decoration, if the style supports it. On arrows, for example, the
  2815. width defines the size perpendicular to the arrow's pointing direction.
  2816. \see setLength
  2817. */
  2818. void QCPLineEnding::setWidth(double width)
  2819. {
  2820. mWidth = width;
  2821. }
  2822. /*!
  2823. Sets the length of the ending decoration, if the style supports it. On arrows, for example, the
  2824. length defines the size in pointing direction.
  2825. \see setWidth
  2826. */
  2827. void QCPLineEnding::setLength(double length)
  2828. {
  2829. mLength = length;
  2830. }
  2831. /*!
  2832. Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point
  2833. inward when \a inverted is set to true.
  2834. Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or
  2835. discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are
  2836. affected by it, which can be used to control to which side the half bar points to.
  2837. */
  2838. void QCPLineEnding::setInverted(bool inverted)
  2839. {
  2840. mInverted = inverted;
  2841. }
  2842. /*! \internal
  2843. Returns the maximum pixel radius the ending decoration might cover, starting from the position
  2844. the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item).
  2845. This is relevant for clipping. Only omit painting of the decoration when the position where the
  2846. decoration is supposed to be drawn is farther away from the clipping rect than the returned
  2847. distance.
  2848. */
  2849. double QCPLineEnding::boundingDistance() const
  2850. {
  2851. switch (mStyle) {
  2852. case esNone:
  2853. return 0;
  2854. case esFlatArrow:
  2855. case esSpikeArrow:
  2856. case esLineArrow:
  2857. case esSkewedBar:
  2858. return qSqrt(mWidth * mWidth + mLength * mLength); // items that have width and length
  2859. case esDisc:
  2860. case esSquare:
  2861. case esDiamond:
  2862. case esBar:
  2863. case esHalfBar:
  2864. return mWidth * 1.42; // items that only have a width -> width*sqrt(2)
  2865. }
  2866. return 0;
  2867. }
  2868. /*!
  2869. Starting from the origin of this line ending (which is style specific), returns the length
  2870. covered by the line ending symbol, in backward direction.
  2871. For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if
  2872. both have the same \ref setLength value, because the spike arrow has an inward curved back, which
  2873. reduces the length along its center axis (the drawing origin for arrows is at the tip).
  2874. This function is used for precise, style specific placement of line endings, for example in
  2875. QCPAxes.
  2876. */
  2877. double QCPLineEnding::realLength() const
  2878. {
  2879. switch (mStyle) {
  2880. case esNone:
  2881. case esLineArrow:
  2882. case esSkewedBar:
  2883. case esBar:
  2884. case esHalfBar:
  2885. return 0;
  2886. case esFlatArrow:
  2887. return mLength;
  2888. case esDisc:
  2889. case esSquare:
  2890. case esDiamond:
  2891. return mWidth * 0.5;
  2892. case esSpikeArrow:
  2893. return mLength * 0.8;
  2894. }
  2895. return 0;
  2896. }
  2897. /*! \internal
  2898. Draws the line ending with the specified \a painter at the position \a pos. The direction of the
  2899. line ending is controlled with \a dir.
  2900. */
  2901. void QCPLineEnding::draw(QCPPainter* painter, const QVector2D& pos, const QVector2D& dir) const
  2902. {
  2903. if (mStyle == esNone)
  2904. return;
  2905. QVector2D lengthVec(dir.normalized());
  2906. if (lengthVec.isNull())
  2907. lengthVec = QVector2D(1, 0);
  2908. QVector2D widthVec(-lengthVec.y(), lengthVec.x());
  2909. lengthVec *= (float)(mLength * (mInverted ? -1 : 1));
  2910. widthVec *= (float)(mWidth * 0.5 * (mInverted ? -1 : 1));
  2911. QPen penBackup = painter->pen();
  2912. QBrush brushBackup = painter->brush();
  2913. QPen miterPen = penBackup;
  2914. miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey
  2915. QBrush brush(painter->pen().color(), Qt::SolidPattern);
  2916. switch (mStyle) {
  2917. case esNone:
  2918. break;
  2919. case esFlatArrow: {
  2920. QPointF points[3] = {pos.toPointF(), (pos - lengthVec + widthVec).toPointF(),
  2921. (pos - lengthVec - widthVec).toPointF()};
  2922. painter->setPen(miterPen);
  2923. painter->setBrush(brush);
  2924. painter->drawConvexPolygon(points, 3);
  2925. painter->setBrush(brushBackup);
  2926. painter->setPen(penBackup);
  2927. break;
  2928. }
  2929. case esSpikeArrow: {
  2930. QPointF points[4] = {pos.toPointF(), (pos - lengthVec + widthVec).toPointF(),
  2931. (pos - lengthVec * 0.8f).toPointF(),
  2932. (pos - lengthVec - widthVec).toPointF()};
  2933. painter->setPen(miterPen);
  2934. painter->setBrush(brush);
  2935. painter->drawConvexPolygon(points, 4);
  2936. painter->setBrush(brushBackup);
  2937. painter->setPen(penBackup);
  2938. break;
  2939. }
  2940. case esLineArrow: {
  2941. QPointF points[3] = {(pos - lengthVec + widthVec).toPointF(), pos.toPointF(),
  2942. (pos - lengthVec - widthVec).toPointF()};
  2943. painter->setPen(miterPen);
  2944. painter->drawPolyline(points, 3);
  2945. painter->setPen(penBackup);
  2946. break;
  2947. }
  2948. case esDisc: {
  2949. painter->setBrush(brush);
  2950. painter->drawEllipse(pos.toPointF(), mWidth * 0.5, mWidth * 0.5);
  2951. painter->setBrush(brushBackup);
  2952. break;
  2953. }
  2954. case esSquare: {
  2955. QVector2D widthVecPerp(-widthVec.y(), widthVec.x());
  2956. QPointF points[4] = {
  2957. (pos - widthVecPerp + widthVec).toPointF(), (pos - widthVecPerp - widthVec).toPointF(),
  2958. (pos + widthVecPerp - widthVec).toPointF(), (pos + widthVecPerp + widthVec).toPointF()};
  2959. painter->setPen(miterPen);
  2960. painter->setBrush(brush);
  2961. painter->drawConvexPolygon(points, 4);
  2962. painter->setBrush(brushBackup);
  2963. painter->setPen(penBackup);
  2964. break;
  2965. }
  2966. case esDiamond: {
  2967. QVector2D widthVecPerp(-widthVec.y(), widthVec.x());
  2968. QPointF points[4] = {(pos - widthVecPerp).toPointF(), (pos - widthVec).toPointF(),
  2969. (pos + widthVecPerp).toPointF(), (pos + widthVec).toPointF()};
  2970. painter->setPen(miterPen);
  2971. painter->setBrush(brush);
  2972. painter->drawConvexPolygon(points, 4);
  2973. painter->setBrush(brushBackup);
  2974. painter->setPen(penBackup);
  2975. break;
  2976. }
  2977. case esBar: {
  2978. painter->drawLine((pos + widthVec).toPointF(), (pos - widthVec).toPointF());
  2979. break;
  2980. }
  2981. case esHalfBar: {
  2982. painter->drawLine((pos + widthVec).toPointF(), pos.toPointF());
  2983. break;
  2984. }
  2985. case esSkewedBar: {
  2986. if (qFuzzyIsNull(painter->pen().widthF())
  2987. && !painter->modes().testFlag(QCPPainter::pmNonCosmetic)) {
  2988. // if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports),
  2989. // draw bar exactly on tip of line
  2990. painter->drawLine(
  2991. (pos + widthVec + lengthVec * 0.2f * (mInverted ? -1 : 1)).toPointF(),
  2992. (pos - widthVec - lengthVec * 0.2f * (mInverted ? -1 : 1)).toPointF());
  2993. } else {
  2994. // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to
  2995. // prevent line from sticking through bar slightly
  2996. painter->drawLine(
  2997. (pos + widthVec + lengthVec * 0.2f * (mInverted ? -1 : 1)
  2998. + dir.normalized() * qMax(1.0f, (float)painter->pen().widthF()) * 0.5f)
  2999. .toPointF(),
  3000. (pos - widthVec - lengthVec * 0.2f * (mInverted ? -1 : 1)
  3001. + dir.normalized() * qMax(1.0f, (float)painter->pen().widthF()) * 0.5f)
  3002. .toPointF());
  3003. }
  3004. break;
  3005. }
  3006. }
  3007. }
  3008. /*! \internal
  3009. \overload
  3010. Draws the line ending. The direction is controlled with the \a angle parameter in radians.
  3011. */
  3012. void QCPLineEnding::draw(QCPPainter* painter, const QVector2D& pos, double angle) const
  3013. {
  3014. draw(painter, pos, QVector2D(qCos(angle), qSin(angle)));
  3015. }
  3016. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3017. //////////////////// QCPGrid
  3018. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3019. /*! \class QCPGrid
  3020. \brief Responsible for drawing the grid of a QCPAxis.
  3021. This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the
  3022. grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref
  3023. QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself.
  3024. The axis and grid drawing was split into two classes to allow them to be placed on different
  3025. layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid
  3026. in the background and the axes in the foreground, and any plottables/items in between. This
  3027. described situation is the default setup, see the QCPLayer documentation.
  3028. */
  3029. /*!
  3030. Creates a QCPGrid instance and sets default values.
  3031. You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid.
  3032. */
  3033. QCPGrid::QCPGrid(QCPAxis* parentAxis)
  3034. : QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis), mParentAxis(parentAxis)
  3035. {
  3036. // warning: this is called in QCPAxis constructor, so parentAxis members should not be
  3037. // accessed/called
  3038. setParent(parentAxis);
  3039. setPen(QPen(QColor(200, 200, 200), 0, Qt::DotLine));
  3040. setSubGridPen(QPen(QColor(220, 220, 220), 0, Qt::DotLine));
  3041. setZeroLinePen(QPen(QColor(200, 200, 200), 0, Qt::SolidLine));
  3042. setSubGridVisible(false);
  3043. setAntialiased(false);
  3044. setAntialiasedSubGrid(false);
  3045. setAntialiasedZeroLine(false);
  3046. }
  3047. /*!
  3048. Sets whether grid lines at sub tick marks are drawn.
  3049. \see setSubGridPen
  3050. */
  3051. void QCPGrid::setSubGridVisible(bool visible)
  3052. {
  3053. mSubGridVisible = visible;
  3054. }
  3055. /*!
  3056. Sets whether sub grid lines are drawn antialiased.
  3057. */
  3058. void QCPGrid::setAntialiasedSubGrid(bool enabled)
  3059. {
  3060. mAntialiasedSubGrid = enabled;
  3061. }
  3062. /*!
  3063. Sets whether zero lines are drawn antialiased.
  3064. */
  3065. void QCPGrid::setAntialiasedZeroLine(bool enabled)
  3066. {
  3067. mAntialiasedZeroLine = enabled;
  3068. }
  3069. /*!
  3070. Sets the pen with which (major) grid lines are drawn.
  3071. */
  3072. void QCPGrid::setPen(const QPen& pen)
  3073. {
  3074. mPen = pen;
  3075. }
  3076. /*!
  3077. Sets the pen with which sub grid lines are drawn.
  3078. */
  3079. void QCPGrid::setSubGridPen(const QPen& pen)
  3080. {
  3081. mSubGridPen = pen;
  3082. }
  3083. /*!
  3084. Sets the pen with which zero lines are drawn.
  3085. Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid
  3086. lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen.
  3087. */
  3088. void QCPGrid::setZeroLinePen(const QPen& pen)
  3089. {
  3090. mZeroLinePen = pen;
  3091. }
  3092. /*! \internal
  3093. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  3094. before drawing the major grid lines.
  3095. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  3096. This function takes into account the local setting of the antialiasing flag as well as the
  3097. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  3098. QCustomPlot::setNotAntialiasedElements.
  3099. \see setAntialiased
  3100. */
  3101. void QCPGrid::applyDefaultAntialiasingHint(QCPPainter* painter) const
  3102. {
  3103. applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
  3104. }
  3105. /*! \internal
  3106. Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
  3107. over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
  3108. */
  3109. void QCPGrid::draw(QCPPainter* painter)
  3110. {
  3111. if (!mParentAxis) {
  3112. qDebug() << Q_FUNC_INFO << "invalid parent axis";
  3113. return;
  3114. }
  3115. if (mSubGridVisible)
  3116. drawSubGridLines(painter);
  3117. drawGridLines(painter);
  3118. }
  3119. /*! \internal
  3120. Draws the main grid lines and possibly a zero line with the specified painter.
  3121. This is a helper function called by \ref draw.
  3122. */
  3123. void QCPGrid::drawGridLines(QCPPainter* painter) const
  3124. {
  3125. if (!mParentAxis) {
  3126. qDebug() << Q_FUNC_INFO << "invalid parent axis";
  3127. return;
  3128. }
  3129. int lowTick = mParentAxis->mLowestVisibleTick;
  3130. int highTick = mParentAxis->mHighestVisibleTick;
  3131. double t; // helper variable, result of coordinate-to-pixel transforms
  3132. if (mParentAxis->orientation() == Qt::Horizontal) {
  3133. // draw zeroline:
  3134. int zeroLineIndex = -1;
  3135. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0
  3136. && mParentAxis->mRange.upper > 0) {
  3137. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  3138. painter->setPen(mZeroLinePen);
  3139. double epsilon = mParentAxis->range().size() * 1E-6; // for comparing double to zero
  3140. for (int i = lowTick; i <= highTick; ++i) {
  3141. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) {
  3142. zeroLineIndex = i;
  3143. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  3144. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t,
  3145. mParentAxis->mAxisRect->top()));
  3146. break;
  3147. }
  3148. }
  3149. }
  3150. // draw grid lines:
  3151. applyDefaultAntialiasingHint(painter);
  3152. painter->setPen(mPen);
  3153. for (int i = lowTick; i <= highTick; ++i) {
  3154. if (i == zeroLineIndex)
  3155. continue; // don't draw a gridline on top of the zeroline
  3156. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  3157. painter->drawLine(
  3158. QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  3159. }
  3160. } else {
  3161. // draw zeroline:
  3162. int zeroLineIndex = -1;
  3163. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0
  3164. && mParentAxis->mRange.upper > 0) {
  3165. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  3166. painter->setPen(mZeroLinePen);
  3167. double epsilon = mParentAxis->mRange.size() * 1E-6; // for comparing double to zero
  3168. for (int i = lowTick; i <= highTick; ++i) {
  3169. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) {
  3170. zeroLineIndex = i;
  3171. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  3172. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t,
  3173. mParentAxis->mAxisRect->right(), t));
  3174. break;
  3175. }
  3176. }
  3177. }
  3178. // draw grid lines:
  3179. applyDefaultAntialiasingHint(painter);
  3180. painter->setPen(mPen);
  3181. for (int i = lowTick; i <= highTick; ++i) {
  3182. if (i == zeroLineIndex)
  3183. continue; // don't draw a gridline on top of the zeroline
  3184. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  3185. painter->drawLine(
  3186. QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  3187. }
  3188. }
  3189. }
  3190. /*! \internal
  3191. Draws the sub grid lines with the specified painter.
  3192. This is a helper function called by \ref draw.
  3193. */
  3194. void QCPGrid::drawSubGridLines(QCPPainter* painter) const
  3195. {
  3196. if (!mParentAxis) {
  3197. qDebug() << Q_FUNC_INFO << "invalid parent axis";
  3198. return;
  3199. }
  3200. applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid);
  3201. double t; // helper variable, result of coordinate-to-pixel transforms
  3202. painter->setPen(mSubGridPen);
  3203. if (mParentAxis->orientation() == Qt::Horizontal) {
  3204. for (int i = 0; i < mParentAxis->mSubTickVector.size(); ++i) {
  3205. t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x
  3206. painter->drawLine(
  3207. QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  3208. }
  3209. } else {
  3210. for (int i = 0; i < mParentAxis->mSubTickVector.size(); ++i) {
  3211. t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y
  3212. painter->drawLine(
  3213. QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  3214. }
  3215. }
  3216. }
  3217. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3218. //////////////////// QCPAxis
  3219. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3220. /*! \class QCPAxis
  3221. \brief Manages a single axis inside a QCustomPlot.
  3222. Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via
  3223. QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and
  3224. QCustomPlot::yAxis2 (right).
  3225. Axes are always part of an axis rect, see QCPAxisRect.
  3226. \image html AxisNamesOverview.png
  3227. <center>Naming convention of axis parts</center>
  3228. \n
  3229. \image html AxisRectSpacingOverview.png
  3230. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray
  3231. line on the left represents the QCustomPlot widget border.</center>
  3232. */
  3233. /* start of documentation of inline functions */
  3234. /*! \fn Qt::Orientation QCPAxis::orientation() const
  3235. Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced
  3236. from the axis type (left, top, right or bottom).
  3237. \see orientation(AxisType type)
  3238. */
  3239. /*! \fn QCPGrid *QCPAxis::grid() const
  3240. Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way
  3241. the grid is displayed.
  3242. */
  3243. /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type)
  3244. Returns the orientation of the specified axis type
  3245. \see orientation()
  3246. */
  3247. /* end of documentation of inline functions */
  3248. /* start of documentation of signals */
  3249. /*! \fn void QCPAxis::ticksRequest()
  3250. This signal is emitted when \ref setAutoTicks is false and the axis is about to generate tick
  3251. labels for a replot.
  3252. Modifying the tick positions can be done with \ref setTickVector. If you also want to control the
  3253. tick labels, set \ref setAutoTickLabels to false and also provide the labels with \ref
  3254. setTickVectorLabels.
  3255. If you only want static ticks you probably don't need this signal, since you can just set the
  3256. tick vector (and possibly tick label vector) once. However, if you want to provide ticks (and
  3257. maybe labels) dynamically, e.g. depending on the current axis range, connect a slot to this
  3258. signal and set the vector/vectors there.
  3259. */
  3260. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange)
  3261. This signal is emitted when the range of this axis has changed. You can connect it to the \ref
  3262. setRange slot of another axis to communicate the new range to the other axis, in order for it to
  3263. be synchronized.
  3264. You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
  3265. This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
  3266. range shouldn't go beyond certain values. For example, the following slot would limit the x axis
  3267. to only positive ranges:
  3268. \code
  3269. if (newRange.lower < 0)
  3270. plot->xAxis->setRange(0, newRange.size());
  3271. \endcode
  3272. */
  3273. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
  3274. \overload
  3275. Additionally to the new range, this signal also provides the previous range held by the axis as
  3276. \a oldRange.
  3277. */
  3278. /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType);
  3279. This signal is emitted when the scale type changes, by calls to \ref setScaleType
  3280. */
  3281. /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection)
  3282. This signal is emitted when the selection state of this axis has changed, either by user
  3283. interaction or by a direct call to \ref setSelectedParts.
  3284. */
  3285. /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts);
  3286. This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
  3287. */
  3288. /* end of documentation of signals */
  3289. /*!
  3290. Constructs an Axis instance of Type \a type for the axis rect \a parent.
  3291. Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
  3292. them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
  3293. create them manually and then inject them also via \ref QCPAxisRect::addAxis.
  3294. */
  3295. QCPAxis::QCPAxis(QCPAxisRect* parent, AxisType type)
  3296. : QCPLayerable(parent->parentPlot(), QString(), parent)
  3297. ,
  3298. // axis base:
  3299. mAxisType(type)
  3300. , mAxisRect(parent)
  3301. , mPadding(5)
  3302. , mOrientation(orientation(type))
  3303. , mSelectableParts(spAxis | spTickLabels | spAxisLabel)
  3304. , mSelectedParts(spNone)
  3305. , mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap))
  3306. , mSelectedBasePen(QPen(Qt::blue, 2))
  3307. ,
  3308. // axis label:
  3309. mLabel()
  3310. , mLabelFont(mParentPlot->font())
  3311. , mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold))
  3312. , mLabelColor(Qt::black)
  3313. , mSelectedLabelColor(Qt::blue)
  3314. ,
  3315. // tick labels:
  3316. mTickLabels(true)
  3317. , mAutoTickLabels(true)
  3318. , mTickLabelType(ltNumber)
  3319. , mTickLabelFont(mParentPlot->font())
  3320. , mSelectedTickLabelFont(
  3321. QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold))
  3322. , mTickLabelColor(Qt::black)
  3323. , mSelectedTickLabelColor(Qt::blue)
  3324. , mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy"))
  3325. , mDateTimeSpec(Qt::LocalTime)
  3326. , mNumberPrecision(6)
  3327. , mNumberFormatChar('g')
  3328. , mNumberBeautifulPowers(true)
  3329. ,
  3330. // ticks and subticks:
  3331. mTicks(true)
  3332. , mTickStep(1)
  3333. , mSubTickCount(4)
  3334. , mAutoTickCount(6)
  3335. , mAutoTicks(true)
  3336. , mAutoTickStep(true)
  3337. , mAutoSubTicks(true)
  3338. , mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap))
  3339. , mSelectedTickPen(QPen(Qt::blue, 2))
  3340. , mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap))
  3341. , mSelectedSubTickPen(QPen(Qt::blue, 2))
  3342. ,
  3343. // scale and range:
  3344. mRange(0, 5)
  3345. , mRangeReversed(false)
  3346. , mScaleType(stLinear)
  3347. , mScaleLogBase(10)
  3348. , mScaleLogBaseLogInv(1.0 / qLn(mScaleLogBase))
  3349. ,
  3350. // internal members:
  3351. mGrid(new QCPGrid(this))
  3352. , mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot()))
  3353. , mLowestVisibleTick(0)
  3354. , mHighestVisibleTick(-1)
  3355. , mCachedMarginValid(false)
  3356. , mCachedMargin(0)
  3357. {
  3358. setParent(parent);
  3359. mGrid->setVisible(false);
  3360. setAntialiased(false);
  3361. setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in
  3362. // front of the grid, so we place it on there again
  3363. if (type == atTop) {
  3364. setTickLabelPadding(3);
  3365. setLabelPadding(6);
  3366. } else if (type == atRight) {
  3367. setTickLabelPadding(7);
  3368. setLabelPadding(12);
  3369. } else if (type == atBottom) {
  3370. setTickLabelPadding(3);
  3371. setLabelPadding(3);
  3372. } else if (type == atLeft) {
  3373. setTickLabelPadding(5);
  3374. setLabelPadding(10);
  3375. }
  3376. }
  3377. QCPAxis::~QCPAxis()
  3378. {
  3379. delete mAxisPainter;
  3380. delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion
  3381. // order
  3382. }
  3383. /* No documentation as it is a property getter */
  3384. int QCPAxis::tickLabelPadding() const
  3385. {
  3386. return mAxisPainter->tickLabelPadding;
  3387. }
  3388. /* No documentation as it is a property getter */
  3389. double QCPAxis::tickLabelRotation() const
  3390. {
  3391. return mAxisPainter->tickLabelRotation;
  3392. }
  3393. /* No documentation as it is a property getter */
  3394. QCPAxis::LabelSide QCPAxis::tickLabelSide() const
  3395. {
  3396. return mAxisPainter->tickLabelSide;
  3397. }
  3398. /* No documentation as it is a property getter */
  3399. QString QCPAxis::numberFormat() const
  3400. {
  3401. QString result;
  3402. result.append(mNumberFormatChar);
  3403. if (mNumberBeautifulPowers) {
  3404. result.append(QLatin1Char('b'));
  3405. if (mAxisPainter->numberMultiplyCross)
  3406. result.append(QLatin1Char('c'));
  3407. }
  3408. return result;
  3409. }
  3410. /* No documentation as it is a property getter */
  3411. int QCPAxis::tickLengthIn() const
  3412. {
  3413. return mAxisPainter->tickLengthIn;
  3414. }
  3415. /* No documentation as it is a property getter */
  3416. int QCPAxis::tickLengthOut() const
  3417. {
  3418. return mAxisPainter->tickLengthOut;
  3419. }
  3420. /* No documentation as it is a property getter */
  3421. int QCPAxis::subTickLengthIn() const
  3422. {
  3423. return mAxisPainter->subTickLengthIn;
  3424. }
  3425. /* No documentation as it is a property getter */
  3426. int QCPAxis::subTickLengthOut() const
  3427. {
  3428. return mAxisPainter->subTickLengthOut;
  3429. }
  3430. /* No documentation as it is a property getter */
  3431. int QCPAxis::labelPadding() const
  3432. {
  3433. return mAxisPainter->labelPadding;
  3434. }
  3435. /* No documentation as it is a property getter */
  3436. int QCPAxis::offset() const
  3437. {
  3438. return mAxisPainter->offset;
  3439. }
  3440. /* No documentation as it is a property getter */
  3441. QCPLineEnding QCPAxis::lowerEnding() const
  3442. {
  3443. return mAxisPainter->lowerEnding;
  3444. }
  3445. /* No documentation as it is a property getter */
  3446. QCPLineEnding QCPAxis::upperEnding() const
  3447. {
  3448. return mAxisPainter->upperEnding;
  3449. }
  3450. /*!
  3451. Sets whether the axis uses a linear scale or a logarithmic scale. If \a type is set to \ref
  3452. stLogarithmic, the logarithm base can be set with \ref setScaleLogBase. In logarithmic axis
  3453. scaling, major tick marks appear at all powers of the logarithm base. Properties like tick step
  3454. (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major
  3455. ticks, consider choosing a logarithm base of 100, 1000 or even higher.
  3456. If \a type is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' option
  3457. (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10
  3458. [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]"
  3459. part). To only display the decimal power, set the number precision to zero with
  3460. \ref setNumberPrecision.
  3461. */
  3462. void QCPAxis::setScaleType(QCPAxis::ScaleType type)
  3463. {
  3464. if (mScaleType != type) {
  3465. mScaleType = type;
  3466. if (mScaleType == stLogarithmic)
  3467. setRange(mRange.sanitizedForLogScale());
  3468. mCachedMarginValid = false;
  3469. emit scaleTypeChanged(mScaleType);
  3470. }
  3471. }
  3472. /*!
  3473. If \ref setScaleType is set to \ref stLogarithmic, \a base will be the logarithm base of the
  3474. scaling. In logarithmic axis scaling, major tick marks appear at all powers of \a base.
  3475. Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a
  3476. decimal base but less major ticks, consider choosing \a base 100, 1000 or even higher.
  3477. */
  3478. void QCPAxis::setScaleLogBase(double base)
  3479. {
  3480. if (base > 1) {
  3481. mScaleLogBase = base;
  3482. mScaleLogBaseLogInv = 1.0 / qLn(mScaleLogBase); // buffer for faster baseLog() calculation
  3483. mCachedMarginValid = false;
  3484. } else
  3485. qDebug() << Q_FUNC_INFO << "Invalid logarithmic scale base (must be greater 1):" << base;
  3486. }
  3487. /*!
  3488. Sets the range of the axis.
  3489. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  3490. is always synchronized with the other axis range, when it changes.
  3491. To invert the direction of an axis, use \ref setRangeReversed.
  3492. */
  3493. void QCPAxis::setRange(const QCPRange& range)
  3494. {
  3495. if (range.lower == mRange.lower && range.upper == mRange.upper)
  3496. return;
  3497. if (!QCPRange::validRange(range))
  3498. return;
  3499. QCPRange oldRange = mRange;
  3500. if (mScaleType == stLogarithmic) {
  3501. mRange = range.sanitizedForLogScale();
  3502. } else {
  3503. mRange = range.sanitizedForLinScale();
  3504. }
  3505. mCachedMarginValid = false;
  3506. emit rangeChanged(mRange);
  3507. emit rangeChanged(mRange, oldRange);
  3508. }
  3509. /*!
  3510. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot
  3511. surface. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  3512. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  3513. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  3514. directly.
  3515. \see SelectablePart, setSelectedParts
  3516. */
  3517. void QCPAxis::setSelectableParts(const SelectableParts& selectable)
  3518. {
  3519. if (mSelectableParts != selectable) {
  3520. mSelectableParts = selectable;
  3521. emit selectableChanged(mSelectableParts);
  3522. }
  3523. }
  3524. /*!
  3525. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  3526. is selected, it uses a different pen/font.
  3527. The entire selection mechanism for axes is handled automatically when \ref
  3528. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  3529. wish to change the selection state manually.
  3530. This function can change the selection state of a part, independent of the \ref setSelectableParts
  3531. setting.
  3532. emits the \ref selectionChanged signal when \a selected is different from the previous selection
  3533. state.
  3534. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen,
  3535. setSelectedSubTickPen, setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor,
  3536. setSelectedLabelColor
  3537. */
  3538. void QCPAxis::setSelectedParts(const SelectableParts& selected)
  3539. {
  3540. if (mSelectedParts != selected) {
  3541. mSelectedParts = selected;
  3542. emit selectionChanged(mSelectedParts);
  3543. }
  3544. }
  3545. /*!
  3546. \overload
  3547. Sets the lower and upper bound of the axis range.
  3548. To invert the direction of an axis, use \ref setRangeReversed.
  3549. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  3550. */
  3551. void QCPAxis::setRange(double lower, double upper)
  3552. {
  3553. if (lower == mRange.lower && upper == mRange.upper)
  3554. return;
  3555. if (!QCPRange::validRange(lower, upper))
  3556. return;
  3557. QCPRange oldRange = mRange;
  3558. mRange.lower = lower;
  3559. mRange.upper = upper;
  3560. if (mScaleType == stLogarithmic) {
  3561. mRange = mRange.sanitizedForLogScale();
  3562. } else {
  3563. mRange = mRange.sanitizedForLinScale();
  3564. }
  3565. mCachedMarginValid = false;
  3566. emit rangeChanged(mRange);
  3567. emit rangeChanged(mRange, oldRange);
  3568. }
  3569. /*!
  3570. \overload
  3571. Sets the range of the axis.
  3572. The \a position coordinate indicates together with the \a alignment parameter, where the new
  3573. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  3574. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  3575. or center of the range to be aligned with \a position. Any other values of \a alignment will
  3576. default to Qt::AlignCenter.
  3577. */
  3578. void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment)
  3579. {
  3580. if (alignment == Qt::AlignLeft)
  3581. setRange(position, position + size);
  3582. else if (alignment == Qt::AlignRight)
  3583. setRange(position - size, position);
  3584. else // alignment == Qt::AlignCenter
  3585. setRange(position - size / 2.0, position + size / 2.0);
  3586. }
  3587. /*!
  3588. Sets the lower bound of the axis range. The upper bound is not changed.
  3589. \see setRange
  3590. */
  3591. void QCPAxis::setRangeLower(double lower)
  3592. {
  3593. if (mRange.lower == lower)
  3594. return;
  3595. QCPRange oldRange = mRange;
  3596. mRange.lower = lower;
  3597. if (mScaleType == stLogarithmic) {
  3598. mRange = mRange.sanitizedForLogScale();
  3599. } else {
  3600. mRange = mRange.sanitizedForLinScale();
  3601. }
  3602. mCachedMarginValid = false;
  3603. emit rangeChanged(mRange);
  3604. emit rangeChanged(mRange, oldRange);
  3605. }
  3606. /*!
  3607. Sets the upper bound of the axis range. The lower bound is not changed.
  3608. \see setRange
  3609. */
  3610. void QCPAxis::setRangeUpper(double upper)
  3611. {
  3612. if (mRange.upper == upper)
  3613. return;
  3614. QCPRange oldRange = mRange;
  3615. mRange.upper = upper;
  3616. if (mScaleType == stLogarithmic) {
  3617. mRange = mRange.sanitizedForLogScale();
  3618. } else {
  3619. mRange = mRange.sanitizedForLinScale();
  3620. }
  3621. mCachedMarginValid = false;
  3622. emit rangeChanged(mRange);
  3623. emit rangeChanged(mRange, oldRange);
  3624. }
  3625. /*!
  3626. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  3627. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  3628. direction of increasing values is inverted.
  3629. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  3630. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  3631. upper part.
  3632. */
  3633. void QCPAxis::setRangeReversed(bool reversed)
  3634. {
  3635. if (mRangeReversed != reversed) {
  3636. mRangeReversed = reversed;
  3637. mCachedMarginValid = false;
  3638. }
  3639. }
  3640. /*!
  3641. Sets whether the tick positions should be calculated automatically (either from an automatically
  3642. generated tick step or a tick step provided manually via \ref setTickStep, see \ref
  3643. setAutoTickStep).
  3644. If \a on is set to false, you must provide the tick positions manually via \ref setTickVector.
  3645. For these manual ticks you may let QCPAxis generate the appropriate labels automatically by
  3646. leaving \ref setAutoTickLabels set to true. If you also wish to control the displayed labels
  3647. manually, set \ref setAutoTickLabels to false and provide the label strings with \ref
  3648. setTickVectorLabels.
  3649. If you need dynamically calculated tick vectors (and possibly tick label vectors), set the
  3650. vectors in a slot connected to the \ref ticksRequest signal.
  3651. \see setAutoTickLabels, setAutoSubTicks, setAutoTickCount, setAutoTickStep
  3652. */
  3653. void QCPAxis::setAutoTicks(bool on)
  3654. {
  3655. if (mAutoTicks != on) {
  3656. mAutoTicks = on;
  3657. mCachedMarginValid = false;
  3658. }
  3659. }
  3660. /*!
  3661. When \ref setAutoTickStep is true, \a approximateCount determines how many ticks should be
  3662. generated in the visible range, approximately.
  3663. It's not guaranteed that this number of ticks is met exactly, but approximately within a
  3664. tolerance of about two.
  3665. Only values greater than zero are accepted as \a approximateCount.
  3666. \see setAutoTickStep, setAutoTicks, setAutoSubTicks
  3667. */
  3668. void QCPAxis::setAutoTickCount(int approximateCount)
  3669. {
  3670. if (mAutoTickCount != approximateCount) {
  3671. if (approximateCount > 0) {
  3672. mAutoTickCount = approximateCount;
  3673. mCachedMarginValid = false;
  3674. } else
  3675. qDebug() << Q_FUNC_INFO
  3676. << "approximateCount must be greater than zero:" << approximateCount;
  3677. }
  3678. }
  3679. /*!
  3680. Sets whether the tick labels are generated automatically. Depending on the tick label type (\ref
  3681. ltNumber or \ref ltDateTime), the labels will either show the coordinate as floating point
  3682. number (\ref setNumberFormat), or a date/time formatted according to \ref setDateTimeFormat.
  3683. If \a on is set to false, you should provide the tick labels via \ref setTickVectorLabels. This
  3684. is usually used in a combination with \ref setAutoTicks set to false for complete control over
  3685. tick positions and labels, e.g. when the ticks should be at multiples of pi and show "2pi", "3pi"
  3686. etc. as tick labels.
  3687. If you need dynamically calculated tick vectors (and possibly tick label vectors), set the
  3688. vectors in a slot connected to the \ref ticksRequest signal.
  3689. \see setAutoTicks
  3690. */
  3691. void QCPAxis::setAutoTickLabels(bool on)
  3692. {
  3693. if (mAutoTickLabels != on) {
  3694. mAutoTickLabels = on;
  3695. mCachedMarginValid = false;
  3696. }
  3697. }
  3698. /*!
  3699. Sets whether the tick step, i.e. the interval between two (major) ticks, is calculated
  3700. automatically. If \a on is set to true, the axis finds a tick step that is reasonable for human
  3701. readable plots.
  3702. The number of ticks the algorithm aims for within the visible range can be specified with \ref
  3703. setAutoTickCount.
  3704. If \a on is set to false, you may set the tick step manually with \ref setTickStep.
  3705. \see setAutoTicks, setAutoSubTicks, setAutoTickCount
  3706. */
  3707. void QCPAxis::setAutoTickStep(bool on)
  3708. {
  3709. if (mAutoTickStep != on) {
  3710. mAutoTickStep = on;
  3711. mCachedMarginValid = false;
  3712. }
  3713. }
  3714. /*!
  3715. Sets whether the number of sub ticks in one tick interval is determined automatically. This
  3716. works, as long as the tick step mantissa is a multiple of 0.5. When \ref setAutoTickStep is
  3717. enabled, this is always the case.
  3718. When \a on is set to false, you may set the sub tick count with \ref setSubTickCount manually.
  3719. \see setAutoTickCount, setAutoTicks, setAutoTickStep
  3720. */
  3721. void QCPAxis::setAutoSubTicks(bool on)
  3722. {
  3723. if (mAutoSubTicks != on) {
  3724. mAutoSubTicks = on;
  3725. mCachedMarginValid = false;
  3726. }
  3727. }
  3728. /*!
  3729. Sets whether tick marks are displayed.
  3730. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  3731. that, see \ref setTickLabels.
  3732. */
  3733. void QCPAxis::setTicks(bool show)
  3734. {
  3735. if (mTicks != show) {
  3736. mTicks = show;
  3737. mCachedMarginValid = false;
  3738. }
  3739. }
  3740. /*!
  3741. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  3742. */
  3743. void QCPAxis::setTickLabels(bool show)
  3744. {
  3745. if (mTickLabels != show) {
  3746. mTickLabels = show;
  3747. mCachedMarginValid = false;
  3748. }
  3749. }
  3750. /*!
  3751. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  3752. \see setLabelPadding, setPadding
  3753. */
  3754. void QCPAxis::setTickLabelPadding(int padding)
  3755. {
  3756. if (mAxisPainter->tickLabelPadding != padding) {
  3757. mAxisPainter->tickLabelPadding = padding;
  3758. mCachedMarginValid = false;
  3759. }
  3760. }
  3761. /*!
  3762. Sets whether the tick labels display numbers or dates/times.
  3763. If \a type is set to \ref ltNumber, the format specifications of \ref setNumberFormat apply.
  3764. If \a type is set to \ref ltDateTime, the format specifications of \ref setDateTimeFormat apply.
  3765. In QCustomPlot, date/time coordinates are <tt>double</tt> numbers representing the seconds since
  3766. 1970-01-01T00:00:00 UTC. This format can be retrieved from QDateTime objects with the
  3767. QDateTime::toTime_t() function. Since this only gives a resolution of one second, there is also
  3768. the QDateTime::toMSecsSinceEpoch() function which returns the timespan described above in
  3769. milliseconds. Divide its return value by 1000.0 to get a value with the format needed for
  3770. date/time plotting, with a resolution of one millisecond.
  3771. Using the toMSecsSinceEpoch function allows dates that go back to 2nd January 4713 B.C.
  3772. (represented by a negative number), unlike the toTime_t function, which works with unsigned
  3773. integers and thus only goes back to 1st January 1970. So both for range and accuracy, use of
  3774. toMSecsSinceEpoch()/1000.0 should be preferred as key coordinate for date/time axes.
  3775. \see setTickLabels
  3776. */
  3777. void QCPAxis::setTickLabelType(LabelType type)
  3778. {
  3779. if (mTickLabelType != type) {
  3780. mTickLabelType = type;
  3781. mCachedMarginValid = false;
  3782. }
  3783. }
  3784. /*!
  3785. Sets the font of the tick labels.
  3786. \see setTickLabels, setTickLabelColor
  3787. */
  3788. void QCPAxis::setTickLabelFont(const QFont& font)
  3789. {
  3790. if (font != mTickLabelFont) {
  3791. mTickLabelFont = font;
  3792. mCachedMarginValid = false;
  3793. }
  3794. }
  3795. /*!
  3796. Sets the color of the tick labels.
  3797. \see setTickLabels, setTickLabelFont
  3798. */
  3799. void QCPAxis::setTickLabelColor(const QColor& color)
  3800. {
  3801. if (color != mTickLabelColor) {
  3802. mTickLabelColor = color;
  3803. mCachedMarginValid = false;
  3804. }
  3805. }
  3806. /*!
  3807. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  3808. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  3809. from -90 to 90 degrees.
  3810. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  3811. other angles, the label is drawn with an offset such that it seems to point toward or away from
  3812. the tick mark.
  3813. */
  3814. void QCPAxis::setTickLabelRotation(double degrees)
  3815. {
  3816. if (!qFuzzyIsNull(degrees - mAxisPainter->tickLabelRotation)) {
  3817. mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0);
  3818. mCachedMarginValid = false;
  3819. }
  3820. }
  3821. /*!
  3822. Sets whether the tick labels (numbers) shall appear inside or outside the axis rect.
  3823. The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels
  3824. to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels
  3825. appear on the inside are additionally clipped to the axis rect.
  3826. */
  3827. void QCPAxis::setTickLabelSide(LabelSide side)
  3828. {
  3829. mAxisPainter->tickLabelSide = side;
  3830. mCachedMarginValid = false;
  3831. }
  3832. /*!
  3833. Sets the format in which dates and times are displayed as tick labels, if \ref setTickLabelType is
  3834. \ref ltDateTime. for details about the \a format string, see the documentation of
  3835. QDateTime::toString().
  3836. Newlines can be inserted with "\n".
  3837. \see setDateTimeSpec
  3838. */
  3839. void QCPAxis::setDateTimeFormat(const QString& format)
  3840. {
  3841. if (mDateTimeFormat != format) {
  3842. mDateTimeFormat = format;
  3843. mCachedMarginValid = false;
  3844. }
  3845. }
  3846. /*!
  3847. Sets the time spec that is used for the date time values when \ref setTickLabelType is \ref
  3848. ltDateTime.
  3849. The default value of QDateTime objects (and also QCustomPlot) is <tt>Qt::LocalTime</tt>. However,
  3850. if the date time values passed to QCustomPlot are given in the UTC spec, set \a
  3851. timeSpec to <tt>Qt::UTC</tt> to get the correct axis labels.
  3852. \see setDateTimeFormat
  3853. */
  3854. void QCPAxis::setDateTimeSpec(const Qt::TimeSpec& timeSpec)
  3855. {
  3856. mDateTimeSpec = timeSpec;
  3857. }
  3858. /*!
  3859. Sets the number format for the numbers drawn as tick labels (if tick label type is \ref
  3860. ltNumber). This \a formatCode is an extended version of the format code used e.g. by
  3861. QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats"
  3862. section in the detailed description of the QString class. \a formatCode is a string of one, two
  3863. or three characters. The first character is identical to the normal format code used by Qt. In
  3864. short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed,
  3865. whichever is shorter.
  3866. The second and third characters are optional and specific to QCustomPlot:\n
  3867. If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
  3868. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
  3869. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  3870. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  3871. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  3872. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  3873. cross and 183 (0xB7) for the dot.
  3874. If the scale type (\ref setScaleType) is \ref stLogarithmic and the \a formatCode uses the 'b'
  3875. option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10
  3876. [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]"
  3877. part). To only display the decimal power, set the number precision to zero with \ref
  3878. setNumberPrecision.
  3879. Examples for \a formatCode:
  3880. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is
  3881. large, normal scientific format is used \li \c gb If number is small, fixed format is used, if
  3882. number is large, scientific format is used with beautifully typeset decimal powers and a dot as
  3883. multiplication sign \li \c ebc All numbers are in scientific format with beautifully typeset
  3884. decimal power and a cross as multiplication sign \li \c fb illegal format code, since fixed format
  3885. doesn't support (or need) beautifully typeset decimal powers. Format code will be reduced to 'f'.
  3886. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current
  3887. format code will not be changed.
  3888. */
  3889. void QCPAxis::setNumberFormat(const QString& formatCode)
  3890. {
  3891. if (formatCode.isEmpty()) {
  3892. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  3893. return;
  3894. }
  3895. mCachedMarginValid = false;
  3896. // interpret first char as number format char:
  3897. QString allowedFormatChars(QLatin1String("eEfgG"));
  3898. if (allowedFormatChars.contains(formatCode.at(0))) {
  3899. mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
  3900. } else {
  3901. qDebug() << Q_FUNC_INFO
  3902. << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  3903. return;
  3904. }
  3905. if (formatCode.length() < 2) {
  3906. mNumberBeautifulPowers = false;
  3907. mAxisPainter->numberMultiplyCross = false;
  3908. return;
  3909. }
  3910. // interpret second char as indicator for beautiful decimal powers:
  3911. if (formatCode.at(1) == QLatin1Char('b')
  3912. && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g'))) {
  3913. mNumberBeautifulPowers = true;
  3914. } else {
  3915. qDebug()
  3916. << Q_FUNC_INFO
  3917. << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):"
  3918. << formatCode;
  3919. return;
  3920. }
  3921. if (formatCode.length() < 3) {
  3922. mAxisPainter->numberMultiplyCross = false;
  3923. return;
  3924. }
  3925. // interpret third char as indicator for dot or cross multiplication symbol:
  3926. if (formatCode.at(2) == QLatin1Char('c')) {
  3927. mAxisPainter->numberMultiplyCross = true;
  3928. } else if (formatCode.at(2) == QLatin1Char('d')) {
  3929. mAxisPainter->numberMultiplyCross = false;
  3930. } else {
  3931. qDebug() << Q_FUNC_INFO
  3932. << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  3933. return;
  3934. }
  3935. }
  3936. /*!
  3937. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  3938. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  3939. \ref setNumberFormat
  3940. If the scale type (\ref setScaleType) is \ref stLogarithmic and the number format (\ref
  3941. setNumberFormat) uses the 'b' format code (beautifully typeset decimal powers), the display
  3942. usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic
  3943. scaling (the redundant "1 [multiplication sign]" part). To only display the decimal power "10
  3944. [superscript] n", set \a precision to zero.
  3945. */
  3946. void QCPAxis::setNumberPrecision(int precision)
  3947. {
  3948. if (mNumberPrecision != precision) {
  3949. mNumberPrecision = precision;
  3950. mCachedMarginValid = false;
  3951. }
  3952. }
  3953. /*!
  3954. If \ref setAutoTickStep is set to false, use this function to set the tick step manually.
  3955. The tick step is the interval between (major) ticks, in plot coordinates.
  3956. \see setSubTickCount
  3957. */
  3958. void QCPAxis::setTickStep(double step)
  3959. {
  3960. if (mTickStep != step) {
  3961. mTickStep = step;
  3962. mCachedMarginValid = false;
  3963. }
  3964. }
  3965. /*!
  3966. If you want full control over what ticks (and possibly labels) the axes show, this function is
  3967. used to set the coordinates at which ticks will appear.\ref setAutoTicks must be disabled, else
  3968. the provided tick vector will be overwritten with automatically generated tick coordinates upon
  3969. replot. The labels of the ticks can be generated automatically when \ref setAutoTickLabels is
  3970. left enabled. If it is disabled, you can set the labels manually with \ref setTickVectorLabels.
  3971. \a vec is a vector containing the positions of the ticks, in plot coordinates.
  3972. \warning \a vec must be sorted in ascending order, no additional checks are made to ensure this.
  3973. \see setTickVectorLabels
  3974. */
  3975. void QCPAxis::setTickVector(const QVector<double>& vec)
  3976. {
  3977. // don't check whether mTickVector != vec here, because it takes longer than we would save
  3978. mTickVector = vec;
  3979. mCachedMarginValid = false;
  3980. }
  3981. /*!
  3982. If you want full control over what ticks and labels the axes show, this function is used to set a
  3983. number of QStrings that will be displayed at the tick positions which you need to provide with
  3984. \ref setTickVector. These two vectors should have the same size. (Note that you need to disable
  3985. \ref setAutoTicks and \ref setAutoTickLabels first.)
  3986. \a vec is a vector containing the labels of the ticks. The entries correspond to the respective
  3987. indices in the tick vector, passed via \ref setTickVector.
  3988. \see setTickVector
  3989. */
  3990. void QCPAxis::setTickVectorLabels(const QVector<QString>& vec)
  3991. {
  3992. // don't check whether mTickVectorLabels != vec here, because it takes longer than we would save
  3993. mTickVectorLabels = vec;
  3994. mCachedMarginValid = false;
  3995. }
  3996. /*!
  3997. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  3998. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  3999. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  4000. they won't collide with the ticks.
  4001. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  4002. */
  4003. void QCPAxis::setTickLength(int inside, int outside)
  4004. {
  4005. setTickLengthIn(inside);
  4006. setTickLengthOut(outside);
  4007. }
  4008. /*!
  4009. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  4010. inside the plot.
  4011. \see setTickLengthOut, setTickLength, setSubTickLength
  4012. */
  4013. void QCPAxis::setTickLengthIn(int inside)
  4014. {
  4015. if (mAxisPainter->tickLengthIn != inside) {
  4016. mAxisPainter->tickLengthIn = inside;
  4017. }
  4018. }
  4019. /*!
  4020. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  4021. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  4022. increase their distance to the axis accordingly, so they won't collide with the ticks.
  4023. \see setTickLengthIn, setTickLength, setSubTickLength
  4024. */
  4025. void QCPAxis::setTickLengthOut(int outside)
  4026. {
  4027. if (mAxisPainter->tickLengthOut != outside) {
  4028. mAxisPainter->tickLengthOut = outside;
  4029. mCachedMarginValid = false; // only outside tick length can change margin
  4030. }
  4031. }
  4032. /*!
  4033. Sets the number of sub ticks in one (major) tick step. A sub tick count of three for example,
  4034. divides the tick intervals in four sub intervals.
  4035. By default, the number of sub ticks is chosen automatically in a reasonable manner as long as the
  4036. mantissa of the tick step is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is
  4037. always the case.
  4038. If you want to disable automatic sub tick count and use this function to set the count manually,
  4039. see \ref setAutoSubTicks.
  4040. */
  4041. void QCPAxis::setSubTickCount(int count)
  4042. {
  4043. mSubTickCount = count;
  4044. }
  4045. /*!
  4046. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  4047. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  4048. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  4049. so they won't collide with the ticks.
  4050. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  4051. */
  4052. void QCPAxis::setSubTickLength(int inside, int outside)
  4053. {
  4054. setSubTickLengthIn(inside);
  4055. setSubTickLengthOut(outside);
  4056. }
  4057. /*!
  4058. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach
  4059. inside the plot.
  4060. \see setSubTickLengthOut, setSubTickLength, setTickLength
  4061. */
  4062. void QCPAxis::setSubTickLengthIn(int inside)
  4063. {
  4064. if (mAxisPainter->subTickLengthIn != inside) {
  4065. mAxisPainter->subTickLengthIn = inside;
  4066. }
  4067. }
  4068. /*!
  4069. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will
  4070. reach outside the plot. If \a outside is greater than zero, the tick labels will increase their
  4071. distance to the axis accordingly, so they won't collide with the ticks.
  4072. \see setSubTickLengthIn, setSubTickLength, setTickLength
  4073. */
  4074. void QCPAxis::setSubTickLengthOut(int outside)
  4075. {
  4076. if (mAxisPainter->subTickLengthOut != outside) {
  4077. mAxisPainter->subTickLengthOut = outside;
  4078. mCachedMarginValid = false; // only outside tick length can change margin
  4079. }
  4080. }
  4081. /*!
  4082. Sets the pen, the axis base line is drawn with.
  4083. \see setTickPen, setSubTickPen
  4084. */
  4085. void QCPAxis::setBasePen(const QPen& pen)
  4086. {
  4087. mBasePen = pen;
  4088. }
  4089. /*!
  4090. Sets the pen, tick marks will be drawn with.
  4091. \see setTickLength, setBasePen
  4092. */
  4093. void QCPAxis::setTickPen(const QPen& pen)
  4094. {
  4095. mTickPen = pen;
  4096. }
  4097. /*!
  4098. Sets the pen, subtick marks will be drawn with.
  4099. \see setSubTickCount, setSubTickLength, setBasePen
  4100. */
  4101. void QCPAxis::setSubTickPen(const QPen& pen)
  4102. {
  4103. mSubTickPen = pen;
  4104. }
  4105. /*!
  4106. Sets the font of the axis label.
  4107. \see setLabelColor
  4108. */
  4109. void QCPAxis::setLabelFont(const QFont& font)
  4110. {
  4111. if (mLabelFont != font) {
  4112. mLabelFont = font;
  4113. mCachedMarginValid = false;
  4114. }
  4115. }
  4116. /*!
  4117. Sets the color of the axis label.
  4118. \see setLabelFont
  4119. */
  4120. void QCPAxis::setLabelColor(const QColor& color)
  4121. {
  4122. mLabelColor = color;
  4123. }
  4124. /*!
  4125. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  4126. its orientation. To disable axis labels, pass an empty string as \a str.
  4127. */
  4128. void QCPAxis::setLabel(const QString& str)
  4129. {
  4130. if (mLabel != str) {
  4131. mLabel = str;
  4132. mCachedMarginValid = false;
  4133. }
  4134. }
  4135. /*!
  4136. Sets the distance between the tick labels and the axis label.
  4137. \see setTickLabelPadding, setPadding
  4138. */
  4139. void QCPAxis::setLabelPadding(int padding)
  4140. {
  4141. if (mAxisPainter->labelPadding != padding) {
  4142. mAxisPainter->labelPadding = padding;
  4143. mCachedMarginValid = false;
  4144. }
  4145. }
  4146. /*!
  4147. Sets the padding of the axis.
  4148. When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space,
  4149. that is left blank.
  4150. The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled.
  4151. \see setLabelPadding, setTickLabelPadding
  4152. */
  4153. void QCPAxis::setPadding(int padding)
  4154. {
  4155. if (mPadding != padding) {
  4156. mPadding = padding;
  4157. mCachedMarginValid = false;
  4158. }
  4159. }
  4160. /*!
  4161. Sets the offset the axis has to its axis rect side.
  4162. If an axis rect side has multiple axes and automatic margin calculation is enabled for that side,
  4163. only the offset of the inner most axis has meaning (even if it is set to be invisible). The
  4164. offset of the other, outer axes is controlled automatically, to place them at appropriate
  4165. positions.
  4166. */
  4167. void QCPAxis::setOffset(int offset)
  4168. {
  4169. mAxisPainter->offset = offset;
  4170. }
  4171. /*!
  4172. Sets the font that is used for tick labels when they are selected.
  4173. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4174. */
  4175. void QCPAxis::setSelectedTickLabelFont(const QFont& font)
  4176. {
  4177. if (font != mSelectedTickLabelFont) {
  4178. mSelectedTickLabelFont = font;
  4179. // don't set mCachedMarginValid to false here because margin calculation is always done with
  4180. // non-selected fonts
  4181. }
  4182. }
  4183. /*!
  4184. Sets the font that is used for the axis label when it is selected.
  4185. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4186. */
  4187. void QCPAxis::setSelectedLabelFont(const QFont& font)
  4188. {
  4189. mSelectedLabelFont = font;
  4190. // don't set mCachedMarginValid to false here because margin calculation is always done with
  4191. // non-selected fonts
  4192. }
  4193. /*!
  4194. Sets the color that is used for tick labels when they are selected.
  4195. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4196. */
  4197. void QCPAxis::setSelectedTickLabelColor(const QColor& color)
  4198. {
  4199. if (color != mSelectedTickLabelColor) {
  4200. mSelectedTickLabelColor = color;
  4201. }
  4202. }
  4203. /*!
  4204. Sets the color that is used for the axis label when it is selected.
  4205. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4206. */
  4207. void QCPAxis::setSelectedLabelColor(const QColor& color)
  4208. {
  4209. mSelectedLabelColor = color;
  4210. }
  4211. /*!
  4212. Sets the pen that is used to draw the axis base line when selected.
  4213. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4214. */
  4215. void QCPAxis::setSelectedBasePen(const QPen& pen)
  4216. {
  4217. mSelectedBasePen = pen;
  4218. }
  4219. /*!
  4220. Sets the pen that is used to draw the (major) ticks when selected.
  4221. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4222. */
  4223. void QCPAxis::setSelectedTickPen(const QPen& pen)
  4224. {
  4225. mSelectedTickPen = pen;
  4226. }
  4227. /*!
  4228. Sets the pen that is used to draw the subticks when selected.
  4229. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  4230. */
  4231. void QCPAxis::setSelectedSubTickPen(const QPen& pen)
  4232. {
  4233. mSelectedSubTickPen = pen;
  4234. }
  4235. /*!
  4236. Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available
  4237. styles.
  4238. For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending.
  4239. Note that this meaning does not change when the axis range is reversed with \ref
  4240. setRangeReversed.
  4241. \see setUpperEnding
  4242. */
  4243. void QCPAxis::setLowerEnding(const QCPLineEnding& ending)
  4244. {
  4245. mAxisPainter->lowerEnding = ending;
  4246. }
  4247. /*!
  4248. Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available
  4249. styles.
  4250. For horizontal axes, this method refers to the right ending, for vertical axes the top ending.
  4251. Note that this meaning does not change when the axis range is reversed with \ref
  4252. setRangeReversed.
  4253. \see setLowerEnding
  4254. */
  4255. void QCPAxis::setUpperEnding(const QCPLineEnding& ending)
  4256. {
  4257. mAxisPainter->upperEnding = ending;
  4258. }
  4259. /*!
  4260. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  4261. bounds of the range. The range is simply moved by \a diff.
  4262. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  4263. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  4264. */
  4265. void QCPAxis::moveRange(double diff)
  4266. {
  4267. QCPRange oldRange = mRange;
  4268. if (mScaleType == stLinear) {
  4269. mRange.lower += diff;
  4270. mRange.upper += diff;
  4271. } else // mScaleType == stLogarithmic
  4272. {
  4273. mRange.lower *= diff;
  4274. mRange.upper *= diff;
  4275. }
  4276. mCachedMarginValid = false;
  4277. emit rangeChanged(mRange);
  4278. emit rangeChanged(mRange, oldRange);
  4279. }
  4280. /*!
  4281. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  4282. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  4283. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  4284. around 1.0 will have moved symmetrically closer to 1.0).
  4285. */
  4286. void QCPAxis::scaleRange(double factor, double center)
  4287. {
  4288. QCPRange oldRange = mRange;
  4289. if (mScaleType == stLinear) {
  4290. QCPRange newRange;
  4291. newRange.lower = (mRange.lower - center) * factor + center;
  4292. newRange.upper = (mRange.upper - center) * factor + center;
  4293. if (QCPRange::validRange(newRange))
  4294. mRange = newRange.sanitizedForLinScale();
  4295. } else // mScaleType == stLogarithmic
  4296. {
  4297. if ((mRange.upper < 0 && center < 0)
  4298. || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
  4299. {
  4300. QCPRange newRange;
  4301. newRange.lower = qPow(mRange.lower / center, factor) * center;
  4302. newRange.upper = qPow(mRange.upper / center, factor) * center;
  4303. if (QCPRange::validRange(newRange))
  4304. mRange = newRange.sanitizedForLogScale();
  4305. } else
  4306. qDebug() << Q_FUNC_INFO
  4307. << "Center of scaling operation doesn't lie in same logarithmic sign domain "
  4308. "as range:"
  4309. << center;
  4310. }
  4311. mCachedMarginValid = false;
  4312. emit rangeChanged(mRange);
  4313. emit rangeChanged(mRange, oldRange);
  4314. }
  4315. /*!
  4316. Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will
  4317. be done around the center of the current axis range.
  4318. For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs
  4319. plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the
  4320. axis rect has.
  4321. This is an operation that changes the range of this axis once, it doesn't fix the scale ratio
  4322. indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent
  4323. won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent
  4324. will follow.
  4325. */
  4326. void QCPAxis::setScaleRatio(const QCPAxis* otherAxis, double ratio)
  4327. {
  4328. int otherPixelSize, ownPixelSize;
  4329. if (otherAxis->orientation() == Qt::Horizontal)
  4330. otherPixelSize = otherAxis->axisRect()->width();
  4331. else
  4332. otherPixelSize = otherAxis->axisRect()->height();
  4333. if (orientation() == Qt::Horizontal)
  4334. ownPixelSize = axisRect()->width();
  4335. else
  4336. ownPixelSize = axisRect()->height();
  4337. double newRangeSize = ratio * otherAxis->range().size() * ownPixelSize / (double)otherPixelSize;
  4338. setRange(range().center(), newRangeSize, Qt::AlignCenter);
  4339. }
  4340. /*!
  4341. Changes the axis range such that all plottables associated with this axis are fully visible in
  4342. that dimension.
  4343. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  4344. */
  4345. void QCPAxis::rescale(bool onlyVisiblePlottables)
  4346. {
  4347. QList<QCPAbstractPlottable*> p = plottables();
  4348. QCPRange newRange;
  4349. bool haveRange = false;
  4350. for (int i = 0; i < p.size(); ++i) {
  4351. if (!p.at(i)->realVisibility() && onlyVisiblePlottables)
  4352. continue;
  4353. QCPRange plottableRange;
  4354. bool currentFoundRange;
  4355. QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth;
  4356. if (mScaleType == stLogarithmic)
  4357. signDomain = (mRange.upper < 0 ? QCPAbstractPlottable::sdNegative
  4358. : QCPAbstractPlottable::sdPositive);
  4359. if (p.at(i)->keyAxis() == this)
  4360. plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain);
  4361. else
  4362. plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain);
  4363. if (currentFoundRange) {
  4364. if (!haveRange)
  4365. newRange = plottableRange;
  4366. else
  4367. newRange.expand(plottableRange);
  4368. haveRange = true;
  4369. }
  4370. }
  4371. if (haveRange) {
  4372. if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only
  4373. // constant data in this axis dimension), shift current
  4374. // range to at least center the plottable
  4375. {
  4376. double center = (newRange.lower + newRange.upper)
  4377. * 0.5; // upper and lower should be equal anyway, but just to make sure,
  4378. // incase validRange returned false for other reason
  4379. if (mScaleType == stLinear) {
  4380. newRange.lower = center - mRange.size() / 2.0;
  4381. newRange.upper = center + mRange.size() / 2.0;
  4382. } else // mScaleType == stLogarithmic
  4383. {
  4384. newRange.lower = center / qSqrt(mRange.upper / mRange.lower);
  4385. newRange.upper = center * qSqrt(mRange.upper / mRange.lower);
  4386. }
  4387. }
  4388. setRange(newRange);
  4389. }
  4390. }
  4391. /*!
  4392. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  4393. */
  4394. double QCPAxis::pixelToCoord(double value) const
  4395. {
  4396. if (orientation() == Qt::Horizontal) {
  4397. if (mScaleType == stLinear) {
  4398. if (!mRangeReversed)
  4399. return (value - mAxisRect->left()) / (double)mAxisRect->width() * mRange.size()
  4400. + mRange.lower;
  4401. else
  4402. return -(value - mAxisRect->left()) / (double)mAxisRect->width() * mRange.size()
  4403. + mRange.upper;
  4404. } else // mScaleType == stLogarithmic
  4405. {
  4406. if (!mRangeReversed)
  4407. return qPow(mRange.upper / mRange.lower,
  4408. (value - mAxisRect->left()) / (double)mAxisRect->width())
  4409. * mRange.lower;
  4410. else
  4411. return qPow(mRange.upper / mRange.lower,
  4412. (mAxisRect->left() - value) / (double)mAxisRect->width())
  4413. * mRange.upper;
  4414. }
  4415. } else // orientation() == Qt::Vertical
  4416. {
  4417. if (mScaleType == stLinear) {
  4418. if (!mRangeReversed)
  4419. return (mAxisRect->bottom() - value) / (double)mAxisRect->height() * mRange.size()
  4420. + mRange.lower;
  4421. else
  4422. return -(mAxisRect->bottom() - value) / (double)mAxisRect->height() * mRange.size()
  4423. + mRange.upper;
  4424. } else // mScaleType == stLogarithmic
  4425. {
  4426. if (!mRangeReversed)
  4427. return qPow(mRange.upper / mRange.lower,
  4428. (mAxisRect->bottom() - value) / (double)mAxisRect->height())
  4429. * mRange.lower;
  4430. else
  4431. return qPow(mRange.upper / mRange.lower,
  4432. (value - mAxisRect->bottom()) / (double)mAxisRect->height())
  4433. * mRange.upper;
  4434. }
  4435. }
  4436. }
  4437. /*!
  4438. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  4439. */
  4440. double QCPAxis::coordToPixel(double value) const
  4441. {
  4442. if (orientation() == Qt::Horizontal) {
  4443. if (mScaleType == stLinear) {
  4444. if (!mRangeReversed)
  4445. return (value - mRange.lower) / mRange.size() * mAxisRect->width()
  4446. + mAxisRect->left();
  4447. else
  4448. return (mRange.upper - value) / mRange.size() * mAxisRect->width()
  4449. + mAxisRect->left();
  4450. } else // mScaleType == stLogarithmic
  4451. {
  4452. if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it
  4453. // outside visible range
  4454. return !mRangeReversed ? mAxisRect->right() + 200 : mAxisRect->left() - 200;
  4455. else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just
  4456. // draw it outside visible range
  4457. return !mRangeReversed ? mAxisRect->left() - 200 : mAxisRect->right() + 200;
  4458. else {
  4459. if (!mRangeReversed)
  4460. return baseLog(value / mRange.lower) / baseLog(mRange.upper / mRange.lower)
  4461. * mAxisRect->width()
  4462. + mAxisRect->left();
  4463. else
  4464. return baseLog(mRange.upper / value) / baseLog(mRange.upper / mRange.lower)
  4465. * mAxisRect->width()
  4466. + mAxisRect->left();
  4467. }
  4468. }
  4469. } else // orientation() == Qt::Vertical
  4470. {
  4471. if (mScaleType == stLinear) {
  4472. if (!mRangeReversed)
  4473. return mAxisRect->bottom()
  4474. - (value - mRange.lower) / mRange.size() * mAxisRect->height();
  4475. else
  4476. return mAxisRect->bottom()
  4477. - (mRange.upper - value) / mRange.size() * mAxisRect->height();
  4478. } else // mScaleType == stLogarithmic
  4479. {
  4480. if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it
  4481. // outside visible range
  4482. return !mRangeReversed ? mAxisRect->top() - 200 : mAxisRect->bottom() + 200;
  4483. else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just
  4484. // draw it outside visible range
  4485. return !mRangeReversed ? mAxisRect->bottom() + 200 : mAxisRect->top() - 200;
  4486. else {
  4487. if (!mRangeReversed)
  4488. return mAxisRect->bottom()
  4489. - baseLog(value / mRange.lower) / baseLog(mRange.upper / mRange.lower)
  4490. * mAxisRect->height();
  4491. else
  4492. return mAxisRect->bottom()
  4493. - baseLog(mRange.upper / value) / baseLog(mRange.upper / mRange.lower)
  4494. * mAxisRect->height();
  4495. }
  4496. }
  4497. }
  4498. }
  4499. /*!
  4500. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  4501. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  4502. function does not change the current selection state of the axis.
  4503. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  4504. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  4505. */
  4506. QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF& pos) const
  4507. {
  4508. if (!mVisible)
  4509. return spNone;
  4510. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  4511. return spAxis;
  4512. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  4513. return spTickLabels;
  4514. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  4515. return spAxisLabel;
  4516. else
  4517. return spNone;
  4518. }
  4519. /* inherits documentation from base class */
  4520. double QCPAxis::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  4521. {
  4522. if (!mParentPlot)
  4523. return -1;
  4524. SelectablePart part = getPartAt(pos);
  4525. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  4526. return -1;
  4527. if (details)
  4528. details->setValue(part);
  4529. return mParentPlot->selectionTolerance() * 0.99;
  4530. }
  4531. /*!
  4532. Returns a list of all the plottables that have this axis as key or value axis.
  4533. If you are only interested in plottables of type QCPGraph, see \ref graphs.
  4534. \see graphs, items
  4535. */
  4536. QList<QCPAbstractPlottable*> QCPAxis::plottables() const
  4537. {
  4538. QList<QCPAbstractPlottable*> result;
  4539. if (!mParentPlot)
  4540. return result;
  4541. for (int i = 0; i < mParentPlot->mPlottables.size(); ++i) {
  4542. if (mParentPlot->mPlottables.at(i)->keyAxis() == this
  4543. || mParentPlot->mPlottables.at(i)->valueAxis() == this)
  4544. result.append(mParentPlot->mPlottables.at(i));
  4545. }
  4546. return result;
  4547. }
  4548. /*!
  4549. Returns a list of all the graphs that have this axis as key or value axis.
  4550. \see plottables, items
  4551. */
  4552. QList<QCPGraph*> QCPAxis::graphs() const
  4553. {
  4554. QList<QCPGraph*> result;
  4555. if (!mParentPlot)
  4556. return result;
  4557. for (int i = 0; i < mParentPlot->mGraphs.size(); ++i) {
  4558. if (mParentPlot->mGraphs.at(i)->keyAxis() == this
  4559. || mParentPlot->mGraphs.at(i)->valueAxis() == this)
  4560. result.append(mParentPlot->mGraphs.at(i));
  4561. }
  4562. return result;
  4563. }
  4564. /*!
  4565. Returns a list of all the items that are associated with this axis. An item is considered
  4566. associated with an axis if at least one of its positions uses the axis as key or value axis.
  4567. \see plottables, graphs
  4568. */
  4569. QList<QCPAbstractItem*> QCPAxis::items() const
  4570. {
  4571. QList<QCPAbstractItem*> result;
  4572. if (!mParentPlot)
  4573. return result;
  4574. for (int itemId = 0; itemId < mParentPlot->mItems.size(); ++itemId) {
  4575. QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions();
  4576. for (int posId = 0; posId < positions.size(); ++posId) {
  4577. if (positions.at(posId)->keyAxis() == this
  4578. || positions.at(posId)->valueAxis() == this) {
  4579. result.append(mParentPlot->mItems.at(itemId));
  4580. break;
  4581. }
  4582. }
  4583. }
  4584. return result;
  4585. }
  4586. /*!
  4587. Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to
  4588. QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.)
  4589. */
  4590. QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side)
  4591. {
  4592. switch (side) {
  4593. case QCP::msLeft:
  4594. return atLeft;
  4595. case QCP::msRight:
  4596. return atRight;
  4597. case QCP::msTop:
  4598. return atTop;
  4599. case QCP::msBottom:
  4600. return atBottom;
  4601. default:
  4602. break;
  4603. }
  4604. qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side;
  4605. return atLeft;
  4606. }
  4607. /*!
  4608. Returns the axis type that describes the opposite axis of an axis with the specified \a type.
  4609. */
  4610. QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type)
  4611. {
  4612. switch (type) {
  4613. case atLeft:
  4614. return atRight;
  4615. break;
  4616. case atRight:
  4617. return atLeft;
  4618. break;
  4619. case atBottom:
  4620. return atTop;
  4621. break;
  4622. case atTop:
  4623. return atBottom;
  4624. break;
  4625. default:
  4626. qDebug() << Q_FUNC_INFO << "invalid axis type";
  4627. return atLeft;
  4628. break;
  4629. }
  4630. }
  4631. /*! \internal
  4632. This function is called to prepare the tick vector, sub tick vector and tick label vector. If
  4633. \ref setAutoTicks is set to true, appropriate tick values are determined automatically via \ref
  4634. generateAutoTicks. If it's set to false, the signal ticksRequest is emitted, which can be used to
  4635. provide external tick positions. Then the sub tick vectors and tick label vectors are created.
  4636. */
  4637. void QCPAxis::setupTickVectors()
  4638. {
  4639. if (!mParentPlot)
  4640. return;
  4641. if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0)
  4642. return;
  4643. // fill tick vectors, either by auto generating or by notifying user to fill the vectors himself
  4644. if (mAutoTicks) {
  4645. generateAutoTicks();
  4646. } else {
  4647. emit ticksRequest();
  4648. }
  4649. visibleTickBounds(mLowestVisibleTick, mHighestVisibleTick);
  4650. if (mTickVector.isEmpty()) {
  4651. mSubTickVector.clear();
  4652. return;
  4653. }
  4654. // generate subticks between ticks:
  4655. mSubTickVector.resize((mTickVector.size() - 1) * mSubTickCount);
  4656. if (mSubTickCount > 0) {
  4657. double subTickStep = 0;
  4658. double subTickPosition = 0;
  4659. int subTickIndex = 0;
  4660. bool done = false;
  4661. int lowTick = mLowestVisibleTick > 0 ? mLowestVisibleTick - 1 : mLowestVisibleTick;
  4662. int highTick = mHighestVisibleTick < mTickVector.size() - 1 ? mHighestVisibleTick + 1
  4663. : mHighestVisibleTick;
  4664. for (int i = lowTick + 1; i <= highTick; ++i) {
  4665. subTickStep = (mTickVector.at(i) - mTickVector.at(i - 1)) / (double)(mSubTickCount + 1);
  4666. for (int k = 1; k <= mSubTickCount; ++k) {
  4667. subTickPosition = mTickVector.at(i - 1) + k * subTickStep;
  4668. if (subTickPosition < mRange.lower)
  4669. continue;
  4670. if (subTickPosition > mRange.upper) {
  4671. done = true;
  4672. break;
  4673. }
  4674. mSubTickVector[subTickIndex] = subTickPosition;
  4675. subTickIndex++;
  4676. }
  4677. if (done)
  4678. break;
  4679. }
  4680. mSubTickVector.resize(subTickIndex);
  4681. }
  4682. // generate tick labels according to tick positions:
  4683. if (mAutoTickLabels) {
  4684. int vecsize = mTickVector.size();
  4685. mTickVectorLabels.resize(vecsize);
  4686. if (mTickLabelType == ltNumber) {
  4687. for (int i = mLowestVisibleTick; i <= mHighestVisibleTick; ++i)
  4688. mTickVectorLabels[i] = mParentPlot->locale().toString(
  4689. mTickVector.at(i), mNumberFormatChar.toLatin1(), mNumberPrecision);
  4690. } else if (mTickLabelType == ltDateTime) {
  4691. for (int i = mLowestVisibleTick; i <= mHighestVisibleTick; ++i) {
  4692. #if QT_VERSION \
  4693. < QT_VERSION_CHECK(4, 7, 0) // use fromMSecsSinceEpoch function if available, to gain sub-second
  4694. // accuracy on tick labels (e.g. for format "hh:mm:ss:zzz")
  4695. mTickVectorLabels[i] = mParentPlot->locale().toString(
  4696. QDateTime::fromTime_t(mTickVector.at(i)).toTimeSpec(mDateTimeSpec),
  4697. mDateTimeFormat);
  4698. #else
  4699. mTickVectorLabels[i] = mParentPlot->locale().toString(
  4700. QDateTime::fromMSecsSinceEpoch(mTickVector.at(i) * 1000)
  4701. .toTimeSpec(mDateTimeSpec),
  4702. mDateTimeFormat);
  4703. #endif
  4704. }
  4705. }
  4706. } else // mAutoTickLabels == false
  4707. {
  4708. if (mAutoTicks) // ticks generated automatically, but not ticklabels, so emit ticksRequest
  4709. // here for labels
  4710. {
  4711. emit ticksRequest();
  4712. }
  4713. // make sure provided tick label vector has correct (minimal) length:
  4714. if (mTickVectorLabels.size() < mTickVector.size())
  4715. mTickVectorLabels.resize(mTickVector.size());
  4716. }
  4717. }
  4718. /*! \internal
  4719. If \ref setAutoTicks is set to true, this function is called by \ref setupTickVectors to
  4720. generate reasonable tick positions (and subtick count). The algorithm tries to create
  4721. approximately <tt>mAutoTickCount</tt> ticks (set via \ref setAutoTickCount).
  4722. If the scale is logarithmic, \ref setAutoTickCount is ignored, and one tick is generated at every
  4723. power of the current logarithm base, set via \ref setScaleLogBase.
  4724. */
  4725. void QCPAxis::generateAutoTicks()
  4726. {
  4727. if (mScaleType == stLinear) {
  4728. if (mAutoTickStep) {
  4729. // Generate tick positions according to linear scaling:
  4730. mTickStep = mRange.size()
  4731. / (double)(mAutoTickCount
  4732. + 1e-10); // mAutoTickCount ticks on average, the small addition
  4733. // is to prevent jitter on exact integers
  4734. double magnitudeFactor =
  4735. qPow(10.0, qFloor(qLn(mTickStep)
  4736. / qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc.
  4737. double tickStepMantissa = mTickStep / magnitudeFactor;
  4738. if (tickStepMantissa < 5) {
  4739. // round digit after decimal point to 0.5
  4740. mTickStep = (int)(tickStepMantissa * 2) / 2.0 * magnitudeFactor;
  4741. } else {
  4742. // round to first digit in multiples of 2
  4743. mTickStep = (int)(tickStepMantissa / 2.0) * 2.0 * magnitudeFactor;
  4744. }
  4745. }
  4746. if (mAutoSubTicks)
  4747. mSubTickCount = calculateAutoSubTickCount(mTickStep);
  4748. // Generate tick positions according to mTickStep:
  4749. qint64 firstStep = floor(
  4750. mRange.lower / mTickStep); // do not use qFloor here, or we'll lose 64 bit precision
  4751. qint64 lastStep =
  4752. ceil(mRange.upper / mTickStep); // do not use qCeil here, or we'll lose 64 bit precision
  4753. int tickcount = lastStep - firstStep + 1;
  4754. if (tickcount < 0)
  4755. tickcount = 0;
  4756. mTickVector.resize(tickcount);
  4757. for (int i = 0; i < tickcount; ++i)
  4758. mTickVector[i] = (firstStep + i) * mTickStep;
  4759. } else // mScaleType == stLogarithmic
  4760. {
  4761. // Generate tick positions according to logbase scaling:
  4762. if (mRange.lower > 0 && mRange.upper > 0) // positive range
  4763. {
  4764. double lowerMag = basePow(qFloor(baseLog(mRange.lower)));
  4765. double currentMag = lowerMag;
  4766. mTickVector.clear();
  4767. mTickVector.append(currentMag);
  4768. while (
  4769. currentMag < mRange.upper
  4770. && currentMag
  4771. > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  4772. {
  4773. currentMag *= mScaleLogBase;
  4774. mTickVector.append(currentMag);
  4775. }
  4776. } else if (mRange.lower < 0 && mRange.upper < 0) // negative range
  4777. {
  4778. double lowerMag = -basePow(qCeil(baseLog(-mRange.lower)));
  4779. double currentMag = lowerMag;
  4780. mTickVector.clear();
  4781. mTickVector.append(currentMag);
  4782. while (
  4783. currentMag < mRange.upper
  4784. && currentMag
  4785. < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  4786. {
  4787. currentMag /= mScaleLogBase;
  4788. mTickVector.append(currentMag);
  4789. }
  4790. } else // invalid range for logarithmic scale, because lower and upper have different sign
  4791. {
  4792. mTickVector.clear();
  4793. qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << mRange.lower << "-"
  4794. << mRange.upper;
  4795. }
  4796. }
  4797. }
  4798. /*! \internal
  4799. Called by generateAutoTicks when \ref setAutoSubTicks is set to true. Depending on the \a
  4800. tickStep between two major ticks on the axis, a different number of sub ticks is appropriate. For
  4801. Example taking 4 sub ticks for a \a tickStep of 1 makes more sense than taking 5 sub ticks,
  4802. because this corresponds to a sub tick step of 0.2, instead of the less intuitive 0.16667. Note
  4803. that a subtick count of 4 means dividing the major tick step into 5 sections.
  4804. This is implemented by a hand made lookup for integer tick steps as well as fractional tick steps
  4805. with a fractional part of (approximately) 0.5. If a tick step is different (i.e. has no
  4806. fractional part close to 0.5), the currently set sub tick count (\ref setSubTickCount) is
  4807. returned.
  4808. */
  4809. int QCPAxis::calculateAutoSubTickCount(double tickStep) const
  4810. {
  4811. int result = mSubTickCount; // default to current setting, if no proper value can be found
  4812. // get mantissa of tickstep:
  4813. double magnitudeFactor =
  4814. qPow(10.0,
  4815. qFloor(qLn(tickStep) / qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc.
  4816. double tickStepMantissa = tickStep / magnitudeFactor;
  4817. // separate integer and fractional part of mantissa:
  4818. double epsilon = 0.01;
  4819. double intPartf;
  4820. int intPart;
  4821. double fracPart = modf(tickStepMantissa, &intPartf);
  4822. intPart = intPartf;
  4823. // handle cases with (almost) integer mantissa:
  4824. if (fracPart < epsilon || 1.0 - fracPart < epsilon) {
  4825. if (1.0 - fracPart < epsilon)
  4826. ++intPart;
  4827. switch (intPart) {
  4828. case 1:
  4829. result = 4;
  4830. break; // 1.0 -> 0.2 substep
  4831. case 2:
  4832. result = 3;
  4833. break; // 2.0 -> 0.5 substep
  4834. case 3:
  4835. result = 2;
  4836. break; // 3.0 -> 1.0 substep
  4837. case 4:
  4838. result = 3;
  4839. break; // 4.0 -> 1.0 substep
  4840. case 5:
  4841. result = 4;
  4842. break; // 5.0 -> 1.0 substep
  4843. case 6:
  4844. result = 2;
  4845. break; // 6.0 -> 2.0 substep
  4846. case 7:
  4847. result = 6;
  4848. break; // 7.0 -> 1.0 substep
  4849. case 8:
  4850. result = 3;
  4851. break; // 8.0 -> 2.0 substep
  4852. case 9:
  4853. result = 2;
  4854. break; // 9.0 -> 3.0 substep
  4855. }
  4856. } else {
  4857. // handle cases with significantly fractional mantissa:
  4858. if (qAbs(fracPart - 0.5) < epsilon) // *.5 mantissa
  4859. {
  4860. switch (intPart) {
  4861. case 1:
  4862. result = 2;
  4863. break; // 1.5 -> 0.5 substep
  4864. case 2:
  4865. result = 4;
  4866. break; // 2.5 -> 0.5 substep
  4867. case 3:
  4868. result = 4;
  4869. break; // 3.5 -> 0.7 substep
  4870. case 4:
  4871. result = 2;
  4872. break; // 4.5 -> 1.5 substep
  4873. case 5:
  4874. result = 4;
  4875. break; // 5.5 -> 1.1 substep (won't occur with autoTickStep from here on)
  4876. case 6:
  4877. result = 4;
  4878. break; // 6.5 -> 1.3 substep
  4879. case 7:
  4880. result = 2;
  4881. break; // 7.5 -> 2.5 substep
  4882. case 8:
  4883. result = 4;
  4884. break; // 8.5 -> 1.7 substep
  4885. case 9:
  4886. result = 4;
  4887. break; // 9.5 -> 1.9 substep
  4888. }
  4889. }
  4890. // if mantissa fraction isnt 0.0 or 0.5, don't bother finding good sub tick marks, leave
  4891. // default
  4892. }
  4893. return result;
  4894. }
  4895. /* inherits documentation from base class */
  4896. void QCPAxis::selectEvent(QMouseEvent* event, bool additive, const QVariant& details,
  4897. bool* selectionStateChanged)
  4898. {
  4899. Q_UNUSED(event)
  4900. SelectablePart part = details.value<SelectablePart>();
  4901. if (mSelectableParts.testFlag(part)) {
  4902. SelectableParts selBefore = mSelectedParts;
  4903. setSelectedParts(additive ? mSelectedParts ^ part : part);
  4904. if (selectionStateChanged)
  4905. *selectionStateChanged = mSelectedParts != selBefore;
  4906. }
  4907. }
  4908. /* inherits documentation from base class */
  4909. void QCPAxis::deselectEvent(bool* selectionStateChanged)
  4910. {
  4911. SelectableParts selBefore = mSelectedParts;
  4912. setSelectedParts(mSelectedParts & ~mSelectableParts);
  4913. if (selectionStateChanged)
  4914. *selectionStateChanged = mSelectedParts != selBefore;
  4915. }
  4916. /*! \internal
  4917. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  4918. before drawing axis lines.
  4919. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  4920. This function takes into account the local setting of the antialiasing flag as well as the
  4921. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  4922. QCustomPlot::setNotAntialiasedElements.
  4923. \see setAntialiased
  4924. */
  4925. void QCPAxis::applyDefaultAntialiasingHint(QCPPainter* painter) const
  4926. {
  4927. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  4928. }
  4929. /*! \internal
  4930. Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
  4931. */
  4932. void QCPAxis::draw(QCPPainter* painter)
  4933. {
  4934. const int lowTick = mLowestVisibleTick;
  4935. const int highTick = mHighestVisibleTick;
  4936. QVector<double>
  4937. subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  4938. QVector<double>
  4939. tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  4940. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  4941. tickPositions.reserve(highTick - lowTick + 1);
  4942. tickLabels.reserve(highTick - lowTick + 1);
  4943. subTickPositions.reserve(mSubTickVector.size());
  4944. if (mTicks) {
  4945. for (int i = lowTick; i <= highTick; ++i) {
  4946. tickPositions.append(coordToPixel(mTickVector.at(i)));
  4947. if (mTickLabels)
  4948. tickLabels.append(mTickVectorLabels.at(i));
  4949. }
  4950. if (mSubTickCount > 0) {
  4951. const int subTickCount = mSubTickVector.size();
  4952. for (int i = 0; i < subTickCount; ++i) // no need to check bounds because subticks are
  4953. // always only created inside current mRange
  4954. subTickPositions.append(coordToPixel(mSubTickVector.at(i)));
  4955. }
  4956. }
  4957. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the
  4958. // axis. Note that some axis painter properties are already set by direct feed-through with
  4959. // QCPAxis setters
  4960. mAxisPainter->type = mAxisType;
  4961. mAxisPainter->basePen = getBasePen();
  4962. mAxisPainter->labelFont = getLabelFont();
  4963. mAxisPainter->labelColor = getLabelColor();
  4964. mAxisPainter->label = mLabel;
  4965. mAxisPainter->substituteExponent =
  4966. mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber;
  4967. mAxisPainter->tickPen = getTickPen();
  4968. mAxisPainter->subTickPen = getSubTickPen();
  4969. mAxisPainter->tickLabelFont = getTickLabelFont();
  4970. mAxisPainter->tickLabelColor = getTickLabelColor();
  4971. mAxisPainter->axisRect = mAxisRect->rect();
  4972. mAxisPainter->viewportRect = mParentPlot->viewport();
  4973. mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic;
  4974. mAxisPainter->reversedEndings = mRangeReversed;
  4975. mAxisPainter->tickPositions = tickPositions;
  4976. mAxisPainter->tickLabels = tickLabels;
  4977. mAxisPainter->subTickPositions = subTickPositions;
  4978. mAxisPainter->draw(painter);
  4979. }
  4980. /*! \internal
  4981. Returns via \a lowIndex and \a highIndex, which ticks in the current tick vector are visible in
  4982. the current range. The return values are indices of the tick vector, not the positions of the
  4983. ticks themselves.
  4984. The actual use of this function is when an external tick vector is provided, since it might
  4985. exceed far beyond the currently displayed range, and would cause unnecessary calculations e.g. of
  4986. subticks.
  4987. If all ticks are outside the axis range, an inverted range is returned, i.e. highIndex will be
  4988. smaller than lowIndex. There is one case, where this function returns indices that are not really
  4989. visible in the current axis range: When the tick spacing is larger than the axis range size and
  4990. one tick is below the axis range and the next tick is already above the axis range. Because in
  4991. such cases it is usually desirable to know the tick pair, to draw proper subticks.
  4992. */
  4993. void QCPAxis::visibleTickBounds(int& lowIndex, int& highIndex) const
  4994. {
  4995. bool lowFound = false;
  4996. bool highFound = false;
  4997. lowIndex = 0;
  4998. highIndex = -1;
  4999. for (int i = 0; i < mTickVector.size(); ++i) {
  5000. if (mTickVector.at(i) >= mRange.lower) {
  5001. lowFound = true;
  5002. lowIndex = i;
  5003. break;
  5004. }
  5005. }
  5006. for (int i = mTickVector.size() - 1; i >= 0; --i) {
  5007. if (mTickVector.at(i) <= mRange.upper) {
  5008. highFound = true;
  5009. highIndex = i;
  5010. break;
  5011. }
  5012. }
  5013. if (!lowFound && highFound)
  5014. lowIndex = highIndex + 1;
  5015. else if (lowFound && !highFound)
  5016. highIndex = lowIndex - 1;
  5017. }
  5018. /*! \internal
  5019. A log function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic
  5020. scales with arbitrary log base. Uses the buffered mScaleLogBaseLogInv for faster calculation.
  5021. This is set to <tt>1.0/qLn(mScaleLogBase)</tt> in \ref setScaleLogBase.
  5022. \see basePow, setScaleLogBase, setScaleType
  5023. */
  5024. double QCPAxis::baseLog(double value) const
  5025. {
  5026. return qLn(value) * mScaleLogBaseLogInv;
  5027. }
  5028. /*! \internal
  5029. A power function with the base mScaleLogBase, used mostly for coordinate transforms in
  5030. logarithmic scales with arbitrary log base.
  5031. \see baseLog, setScaleLogBase, setScaleType
  5032. */
  5033. double QCPAxis::basePow(double value) const
  5034. {
  5035. return qPow(mScaleLogBase, value);
  5036. }
  5037. /*! \internal
  5038. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  5039. is either mSelectedBasePen or mBasePen.
  5040. */
  5041. QPen QCPAxis::getBasePen() const
  5042. {
  5043. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  5044. }
  5045. /*! \internal
  5046. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  5047. is either mSelectedTickPen or mTickPen.
  5048. */
  5049. QPen QCPAxis::getTickPen() const
  5050. {
  5051. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  5052. }
  5053. /*! \internal
  5054. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  5055. is either mSelectedSubTickPen or mSubTickPen.
  5056. */
  5057. QPen QCPAxis::getSubTickPen() const
  5058. {
  5059. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  5060. }
  5061. /*! \internal
  5062. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  5063. is either mSelectedTickLabelFont or mTickLabelFont.
  5064. */
  5065. QFont QCPAxis::getTickLabelFont() const
  5066. {
  5067. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  5068. }
  5069. /*! \internal
  5070. Returns the font that is used to draw the axis label. Depending on the selection state, this
  5071. is either mSelectedLabelFont or mLabelFont.
  5072. */
  5073. QFont QCPAxis::getLabelFont() const
  5074. {
  5075. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  5076. }
  5077. /*! \internal
  5078. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  5079. is either mSelectedTickLabelColor or mTickLabelColor.
  5080. */
  5081. QColor QCPAxis::getTickLabelColor() const
  5082. {
  5083. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  5084. }
  5085. /*! \internal
  5086. Returns the color that is used to draw the axis label. Depending on the selection state, this
  5087. is either mSelectedLabelColor or mLabelColor.
  5088. */
  5089. QColor QCPAxis::getLabelColor() const
  5090. {
  5091. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  5092. }
  5093. /*! \internal
  5094. Returns the appropriate outward margin for this axis. It is needed if \ref
  5095. QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref
  5096. atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom
  5097. margin and so forth. For the calculation, this function goes through similar steps as \ref draw,
  5098. so changing one function likely requires the modification of the other one as well.
  5099. The margin consists of the outward tick length, tick label padding, tick label size, label
  5100. padding, label size, and padding.
  5101. The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc.
  5102. unchanged are very fast.
  5103. */
  5104. int QCPAxis::calculateMargin()
  5105. {
  5106. if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to
  5107. // setVisible in QCPAxis
  5108. return 0;
  5109. if (mCachedMarginValid)
  5110. return mCachedMargin;
  5111. // run through similar steps as QCPAxis::draw, and caluclate margin needed to fit axis and its
  5112. // labels
  5113. int margin = 0;
  5114. int lowTick, highTick;
  5115. visibleTickBounds(lowTick, highTick);
  5116. QVector<double>
  5117. tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  5118. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  5119. tickPositions.reserve(highTick - lowTick + 1);
  5120. tickLabels.reserve(highTick - lowTick + 1);
  5121. if (mTicks) {
  5122. for (int i = lowTick; i <= highTick; ++i) {
  5123. tickPositions.append(coordToPixel(mTickVector.at(i)));
  5124. if (mTickLabels)
  5125. tickLabels.append(mTickVectorLabels.at(i));
  5126. }
  5127. }
  5128. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the
  5129. // size. Note that some axis painter properties are already set by direct feed-through with
  5130. // QCPAxis setters
  5131. mAxisPainter->type = mAxisType;
  5132. mAxisPainter->labelFont = getLabelFont();
  5133. mAxisPainter->label = mLabel;
  5134. mAxisPainter->tickLabelFont = mTickLabelFont;
  5135. mAxisPainter->axisRect = mAxisRect->rect();
  5136. mAxisPainter->viewportRect = mParentPlot->viewport();
  5137. mAxisPainter->tickPositions = tickPositions;
  5138. mAxisPainter->tickLabels = tickLabels;
  5139. margin += mAxisPainter->size();
  5140. margin += mPadding;
  5141. mCachedMargin = margin;
  5142. mCachedMarginValid = true;
  5143. return margin;
  5144. }
  5145. /* inherits documentation from base class */
  5146. QCP::Interaction QCPAxis::selectionCategory() const
  5147. {
  5148. return QCP::iSelectAxes;
  5149. }
  5150. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5151. //////////////////// QCPAxisPainterPrivate
  5152. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5153. /*! \class QCPAxisPainterPrivate
  5154. \internal
  5155. \brief (Private)
  5156. This is a private class and not part of the public QCustomPlot interface.
  5157. It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and
  5158. axis label. It also buffers the labels to reduce replot times. The parameters are configured by
  5159. directly accessing the public member variables.
  5160. */
  5161. /*!
  5162. Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every
  5163. redraw, to utilize the caching mechanisms.
  5164. */
  5165. QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot* parentPlot)
  5166. : type(QCPAxis::atLeft)
  5167. , basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap))
  5168. , lowerEnding(QCPLineEnding::esNone)
  5169. , upperEnding(QCPLineEnding::esNone)
  5170. , labelPadding(0)
  5171. , tickLabelPadding(0)
  5172. , tickLabelRotation(0)
  5173. , tickLabelSide(QCPAxis::lsOutside)
  5174. , substituteExponent(true)
  5175. , numberMultiplyCross(false)
  5176. , tickLengthIn(5)
  5177. , tickLengthOut(0)
  5178. , subTickLengthIn(2)
  5179. , subTickLengthOut(0)
  5180. , tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap))
  5181. , subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap))
  5182. , offset(0)
  5183. , abbreviateDecimalPowers(false)
  5184. , reversedEndings(false)
  5185. , mParentPlot(parentPlot)
  5186. , mLabelCache(16) // cache at most 16 (tick) labels
  5187. {}
  5188. QCPAxisPainterPrivate::~QCPAxisPainterPrivate()
  5189. {}
  5190. /*! \internal
  5191. Draws the axis with the specified \a painter.
  5192. The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set
  5193. here, too.
  5194. */
  5195. void QCPAxisPainterPrivate::draw(QCPPainter* painter)
  5196. {
  5197. QByteArray newHash = generateLabelParameterHash();
  5198. if (newHash != mLabelParameterHash) {
  5199. mLabelCache.clear();
  5200. mLabelParameterHash = newHash;
  5201. }
  5202. QPoint origin;
  5203. switch (type) {
  5204. case QCPAxis::atLeft:
  5205. origin = axisRect.bottomLeft() + QPoint(-offset, 0);
  5206. break;
  5207. case QCPAxis::atRight:
  5208. origin = axisRect.bottomRight() + QPoint(+offset, 0);
  5209. break;
  5210. case QCPAxis::atTop:
  5211. origin = axisRect.topLeft() + QPoint(0, -offset);
  5212. break;
  5213. case QCPAxis::atBottom:
  5214. origin = axisRect.bottomLeft() + QPoint(0, +offset);
  5215. break;
  5216. }
  5217. double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects
  5218. // baselines and ticks of top/right axes)
  5219. switch (type) {
  5220. case QCPAxis::atTop:
  5221. yCor = -1;
  5222. break;
  5223. case QCPAxis::atRight:
  5224. xCor = 1;
  5225. break;
  5226. default:
  5227. break;
  5228. }
  5229. int margin = 0;
  5230. // draw baseline:
  5231. QLineF baseLine;
  5232. painter->setPen(basePen);
  5233. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5234. baseLine.setPoints(origin + QPointF(xCor, yCor),
  5235. origin + QPointF(axisRect.width() + xCor, yCor));
  5236. else
  5237. baseLine.setPoints(origin + QPointF(xCor, yCor),
  5238. origin + QPointF(xCor, -axisRect.height() + yCor));
  5239. if (reversedEndings)
  5240. baseLine = QLineF(
  5241. baseLine.p2(),
  5242. baseLine.p1()); // won't make a difference for line itself, but for line endings later
  5243. painter->drawLine(baseLine);
  5244. // draw ticks:
  5245. if (!tickPositions.isEmpty()) {
  5246. painter->setPen(tickPen);
  5247. int tickDir =
  5248. (type == QCPAxis::atBottom || type == QCPAxis::atRight)
  5249. ? -1
  5250. : 1; // direction of ticks ("inward" is right for left axis and left for right axis)
  5251. if (QCPAxis::orientation(type) == Qt::Horizontal) {
  5252. for (int i = 0; i < tickPositions.size(); ++i)
  5253. painter->drawLine(
  5254. QLineF(tickPositions.at(i) + xCor, origin.y() - tickLengthOut * tickDir + yCor,
  5255. tickPositions.at(i) + xCor, origin.y() + tickLengthIn * tickDir + yCor));
  5256. } else {
  5257. for (int i = 0; i < tickPositions.size(); ++i)
  5258. painter->drawLine(
  5259. QLineF(origin.x() - tickLengthOut * tickDir + xCor, tickPositions.at(i) + yCor,
  5260. origin.x() + tickLengthIn * tickDir + xCor, tickPositions.at(i) + yCor));
  5261. }
  5262. }
  5263. // draw subticks:
  5264. if (!subTickPositions.isEmpty()) {
  5265. painter->setPen(subTickPen);
  5266. // direction of ticks ("inward" is right for left axis and left for right axis)
  5267. int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1;
  5268. if (QCPAxis::orientation(type) == Qt::Horizontal) {
  5269. for (int i = 0; i < subTickPositions.size(); ++i)
  5270. painter->drawLine(QLineF(
  5271. subTickPositions.at(i) + xCor, origin.y() - subTickLengthOut * tickDir + yCor,
  5272. subTickPositions.at(i) + xCor, origin.y() + subTickLengthIn * tickDir + yCor));
  5273. } else {
  5274. for (int i = 0; i < subTickPositions.size(); ++i)
  5275. painter->drawLine(QLineF(
  5276. origin.x() - subTickLengthOut * tickDir + xCor, subTickPositions.at(i) + yCor,
  5277. origin.x() + subTickLengthIn * tickDir + xCor, subTickPositions.at(i) + yCor));
  5278. }
  5279. }
  5280. margin += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  5281. // draw axis base endings:
  5282. bool antialiasingBackup = painter->antialiasing();
  5283. painter->setAntialiasing(
  5284. true); // always want endings to be antialiased, even if base and ticks themselves aren't
  5285. painter->setBrush(QBrush(basePen.color()));
  5286. QVector2D baseLineVector(baseLine.dx(), baseLine.dy());
  5287. if (lowerEnding.style() != QCPLineEnding::esNone)
  5288. lowerEnding.draw(painter,
  5289. QVector2D(baseLine.p1())
  5290. - baseLineVector.normalized() * lowerEnding.realLength()
  5291. * (lowerEnding.inverted() ? -1 : 1),
  5292. -baseLineVector);
  5293. if (upperEnding.style() != QCPLineEnding::esNone)
  5294. upperEnding.draw(painter,
  5295. QVector2D(baseLine.p2())
  5296. + baseLineVector.normalized() * upperEnding.realLength()
  5297. * (upperEnding.inverted() ? -1 : 1),
  5298. baseLineVector);
  5299. painter->setAntialiasing(antialiasingBackup);
  5300. // tick labels:
  5301. QRect oldClipRect;
  5302. if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect
  5303. {
  5304. oldClipRect = painter->clipRegion().boundingRect();
  5305. painter->setClipRect(axisRect);
  5306. }
  5307. QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label
  5308. if (!tickLabels.isEmpty()) {
  5309. if (tickLabelSide == QCPAxis::lsOutside)
  5310. margin += tickLabelPadding;
  5311. painter->setFont(tickLabelFont);
  5312. painter->setPen(QPen(tickLabelColor));
  5313. const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size());
  5314. int distanceToAxis = margin;
  5315. if (tickLabelSide == QCPAxis::lsInside)
  5316. distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn) + tickLabelPadding);
  5317. for (int i = 0; i < maxLabelIndex; ++i)
  5318. placeTickLabel(painter, tickPositions.at(i), distanceToAxis, tickLabels.at(i),
  5319. &tickLabelsSize);
  5320. if (tickLabelSide == QCPAxis::lsOutside)
  5321. margin += (QCPAxis::orientation(type) == Qt::Horizontal) ? tickLabelsSize.height()
  5322. : tickLabelsSize.width();
  5323. }
  5324. if (tickLabelSide == QCPAxis::lsInside)
  5325. painter->setClipRect(oldClipRect);
  5326. // axis label:
  5327. QRect labelBounds;
  5328. if (!label.isEmpty()) {
  5329. margin += labelPadding;
  5330. painter->setFont(labelFont);
  5331. painter->setPen(QPen(labelColor));
  5332. labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label);
  5333. if (type == QCPAxis::atLeft) {
  5334. QTransform oldTransform = painter->transform();
  5335. painter->translate((origin.x() - margin - labelBounds.height()), origin.y());
  5336. painter->rotate(-90);
  5337. painter->drawText(0, 0, axisRect.height(), labelBounds.height(),
  5338. Qt::TextDontClip | Qt::AlignCenter, label);
  5339. painter->setTransform(oldTransform);
  5340. } else if (type == QCPAxis::atRight) {
  5341. QTransform oldTransform = painter->transform();
  5342. painter->translate((origin.x() + margin + labelBounds.height()),
  5343. origin.y() - axisRect.height());
  5344. painter->rotate(90);
  5345. painter->drawText(0, 0, axisRect.height(), labelBounds.height(),
  5346. Qt::TextDontClip | Qt::AlignCenter, label);
  5347. painter->setTransform(oldTransform);
  5348. } else if (type == QCPAxis::atTop)
  5349. painter->drawText(origin.x(), origin.y() - margin - labelBounds.height(),
  5350. axisRect.width(), labelBounds.height(),
  5351. Qt::TextDontClip | Qt::AlignCenter, label);
  5352. else if (type == QCPAxis::atBottom)
  5353. painter->drawText(origin.x(), origin.y() + margin, axisRect.width(),
  5354. labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  5355. }
  5356. // set selection boxes:
  5357. int selectionTolerance = 0;
  5358. if (mParentPlot)
  5359. selectionTolerance = mParentPlot->selectionTolerance();
  5360. else
  5361. qDebug() << Q_FUNC_INFO << "mParentPlot is null";
  5362. int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance);
  5363. int selAxisInSize = selectionTolerance;
  5364. int selTickLabelSize;
  5365. int selTickLabelOffset;
  5366. if (tickLabelSide == QCPAxis::lsOutside) {
  5367. selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height()
  5368. : tickLabelsSize.width());
  5369. selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut) + tickLabelPadding;
  5370. } else {
  5371. selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height()
  5372. : tickLabelsSize.width());
  5373. selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn) + tickLabelPadding);
  5374. }
  5375. int selLabelSize = labelBounds.height();
  5376. int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)
  5377. + (!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside
  5378. ? tickLabelPadding + selTickLabelSize
  5379. : 0)
  5380. + labelPadding;
  5381. if (type == QCPAxis::atLeft) {
  5382. mAxisSelectionBox.setCoords(origin.x() - selAxisOutSize, axisRect.top(),
  5383. origin.x() + selAxisInSize, axisRect.bottom());
  5384. mTickLabelsSelectionBox.setCoords(origin.x() - selTickLabelOffset - selTickLabelSize,
  5385. axisRect.top(), origin.x() - selTickLabelOffset,
  5386. axisRect.bottom());
  5387. mLabelSelectionBox.setCoords(origin.x() - selLabelOffset - selLabelSize, axisRect.top(),
  5388. origin.x() - selLabelOffset, axisRect.bottom());
  5389. } else if (type == QCPAxis::atRight) {
  5390. mAxisSelectionBox.setCoords(origin.x() - selAxisInSize, axisRect.top(),
  5391. origin.x() + selAxisOutSize, axisRect.bottom());
  5392. mTickLabelsSelectionBox.setCoords(origin.x() + selTickLabelOffset + selTickLabelSize,
  5393. axisRect.top(), origin.x() + selTickLabelOffset,
  5394. axisRect.bottom());
  5395. mLabelSelectionBox.setCoords(origin.x() + selLabelOffset + selLabelSize, axisRect.top(),
  5396. origin.x() + selLabelOffset, axisRect.bottom());
  5397. } else if (type == QCPAxis::atTop) {
  5398. mAxisSelectionBox.setCoords(axisRect.left(), origin.y() - selAxisOutSize, axisRect.right(),
  5399. origin.y() + selAxisInSize);
  5400. mTickLabelsSelectionBox.setCoords(axisRect.left(),
  5401. origin.y() - selTickLabelOffset - selTickLabelSize,
  5402. axisRect.right(), origin.y() - selTickLabelOffset);
  5403. mLabelSelectionBox.setCoords(axisRect.left(), origin.y() - selLabelOffset - selLabelSize,
  5404. axisRect.right(), origin.y() - selLabelOffset);
  5405. } else if (type == QCPAxis::atBottom) {
  5406. mAxisSelectionBox.setCoords(axisRect.left(), origin.y() - selAxisInSize, axisRect.right(),
  5407. origin.y() + selAxisOutSize);
  5408. mTickLabelsSelectionBox.setCoords(axisRect.left(),
  5409. origin.y() + selTickLabelOffset + selTickLabelSize,
  5410. axisRect.right(), origin.y() + selTickLabelOffset);
  5411. mLabelSelectionBox.setCoords(axisRect.left(), origin.y() + selLabelOffset + selLabelSize,
  5412. axisRect.right(), origin.y() + selLabelOffset);
  5413. }
  5414. mAxisSelectionBox = mAxisSelectionBox.normalized();
  5415. mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized();
  5416. mLabelSelectionBox = mLabelSelectionBox.normalized();
  5417. // draw hitboxes for debug purposes:
  5418. // painter->setBrush(Qt::NoBrush);
  5419. // painter->drawRects(QVector<QRect>() << mAxisSelectionBox << mTickLabelsSelectionBox <<
  5420. // mLabelSelectionBox);
  5421. }
  5422. /*! \internal
  5423. Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
  5424. direction) needed to fit the axis.
  5425. */
  5426. int QCPAxisPainterPrivate::size() const
  5427. {
  5428. int result = 0;
  5429. // get length of tick marks pointing outwards:
  5430. if (!tickPositions.isEmpty())
  5431. result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  5432. // calculate size of tick labels:
  5433. if (tickLabelSide == QCPAxis::lsOutside) {
  5434. QSize tickLabelsSize(0, 0);
  5435. if (!tickLabels.isEmpty()) {
  5436. for (int i = 0; i < tickLabels.size(); ++i)
  5437. getMaxTickLabelSize(tickLabelFont, tickLabels.at(i), &tickLabelsSize);
  5438. result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height()
  5439. : tickLabelsSize.width();
  5440. result += tickLabelPadding;
  5441. }
  5442. }
  5443. // calculate size of axis label (only height needed, because left/right labels are rotated by 90
  5444. // degrees):
  5445. if (!label.isEmpty()) {
  5446. QFontMetrics fontMetrics(labelFont);
  5447. QRect bounds;
  5448. bounds = fontMetrics.boundingRect(
  5449. 0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
  5450. result += bounds.height() + labelPadding;
  5451. }
  5452. return result;
  5453. }
  5454. /*! \internal
  5455. Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
  5456. method is called automatically in \ref draw, if any parameters have changed that invalidate the
  5457. cached labels, such as font, color, etc.
  5458. */
  5459. void QCPAxisPainterPrivate::clearCache()
  5460. {
  5461. mLabelCache.clear();
  5462. }
  5463. /*! \internal
  5464. Returns a hash that allows uniquely identifying whether the label parameters have changed such
  5465. that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
  5466. return value of this method hasn't changed since the last redraw, the respective label parameters
  5467. haven't changed and cached labels may be used.
  5468. */
  5469. QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const
  5470. {
  5471. QByteArray result;
  5472. result.append(QByteArray::number(tickLabelRotation));
  5473. result.append(QByteArray::number((int)tickLabelSide));
  5474. result.append(QByteArray::number((int)substituteExponent));
  5475. result.append(QByteArray::number((int)numberMultiplyCross));
  5476. result.append(tickLabelColor.name().toLatin1()
  5477. + QByteArray::number(tickLabelColor.alpha(), 16));
  5478. result.append(tickLabelFont.toString().toLatin1());
  5479. return result;
  5480. }
  5481. /*! \internal
  5482. Draws a single tick label with the provided \a painter, utilizing the internal label cache to
  5483. significantly speed up drawing of labels that were drawn in previous calls. The tick label is
  5484. always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
  5485. pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
  5486. for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
  5487. at which the label should be drawn.
  5488. In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
  5489. largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
  5490. drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
  5491. tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
  5492. holds.
  5493. The label is drawn with the font and pen that are currently set on the \a painter. To draw
  5494. superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
  5495. getTickLabelData).
  5496. */
  5497. void QCPAxisPainterPrivate::placeTickLabel(QCPPainter* painter, double position, int distanceToAxis,
  5498. const QString& text, QSize* tickLabelsSize)
  5499. {
  5500. // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
  5501. if (text.isEmpty())
  5502. return;
  5503. QSize finalSize;
  5504. QPointF labelAnchor;
  5505. switch (type) {
  5506. case QCPAxis::atLeft:
  5507. labelAnchor = QPointF(axisRect.left() - distanceToAxis - offset, position);
  5508. break;
  5509. case QCPAxis::atRight:
  5510. labelAnchor = QPointF(axisRect.right() + distanceToAxis + offset, position);
  5511. break;
  5512. case QCPAxis::atTop:
  5513. labelAnchor = QPointF(position, axisRect.top() - distanceToAxis - offset);
  5514. break;
  5515. case QCPAxis::atBottom:
  5516. labelAnchor = QPointF(position, axisRect.bottom() + distanceToAxis + offset);
  5517. break;
  5518. }
  5519. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels)
  5520. && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
  5521. {
  5522. CachedLabel* cachedLabel = mLabelCache.take(text); // attempt to get label from cache
  5523. if (!cachedLabel) // no cached label existed, create it
  5524. {
  5525. cachedLabel = new CachedLabel;
  5526. TickLabelData labelData = getTickLabelData(painter->font(), text);
  5527. cachedLabel->offset =
  5528. getTickLabelDrawOffset(labelData) + labelData.rotatedTotalBounds.topLeft();
  5529. cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
  5530. cachedLabel->pixmap.fill(Qt::transparent);
  5531. QCPPainter cachePainter(&cachedLabel->pixmap);
  5532. cachePainter.setPen(painter->pen());
  5533. drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(),
  5534. -labelData.rotatedTotalBounds.topLeft().y(), labelData);
  5535. }
  5536. // if label would be partly clipped by widget border on sides, don't draw it (only for
  5537. // outside tick labels):
  5538. bool labelClippedByBorder = false;
  5539. if (tickLabelSide == QCPAxis::lsOutside) {
  5540. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5541. labelClippedByBorder =
  5542. labelAnchor.x() + cachedLabel->offset.x() + cachedLabel->pixmap.width()
  5543. > viewportRect.right()
  5544. || labelAnchor.x() + cachedLabel->offset.x() < viewportRect.left();
  5545. else
  5546. labelClippedByBorder =
  5547. labelAnchor.y() + cachedLabel->offset.y() + cachedLabel->pixmap.height()
  5548. > viewportRect.bottom()
  5549. || labelAnchor.y() + cachedLabel->offset.y() < viewportRect.top();
  5550. }
  5551. if (!labelClippedByBorder) {
  5552. painter->drawPixmap(labelAnchor + cachedLabel->offset, cachedLabel->pixmap);
  5553. finalSize = cachedLabel->pixmap.size();
  5554. }
  5555. mLabelCache.insert(
  5556. text,
  5557. cachedLabel); // return label to cache or insert for the first time if newly created
  5558. } else // label caching disabled, draw text directly on surface:
  5559. {
  5560. TickLabelData labelData = getTickLabelData(painter->font(), text);
  5561. QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData);
  5562. // if label would be partly clipped by widget border on sides, don't draw it (only for
  5563. // outside tick labels):
  5564. bool labelClippedByBorder = false;
  5565. if (tickLabelSide == QCPAxis::lsOutside) {
  5566. if (QCPAxis::orientation(type) == Qt::Horizontal)
  5567. labelClippedByBorder = finalPosition.x()
  5568. + (labelData.rotatedTotalBounds.width()
  5569. + labelData.rotatedTotalBounds.left())
  5570. > viewportRect.right()
  5571. || finalPosition.x() + labelData.rotatedTotalBounds.left()
  5572. < viewportRect.left();
  5573. else
  5574. labelClippedByBorder =
  5575. finalPosition.y()
  5576. + (labelData.rotatedTotalBounds.height()
  5577. + labelData.rotatedTotalBounds.top())
  5578. > viewportRect.bottom()
  5579. || finalPosition.y() + labelData.rotatedTotalBounds.top() < viewportRect.top();
  5580. }
  5581. if (!labelClippedByBorder) {
  5582. drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData);
  5583. finalSize = labelData.rotatedTotalBounds.size();
  5584. }
  5585. }
  5586. // expand passed tickLabelsSize if current tick label is larger:
  5587. if (finalSize.width() > tickLabelsSize->width())
  5588. tickLabelsSize->setWidth(finalSize.width());
  5589. if (finalSize.height() > tickLabelsSize->height())
  5590. tickLabelsSize->setHeight(finalSize.height());
  5591. }
  5592. /*! \internal
  5593. This is a \ref placeTickLabel helper function.
  5594. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
  5595. y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
  5596. directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
  5597. QCP::phCacheLabels plotting hint is not set.
  5598. */
  5599. void QCPAxisPainterPrivate::drawTickLabel(QCPPainter* painter, double x, double y,
  5600. const TickLabelData& labelData) const
  5601. {
  5602. // backup painter settings that we're about to change:
  5603. QTransform oldTransform = painter->transform();
  5604. QFont oldFont = painter->font();
  5605. // transform painter to position/rotation:
  5606. painter->translate(x, y);
  5607. if (!qFuzzyIsNull(tickLabelRotation))
  5608. painter->rotate(tickLabelRotation);
  5609. // draw text:
  5610. if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used
  5611. {
  5612. painter->setFont(labelData.baseFont);
  5613. painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
  5614. painter->setFont(labelData.expFont);
  5615. painter->drawText(labelData.baseBounds.width() + 1, 0, labelData.expBounds.width(),
  5616. labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
  5617. } else {
  5618. painter->setFont(labelData.baseFont);
  5619. painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(),
  5620. Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
  5621. }
  5622. // reset painter settings to what it was before:
  5623. painter->setTransform(oldTransform);
  5624. painter->setFont(oldFont);
  5625. }
  5626. /*! \internal
  5627. This is a \ref placeTickLabel helper function.
  5628. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
  5629. processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
  5630. exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
  5631. */
  5632. QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(
  5633. const QFont& font, const QString& text) const
  5634. {
  5635. TickLabelData result;
  5636. // determine whether beautiful decimal powers should be used
  5637. bool useBeautifulPowers = false;
  5638. int ePos = -1; // first index of exponent part, text before that will be basePart, text until
  5639. // eLast will be expPart
  5640. int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
  5641. if (substituteExponent) {
  5642. ePos = text.indexOf(QLatin1Char('e'));
  5643. if (ePos > 0 && text.at(ePos - 1).isDigit()) {
  5644. eLast = ePos;
  5645. while (eLast + 1 < text.size()
  5646. && (text.at(eLast + 1) == QLatin1Char('+')
  5647. || text.at(eLast + 1) == QLatin1Char('-') || text.at(eLast + 1).isDigit()))
  5648. ++eLast;
  5649. if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as
  5650. // beautifiable power
  5651. useBeautifulPowers = true;
  5652. }
  5653. }
  5654. // calculate text bounding rects and do string preparation for beautiful decimal powers:
  5655. result.baseFont = font;
  5656. if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that
  5657. // case we can't do correction in next line
  5658. result.baseFont.setPointSizeF(
  5659. result.baseFont.pointSizeF()
  5660. + 0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the
  5661. // results oscillate due to internal rounding
  5662. if (useBeautifulPowers) {
  5663. // split text into parts of number/symbol that will be drawn normally and part that will be
  5664. // drawn as exponent:
  5665. result.basePart = text.left(ePos);
  5666. // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and
  5667. // decimal base:
  5668. if (abbreviateDecimalPowers && result.basePart == QLatin1String("1"))
  5669. result.basePart = QLatin1String("10");
  5670. else
  5671. result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183)))
  5672. + QLatin1String("10");
  5673. result.expPart = text.mid(ePos + 1);
  5674. // clip "+" and leading zeros off expPart:
  5675. while (result.expPart.length() > 2
  5676. && result.expPart.at(1)
  5677. == QLatin1Char(
  5678. '0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
  5679. result.expPart.remove(1, 1);
  5680. if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
  5681. result.expPart.remove(0, 1);
  5682. // prepare smaller font for exponent:
  5683. result.expFont = font;
  5684. if (result.expFont.pointSize() > 0)
  5685. result.expFont.setPointSize(result.expFont.pointSize() * 0.75);
  5686. else
  5687. result.expFont.setPixelSize(result.expFont.pixelSize() * 0.75);
  5688. // calculate bounding rects of base part, exponent part and total one:
  5689. result.baseBounds = QFontMetrics(result.baseFont)
  5690. .boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
  5691. result.expBounds =
  5692. QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
  5693. result.totalBounds = result.baseBounds.adjusted(
  5694. 0, 0, result.expBounds.width() + 2,
  5695. 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel)
  5696. // and an extra pixel to include AA
  5697. } else // useBeautifulPowers == false
  5698. {
  5699. result.basePart = text;
  5700. result.totalBounds =
  5701. QFontMetrics(result.baseFont)
  5702. .boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
  5703. }
  5704. result.totalBounds.moveTopLeft(
  5705. QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was
  5706. // created, to make further processing simpler
  5707. // calculate possibly different bounding rect after rotation:
  5708. result.rotatedTotalBounds = result.totalBounds;
  5709. if (!qFuzzyIsNull(tickLabelRotation)) {
  5710. QTransform transform;
  5711. transform.rotate(tickLabelRotation);
  5712. result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds);
  5713. }
  5714. return result;
  5715. }
  5716. /*! \internal
  5717. This is a \ref placeTickLabel helper function.
  5718. Calculates the offset at which the top left corner of the specified tick label shall be drawn.
  5719. The offset is relative to a point right next to the tick the label belongs to.
  5720. This function is thus responsible for e.g. centering tick labels under ticks and positioning them
  5721. appropriately when they are rotated.
  5722. */
  5723. QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData& labelData) const
  5724. {
  5725. /*
  5726. calculate label offset from base point at tick (non-trivial, for best visual appearance):
  5727. short explanation for bottom axis: The anchor, i.e. the point in the label that is placed
  5728. horizontally under the corresponding tick is always on the label side that is closer to the
  5729. axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height
  5730. is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text
  5731. will be centered under the tick (i.e. displaced horizontally by half its height). At the same
  5732. time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick
  5733. labels.
  5734. */
  5735. bool doRotation = !qFuzzyIsNull(tickLabelRotation);
  5736. bool flip = qFuzzyCompare(
  5737. qAbs(tickLabelRotation),
  5738. 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes.
  5739. double radians = tickLabelRotation / 180.0 * M_PI;
  5740. int x = 0, y = 0;
  5741. if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside)
  5742. || (type == QCPAxis::atRight
  5743. && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label
  5744. {
  5745. if (doRotation) {
  5746. if (tickLabelRotation > 0) {
  5747. x = -qCos(radians) * labelData.totalBounds.width();
  5748. y = flip ? -labelData.totalBounds.width() / 2.0
  5749. : -qSin(radians) * labelData.totalBounds.width()
  5750. - qCos(radians) * labelData.totalBounds.height() / 2.0;
  5751. } else {
  5752. x = -qCos(-radians) * labelData.totalBounds.width()
  5753. - qSin(-radians) * labelData.totalBounds.height();
  5754. y = flip ? +labelData.totalBounds.width() / 2.0
  5755. : +qSin(-radians) * labelData.totalBounds.width()
  5756. - qCos(-radians) * labelData.totalBounds.height() / 2.0;
  5757. }
  5758. } else {
  5759. x = -labelData.totalBounds.width();
  5760. y = -labelData.totalBounds.height() / 2.0;
  5761. }
  5762. } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside)
  5763. || (type == QCPAxis::atLeft
  5764. && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label
  5765. {
  5766. if (doRotation) {
  5767. if (tickLabelRotation > 0) {
  5768. x = +qSin(radians) * labelData.totalBounds.height();
  5769. y = flip ? -labelData.totalBounds.width() / 2.0
  5770. : -qCos(radians) * labelData.totalBounds.height() / 2.0;
  5771. } else {
  5772. x = 0;
  5773. y = flip ? +labelData.totalBounds.width() / 2.0
  5774. : -qCos(-radians) * labelData.totalBounds.height() / 2.0;
  5775. }
  5776. } else {
  5777. x = 0;
  5778. y = -labelData.totalBounds.height() / 2.0;
  5779. }
  5780. } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside)
  5781. || (type == QCPAxis::atBottom
  5782. && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label
  5783. {
  5784. if (doRotation) {
  5785. if (tickLabelRotation > 0) {
  5786. x = -qCos(radians) * labelData.totalBounds.width()
  5787. + qSin(radians) * labelData.totalBounds.height() / 2.0;
  5788. y = -qSin(radians) * labelData.totalBounds.width()
  5789. - qCos(radians) * labelData.totalBounds.height();
  5790. } else {
  5791. x = -qSin(-radians) * labelData.totalBounds.height() / 2.0;
  5792. y = -qCos(-radians) * labelData.totalBounds.height();
  5793. }
  5794. } else {
  5795. x = -labelData.totalBounds.width() / 2.0;
  5796. y = -labelData.totalBounds.height();
  5797. }
  5798. } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside)
  5799. || (type == QCPAxis::atTop
  5800. && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label
  5801. {
  5802. if (doRotation) {
  5803. if (tickLabelRotation > 0) {
  5804. x = +qSin(radians) * labelData.totalBounds.height() / 2.0;
  5805. y = 0;
  5806. } else {
  5807. x = -qCos(-radians) * labelData.totalBounds.width()
  5808. - qSin(-radians) * labelData.totalBounds.height() / 2.0;
  5809. y = +qSin(-radians) * labelData.totalBounds.width();
  5810. }
  5811. } else {
  5812. x = -labelData.totalBounds.width() / 2.0;
  5813. y = 0;
  5814. }
  5815. }
  5816. return QPointF(x, y);
  5817. }
  5818. /*! \internal
  5819. Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
  5820. to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
  5821. margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
  5822. smaller width/height.
  5823. */
  5824. void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont& font, const QString& text,
  5825. QSize* tickLabelsSize) const
  5826. {
  5827. // note: this function must return the same tick label sizes as the placeTickLabel function.
  5828. QSize finalSize;
  5829. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels)
  5830. && mLabelCache.contains(text)) // label caching enabled and have cached label
  5831. {
  5832. const CachedLabel* cachedLabel = mLabelCache.object(text);
  5833. finalSize = cachedLabel->pixmap.size();
  5834. } else // label caching disabled or no label with this text cached:
  5835. {
  5836. TickLabelData labelData = getTickLabelData(font, text);
  5837. finalSize = labelData.rotatedTotalBounds.size();
  5838. }
  5839. // expand passed tickLabelsSize if current tick label is larger:
  5840. if (finalSize.width() > tickLabelsSize->width())
  5841. tickLabelsSize->setWidth(finalSize.width());
  5842. if (finalSize.height() > tickLabelsSize->height())
  5843. tickLabelsSize->setHeight(finalSize.height());
  5844. }
  5845. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5846. //////////////////// QCPAbstractPlottable
  5847. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5848. /*! \class QCPAbstractPlottable
  5849. \brief The abstract base class for all data representing objects in a plot.
  5850. It defines a very basic interface like name, pen, brush, visibility etc. Since this class is
  5851. abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to
  5852. create new ways of displaying data (see "Creating own plottables" below).
  5853. All further specifics are in the subclasses, for example:
  5854. \li A normal graph with possibly a line, scatter points and error bars: \ref QCPGraph
  5855. (typically created with \ref QCustomPlot::addGraph)
  5856. \li A parametric curve: \ref QCPCurve
  5857. \li A bar chart: \ref QCPBars
  5858. \li A statistical box plot: \ref QCPStatisticalBox
  5859. \li A color encoded two-dimensional map: \ref QCPColorMap
  5860. \li An OHLC/Candlestick chart: \ref QCPFinancial
  5861. \section plottables-subclassing Creating own plottables
  5862. To create an own plottable, you implement a subclass of QCPAbstractPlottable. These are the pure
  5863. virtual functions, you must implement:
  5864. \li \ref clearData
  5865. \li \ref selectTest
  5866. \li \ref draw
  5867. \li \ref drawLegendIcon
  5868. \li \ref getKeyRange
  5869. \li \ref getValueRange
  5870. See the documentation of those functions for what they need to do.
  5871. For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot
  5872. coordinates to pixel coordinates. This function is quite convenient, because it takes the
  5873. orientation of the key and value axes into account for you (x and y are swapped when the key axis
  5874. is vertical and the value axis horizontal). If you are worried about performance (i.e. you need
  5875. to translate many points in a loop like QCPGraph), you can directly use \ref
  5876. QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis
  5877. yourself.
  5878. Here are some important members you inherit from QCPAbstractPlottable:
  5879. <table>
  5880. <tr>
  5881. <td>QCustomPlot *\b mParentPlot</td>
  5882. <td>A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that
  5883. are passed in the constructor.</td>
  5884. </tr><tr>
  5885. <td>QString \b mName</td>
  5886. <td>The name of the plottable.</td>
  5887. </tr><tr>
  5888. <td>QPen \b mPen</td>
  5889. <td>The generic pen of the plottable. You should use this pen for the most prominent data
  5890. representing lines in the plottable (e.g QCPGraph uses this pen for its graph lines and
  5891. scatters)</td>
  5892. </tr><tr>
  5893. <td>QPen \b mSelectedPen</td>
  5894. <td>The generic pen that should be used when the plottable is selected (hint: \ref mainPen gives
  5895. you the right pen, depending on selection state).</td>
  5896. </tr><tr>
  5897. <td>QBrush \b mBrush</td>
  5898. <td>The generic brush of the plottable. You should use this brush for the most prominent
  5899. fillable structures in the plottable (e.g. QCPGraph uses this brush to control filling under the
  5900. graph)</td>
  5901. </tr><tr>
  5902. <td>QBrush \b mSelectedBrush</td>
  5903. <td>The generic brush that should be used when the plottable is selected (hint: \ref mainBrush
  5904. gives you the right brush, depending on selection state).</td>
  5905. </tr><tr>
  5906. <td>QPointer<QCPAxis>\b mKeyAxis, \b mValueAxis</td>
  5907. <td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel
  5908. functions to translate coordinates to pixels in either the key or value dimension. Make sure to
  5909. check whether the pointer is null before using it. If one of the axes is null, don't draw the
  5910. plottable.</td>
  5911. </tr><tr>
  5912. <td>bool \b mSelected</td>
  5913. <td>indicates whether the plottable is selected or not.</td>
  5914. </tr>
  5915. </table>
  5916. */
  5917. /* start of documentation of pure virtual functions */
  5918. /*! \fn void QCPAbstractPlottable::clearData() = 0
  5919. Clears all data in the plottable.
  5920. */
  5921. /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0
  5922. \internal
  5923. called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation
  5924. of this plottable inside \a rect, next to the plottable name.
  5925. The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't
  5926. appear outside the legend icon border.
  5927. */
  5928. /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, SignDomain inSignDomain) const
  5929. = 0 \internal
  5930. called by rescaleAxes functions to get the full data key bounds. For logarithmic plots, one can
  5931. set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the
  5932. returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain
  5933. to \ref sdNegative and all positive points will be ignored for range calculation. For no
  5934. restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output
  5935. parameter that indicates whether a range could be found or not. If this is false, you shouldn't
  5936. use the returned range (e.g. no points in data).
  5937. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  5938. this function may have size zero, which wouldn't count as a valid range.
  5939. \see rescaleAxes, getValueRange
  5940. */
  5941. /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, SignDomain inSignDomain)
  5942. const = 0 \internal
  5943. called by rescaleAxes functions to get the full data value bounds. For logarithmic plots, one can
  5944. set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the
  5945. returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain
  5946. to \ref sdNegative and all positive points will be ignored for range calculation. For no
  5947. restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output
  5948. parameter that indicates whether a range could be found or not. If this is false, you shouldn't
  5949. use the returned range (e.g. no points in data).
  5950. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  5951. this function may have size zero, which wouldn't count as a valid range.
  5952. \see rescaleAxes, getKeyRange
  5953. */
  5954. /* end of documentation of pure virtual functions */
  5955. /* start of documentation of signals */
  5956. /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected)
  5957. This signal is emitted when the selection state of this plottable has changed, either by user
  5958. interaction or by a direct call to \ref setSelected.
  5959. */
  5960. /*! \fn void QCPAbstractPlottable::selectableChanged(bool selectable);
  5961. This signal is emitted when the selectability of this plottable has changed.
  5962. \see setSelectable
  5963. */
  5964. /* end of documentation of signals */
  5965. /*!
  5966. Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as
  5967. its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance
  5968. and have perpendicular orientations. If either of these restrictions is violated, a corresponding
  5969. message is printed to the debug output (qDebug), the construction is not aborted, though.
  5970. Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables,
  5971. it can't be directly instantiated.
  5972. You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead.
  5973. */
  5974. QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis* keyAxis, QCPAxis* valueAxis)
  5975. : QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect())
  5976. , mName()
  5977. , mAntialiasedFill(true)
  5978. , mAntialiasedScatters(true)
  5979. , mAntialiasedErrorBars(false)
  5980. , mPen(Qt::black)
  5981. , mSelectedPen(Qt::black)
  5982. , mBrush(Qt::NoBrush)
  5983. , mSelectedBrush(Qt::NoBrush)
  5984. , mKeyAxis(keyAxis)
  5985. , mValueAxis(valueAxis)
  5986. , mSelectable(true)
  5987. , mSelected(false)
  5988. {
  5989. if (keyAxis->parentPlot() != valueAxis->parentPlot())
  5990. qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
  5991. if (keyAxis->orientation() == valueAxis->orientation())
  5992. qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other.";
  5993. }
  5994. /*!
  5995. The name is the textual representation of this plottable as it is displayed in the legend
  5996. (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
  5997. */
  5998. void QCPAbstractPlottable::setName(const QString& name)
  5999. {
  6000. mName = name;
  6001. }
  6002. /*!
  6003. Sets whether fills of this plottable are drawn antialiased or not.
  6004. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  6005. QCustomPlot::setNotAntialiasedElements.
  6006. */
  6007. void QCPAbstractPlottable::setAntialiasedFill(bool enabled)
  6008. {
  6009. mAntialiasedFill = enabled;
  6010. }
  6011. /*!
  6012. Sets whether the scatter symbols of this plottable are drawn antialiased or not.
  6013. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  6014. QCustomPlot::setNotAntialiasedElements.
  6015. */
  6016. void QCPAbstractPlottable::setAntialiasedScatters(bool enabled)
  6017. {
  6018. mAntialiasedScatters = enabled;
  6019. }
  6020. /*!
  6021. Sets whether the error bars of this plottable are drawn antialiased or not.
  6022. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  6023. QCustomPlot::setNotAntialiasedElements.
  6024. */
  6025. void QCPAbstractPlottable::setAntialiasedErrorBars(bool enabled)
  6026. {
  6027. mAntialiasedErrorBars = enabled;
  6028. }
  6029. /*!
  6030. The pen is used to draw basic lines that make up the plottable representation in the
  6031. plot.
  6032. For example, the \ref QCPGraph subclass draws its graph lines with this pen.
  6033. \see setBrush
  6034. */
  6035. void QCPAbstractPlottable::setPen(const QPen& pen)
  6036. {
  6037. mPen = pen;
  6038. }
  6039. /*!
  6040. When the plottable is selected, this pen is used to draw basic lines instead of the normal
  6041. pen set via \ref setPen.
  6042. \see setSelected, setSelectable, setSelectedBrush, selectTest
  6043. */
  6044. void QCPAbstractPlottable::setSelectedPen(const QPen& pen)
  6045. {
  6046. mSelectedPen = pen;
  6047. }
  6048. /*!
  6049. The brush is used to draw basic fills of the plottable representation in the
  6050. plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
  6051. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
  6052. it's not set to Qt::NoBrush.
  6053. \see setPen
  6054. */
  6055. void QCPAbstractPlottable::setBrush(const QBrush& brush)
  6056. {
  6057. mBrush = brush;
  6058. }
  6059. /*!
  6060. When the plottable is selected, this brush is used to draw fills instead of the normal
  6061. brush set via \ref setBrush.
  6062. \see setSelected, setSelectable, setSelectedPen, selectTest
  6063. */
  6064. void QCPAbstractPlottable::setSelectedBrush(const QBrush& brush)
  6065. {
  6066. mSelectedBrush = brush;
  6067. }
  6068. /*!
  6069. The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
  6070. to the plottable's value axis. This function performs no checks to make sure this is the case.
  6071. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
  6072. y-axis (QCustomPlot::yAxis) as value axis.
  6073. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  6074. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  6075. \see setValueAxis
  6076. */
  6077. void QCPAbstractPlottable::setKeyAxis(QCPAxis* axis)
  6078. {
  6079. mKeyAxis = axis;
  6080. }
  6081. /*!
  6082. The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
  6083. orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
  6084. case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
  6085. the y-axis (QCustomPlot::yAxis) as value axis.
  6086. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  6087. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  6088. \see setKeyAxis
  6089. */
  6090. void QCPAbstractPlottable::setValueAxis(QCPAxis* axis)
  6091. {
  6092. mValueAxis = axis;
  6093. }
  6094. /*!
  6095. Sets whether the user can (de-)select this plottable by clicking on the QCustomPlot surface.
  6096. (When \ref QCustomPlot::setInteractions contains iSelectPlottables.)
  6097. However, even when \a selectable was set to false, it is possible to set the selection manually,
  6098. by calling \ref setSelected directly.
  6099. \see setSelected
  6100. */
  6101. void QCPAbstractPlottable::setSelectable(bool selectable)
  6102. {
  6103. if (mSelectable != selectable) {
  6104. mSelectable = selectable;
  6105. emit selectableChanged(mSelectable);
  6106. }
  6107. }
  6108. /*!
  6109. Sets whether this plottable is selected or not. When selected, it uses a different pen and brush
  6110. to draw its lines and fills, see \ref setSelectedPen and \ref setSelectedBrush.
  6111. The entire selection mechanism for plottables is handled automatically when \ref
  6112. QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
  6113. you wish to change the selection state manually.
  6114. This function can change the selection state even when \ref setSelectable was set to false.
  6115. emits the \ref selectionChanged signal when \a selected is different from the previous selection
  6116. state.
  6117. \see setSelectable, selectTest
  6118. */
  6119. void QCPAbstractPlottable::setSelected(bool selected)
  6120. {
  6121. if (mSelected != selected) {
  6122. mSelected = selected;
  6123. emit selectionChanged(mSelected);
  6124. }
  6125. }
  6126. /*!
  6127. Rescales the key and value axes associated with this plottable to contain all displayed data, so
  6128. the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make
  6129. sure not to rescale to an illegal range i.e. a range containing different signs and/or zero.
  6130. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie
  6131. outside of that domain.
  6132. \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show
  6133. multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has
  6134. \a onlyEnlarge set to false (the default), and all subsequent set to true.
  6135. \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale
  6136. */
  6137. void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const
  6138. {
  6139. rescaleKeyAxis(onlyEnlarge);
  6140. rescaleValueAxis(onlyEnlarge);
  6141. }
  6142. /*!
  6143. Rescales the key axis of the plottable so the whole plottable is visible.
  6144. See \ref rescaleAxes for detailed behaviour.
  6145. */
  6146. void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
  6147. {
  6148. QCPAxis* keyAxis = mKeyAxis.data();
  6149. if (!keyAxis) {
  6150. qDebug() << Q_FUNC_INFO << "invalid key axis";
  6151. return;
  6152. }
  6153. SignDomain signDomain = sdBoth;
  6154. if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
  6155. signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive);
  6156. bool foundRange;
  6157. QCPRange newRange = getKeyRange(foundRange, signDomain);
  6158. if (foundRange) {
  6159. if (onlyEnlarge)
  6160. newRange.expand(keyAxis->range());
  6161. if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only
  6162. // constant data in this axis dimension), shift current
  6163. // range to at least center the plottable
  6164. {
  6165. double center = (newRange.lower + newRange.upper)
  6166. * 0.5; // upper and lower should be equal anyway, but just to make sure,
  6167. // incase validRange returned false for other reason
  6168. if (keyAxis->scaleType() == QCPAxis::stLinear) {
  6169. newRange.lower = center - keyAxis->range().size() / 2.0;
  6170. newRange.upper = center + keyAxis->range().size() / 2.0;
  6171. } else // scaleType() == stLogarithmic
  6172. {
  6173. newRange.lower = center / qSqrt(keyAxis->range().upper / keyAxis->range().lower);
  6174. newRange.upper = center * qSqrt(keyAxis->range().upper / keyAxis->range().lower);
  6175. }
  6176. }
  6177. keyAxis->setRange(newRange);
  6178. }
  6179. }
  6180. /*!
  6181. Rescales the value axis of the plottable so the whole plottable is visible.
  6182. Returns true if the axis was actually scaled. This might not be the case if this plottable has an
  6183. invalid range, e.g. because it has no data points.
  6184. See \ref rescaleAxes for detailed behaviour.
  6185. */
  6186. void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge) const
  6187. {
  6188. QCPAxis* valueAxis = mValueAxis.data();
  6189. if (!valueAxis) {
  6190. qDebug() << Q_FUNC_INFO << "invalid value axis";
  6191. return;
  6192. }
  6193. SignDomain signDomain = sdBoth;
  6194. if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
  6195. signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive);
  6196. bool foundRange;
  6197. QCPRange newRange = getValueRange(foundRange, signDomain);
  6198. if (foundRange) {
  6199. if (onlyEnlarge)
  6200. newRange.expand(valueAxis->range());
  6201. if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only
  6202. // constant data in this axis dimension), shift current
  6203. // range to at least center the plottable
  6204. {
  6205. double center = (newRange.lower + newRange.upper)
  6206. * 0.5; // upper and lower should be equal anyway, but just to make sure,
  6207. // incase validRange returned false for other reason
  6208. if (valueAxis->scaleType() == QCPAxis::stLinear) {
  6209. newRange.lower = center - valueAxis->range().size() / 2.0;
  6210. newRange.upper = center + valueAxis->range().size() / 2.0;
  6211. } else // scaleType() == stLogarithmic
  6212. {
  6213. newRange.lower =
  6214. center / qSqrt(valueAxis->range().upper / valueAxis->range().lower);
  6215. newRange.upper =
  6216. center * qSqrt(valueAxis->range().upper / valueAxis->range().lower);
  6217. }
  6218. }
  6219. valueAxis->setRange(newRange);
  6220. }
  6221. }
  6222. /*!
  6223. Adds this plottable to the legend of the parent QCustomPlot (QCustomPlot::legend).
  6224. Normally, a QCPPlottableLegendItem is created and inserted into the legend. If the plottable
  6225. needs a more specialized representation in the legend, this function will take this into account
  6226. and instead create the specialized subclass of QCPAbstractLegendItem.
  6227. Returns true on success, i.e. when the legend exists and a legend item associated with this
  6228. plottable isn't already in the legend.
  6229. \see removeFromLegend, QCPLegend::addItem
  6230. */
  6231. bool QCPAbstractPlottable::addToLegend()
  6232. {
  6233. if (!mParentPlot || !mParentPlot->legend)
  6234. return false;
  6235. if (!mParentPlot->legend->hasItemWithPlottable(this)) {
  6236. mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this));
  6237. return true;
  6238. } else
  6239. return false;
  6240. }
  6241. /*!
  6242. Removes the plottable from the legend of the parent QCustomPlot. This means the
  6243. QCPAbstractLegendItem (usually a QCPPlottableLegendItem) that is associated with this plottable
  6244. is removed.
  6245. Returns true on success, i.e. if the legend exists and a legend item associated with this
  6246. plottable was found and removed.
  6247. \see addToLegend, QCPLegend::removeItem
  6248. */
  6249. bool QCPAbstractPlottable::removeFromLegend() const
  6250. {
  6251. if (!mParentPlot->legend)
  6252. return false;
  6253. if (QCPPlottableLegendItem* lip = mParentPlot->legend->itemWithPlottable(this))
  6254. return mParentPlot->legend->removeItem(lip);
  6255. else
  6256. return false;
  6257. }
  6258. /* inherits documentation from base class */
  6259. QRect QCPAbstractPlottable::clipRect() const
  6260. {
  6261. if (mKeyAxis && mValueAxis)
  6262. return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
  6263. else
  6264. return QRect();
  6265. }
  6266. /* inherits documentation from base class */
  6267. QCP::Interaction QCPAbstractPlottable::selectionCategory() const
  6268. {
  6269. return QCP::iSelectPlottables;
  6270. }
  6271. /*! \internal
  6272. Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
  6273. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  6274. represents x or y).
  6275. \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
  6276. \see pixelsToCoords, QCPAxis::coordToPixel
  6277. */
  6278. void QCPAbstractPlottable::coordsToPixels(double key, double value, double& x, double& y) const
  6279. {
  6280. QCPAxis* keyAxis = mKeyAxis.data();
  6281. QCPAxis* valueAxis = mValueAxis.data();
  6282. if (!keyAxis || !valueAxis) {
  6283. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  6284. return;
  6285. }
  6286. if (keyAxis->orientation() == Qt::Horizontal) {
  6287. x = keyAxis->coordToPixel(key);
  6288. y = valueAxis->coordToPixel(value);
  6289. } else {
  6290. y = keyAxis->coordToPixel(key);
  6291. x = valueAxis->coordToPixel(value);
  6292. }
  6293. }
  6294. /*! \internal
  6295. \overload
  6296. Returns the input as pixel coordinates in a QPointF.
  6297. */
  6298. const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
  6299. {
  6300. QCPAxis* keyAxis = mKeyAxis.data();
  6301. QCPAxis* valueAxis = mValueAxis.data();
  6302. if (!keyAxis || !valueAxis) {
  6303. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  6304. return QPointF();
  6305. }
  6306. if (keyAxis->orientation() == Qt::Horizontal)
  6307. return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
  6308. else
  6309. return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
  6310. }
  6311. /*! \internal
  6312. Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot
  6313. coordinates, taking the orientations of the axes associated with this plottable into account (e.g.
  6314. whether key represents x or y).
  6315. \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
  6316. \see coordsToPixels, QCPAxis::coordToPixel
  6317. */
  6318. void QCPAbstractPlottable::pixelsToCoords(double x, double y, double& key, double& value) const
  6319. {
  6320. QCPAxis* keyAxis = mKeyAxis.data();
  6321. QCPAxis* valueAxis = mValueAxis.data();
  6322. if (!keyAxis || !valueAxis) {
  6323. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  6324. return;
  6325. }
  6326. if (keyAxis->orientation() == Qt::Horizontal) {
  6327. key = keyAxis->pixelToCoord(x);
  6328. value = valueAxis->pixelToCoord(y);
  6329. } else {
  6330. key = keyAxis->pixelToCoord(y);
  6331. value = valueAxis->pixelToCoord(x);
  6332. }
  6333. }
  6334. /*! \internal
  6335. \overload
  6336. Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
  6337. */
  6338. void QCPAbstractPlottable::pixelsToCoords(const QPointF& pixelPos, double& key, double& value) const
  6339. {
  6340. pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
  6341. }
  6342. /*! \internal
  6343. Returns the pen that should be used for drawing lines of the plottable. Returns mPen when the
  6344. graph is not selected and mSelectedPen when it is.
  6345. */
  6346. QPen QCPAbstractPlottable::mainPen() const
  6347. {
  6348. return mSelected ? mSelectedPen : mPen;
  6349. }
  6350. /*! \internal
  6351. Returns the brush that should be used for drawing fills of the plottable. Returns mBrush when the
  6352. graph is not selected and mSelectedBrush when it is.
  6353. */
  6354. QBrush QCPAbstractPlottable::mainBrush() const
  6355. {
  6356. return mSelected ? mSelectedBrush : mBrush;
  6357. }
  6358. /*! \internal
  6359. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6360. before drawing plottable lines.
  6361. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  6362. This function takes into account the local setting of the antialiasing flag as well as the
  6363. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6364. QCustomPlot::setNotAntialiasedElements.
  6365. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint,
  6366. applyErrorBarsAntialiasingHint
  6367. */
  6368. void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter* painter) const
  6369. {
  6370. applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
  6371. }
  6372. /*! \internal
  6373. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6374. before drawing plottable fills.
  6375. This function takes into account the local setting of the antialiasing flag as well as the
  6376. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6377. QCustomPlot::setNotAntialiasedElements.
  6378. \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint,
  6379. applyErrorBarsAntialiasingHint
  6380. */
  6381. void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter* painter) const
  6382. {
  6383. applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
  6384. }
  6385. /*! \internal
  6386. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6387. before drawing plottable scatter points.
  6388. This function takes into account the local setting of the antialiasing flag as well as the
  6389. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6390. QCustomPlot::setNotAntialiasedElements.
  6391. \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint,
  6392. applyErrorBarsAntialiasingHint
  6393. */
  6394. void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter* painter) const
  6395. {
  6396. applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
  6397. }
  6398. /*! \internal
  6399. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6400. before drawing plottable error bars.
  6401. This function takes into account the local setting of the antialiasing flag as well as the
  6402. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6403. QCustomPlot::setNotAntialiasedElements.
  6404. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint,
  6405. applyDefaultAntialiasingHint
  6406. */
  6407. void QCPAbstractPlottable::applyErrorBarsAntialiasingHint(QCPPainter* painter) const
  6408. {
  6409. applyAntialiasingHint(painter, mAntialiasedErrorBars, QCP::aeErrorBars);
  6410. }
  6411. /*! \internal
  6412. Finds the shortest squared distance of \a point to the line segment defined by \a start and \a
  6413. end.
  6414. This function may be used to help with the implementation of the \ref selectTest function for
  6415. specific plottables.
  6416. \note This function is identical to QCPAbstractItem::distSqrToLine
  6417. */
  6418. double QCPAbstractPlottable::distSqrToLine(const QPointF& start, const QPointF& end,
  6419. const QPointF& point) const
  6420. {
  6421. QVector2D a(start);
  6422. QVector2D b(end);
  6423. QVector2D p(point);
  6424. QVector2D v(b - a);
  6425. double vLengthSqr = v.lengthSquared();
  6426. if (!qFuzzyIsNull(vLengthSqr)) {
  6427. double mu = QVector2D::dotProduct(p - a, v) / vLengthSqr;
  6428. if (mu < 0)
  6429. return (a - p).lengthSquared();
  6430. else if (mu > 1)
  6431. return (b - p).lengthSquared();
  6432. else
  6433. return ((a + mu * v) - p).lengthSquared();
  6434. } else
  6435. return (a - p).lengthSquared();
  6436. }
  6437. /* inherits documentation from base class */
  6438. void QCPAbstractPlottable::selectEvent(QMouseEvent* event, bool additive, const QVariant& details,
  6439. bool* selectionStateChanged)
  6440. {
  6441. Q_UNUSED(event)
  6442. Q_UNUSED(details)
  6443. if (mSelectable) {
  6444. bool selBefore = mSelected;
  6445. setSelected(additive ? !mSelected : true);
  6446. if (selectionStateChanged)
  6447. *selectionStateChanged = mSelected != selBefore;
  6448. }
  6449. }
  6450. /* inherits documentation from base class */
  6451. void QCPAbstractPlottable::deselectEvent(bool* selectionStateChanged)
  6452. {
  6453. if (mSelectable) {
  6454. bool selBefore = mSelected;
  6455. setSelected(false);
  6456. if (selectionStateChanged)
  6457. *selectionStateChanged = mSelected != selBefore;
  6458. }
  6459. }
  6460. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6461. //////////////////// QCPItemAnchor
  6462. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6463. /*! \class QCPItemAnchor
  6464. \brief An anchor of an item to which positions can be attached to.
  6465. An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't
  6466. control anything on its item, but provides a way to tie other items via their positions to the
  6467. anchor.
  6468. For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight.
  6469. Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can
  6470. attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by
  6471. calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the
  6472. QCPItemRect. This way the start of the line will now always follow the respective anchor location
  6473. on the rect item.
  6474. Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an
  6475. anchor to other positions.
  6476. To learn how to provide anchors in your own item subclasses, see the subclassing section of the
  6477. QCPAbstractItem documentation.
  6478. */
  6479. /* start documentation of inline functions */
  6480. /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition()
  6481. Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition*
  6482. if it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor).
  6483. This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot
  6484. avoids dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti
  6485. flag with gcc compiler).
  6486. */
  6487. /* end documentation of inline functions */
  6488. /*!
  6489. Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if
  6490. you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as
  6491. explained in the subclassing section of the QCPAbstractItem documentation.
  6492. */
  6493. QCPItemAnchor::QCPItemAnchor(QCustomPlot* parentPlot, QCPAbstractItem* parentItem,
  6494. const QString name, int anchorId)
  6495. : mName(name), mParentPlot(parentPlot), mParentItem(parentItem), mAnchorId(anchorId)
  6496. {}
  6497. QCPItemAnchor::~QCPItemAnchor()
  6498. {
  6499. // unregister as parent at children:
  6500. foreach (QCPItemPosition* child, mChildrenX.toList()) {
  6501. if (child->parentAnchorX() == this)
  6502. child->setParentAnchorX(
  6503. 0); // this acts back on this anchor and child removes itself from mChildrenX
  6504. }
  6505. foreach (QCPItemPosition* child, mChildrenY.toList()) {
  6506. if (child->parentAnchorY() == this)
  6507. child->setParentAnchorY(
  6508. 0); // this acts back on this anchor and child removes itself from mChildrenY
  6509. }
  6510. }
  6511. /*!
  6512. Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface.
  6513. The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the
  6514. parent item, QCPItemAnchor is just an intermediary.
  6515. */
  6516. QPointF QCPItemAnchor::pixelPoint() const
  6517. {
  6518. if (mParentItem) {
  6519. if (mAnchorId > -1) {
  6520. return mParentItem->anchorPixelPoint(mAnchorId);
  6521. } else {
  6522. qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId;
  6523. return QPointF();
  6524. }
  6525. } else {
  6526. qDebug() << Q_FUNC_INFO << "no parent item set";
  6527. return QPointF();
  6528. }
  6529. }
  6530. /*! \internal
  6531. Adds \a pos to the childX list of this anchor, which keeps track of which children use this
  6532. anchor as parent anchor for the respective coordinate. This is necessary to notify the children
  6533. prior to destruction of the anchor.
  6534. Note that this function does not change the parent setting in \a pos.
  6535. */
  6536. void QCPItemAnchor::addChildX(QCPItemPosition* pos)
  6537. {
  6538. if (!mChildrenX.contains(pos))
  6539. mChildrenX.insert(pos);
  6540. else
  6541. qDebug() << Q_FUNC_INFO << "provided pos is child already"
  6542. << reinterpret_cast<quintptr>(pos);
  6543. }
  6544. /*! \internal
  6545. Removes \a pos from the childX list of this anchor.
  6546. Note that this function does not change the parent setting in \a pos.
  6547. */
  6548. void QCPItemAnchor::removeChildX(QCPItemPosition* pos)
  6549. {
  6550. if (!mChildrenX.remove(pos))
  6551. qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
  6552. }
  6553. /*! \internal
  6554. Adds \a pos to the childY list of this anchor, which keeps track of which children use this
  6555. anchor as parent anchor for the respective coordinate. This is necessary to notify the children
  6556. prior to destruction of the anchor.
  6557. Note that this function does not change the parent setting in \a pos.
  6558. */
  6559. void QCPItemAnchor::addChildY(QCPItemPosition* pos)
  6560. {
  6561. if (!mChildrenY.contains(pos))
  6562. mChildrenY.insert(pos);
  6563. else
  6564. qDebug() << Q_FUNC_INFO << "provided pos is child already"
  6565. << reinterpret_cast<quintptr>(pos);
  6566. }
  6567. /*! \internal
  6568. Removes \a pos from the childY list of this anchor.
  6569. Note that this function does not change the parent setting in \a pos.
  6570. */
  6571. void QCPItemAnchor::removeChildY(QCPItemPosition* pos)
  6572. {
  6573. if (!mChildrenY.remove(pos))
  6574. qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
  6575. }
  6576. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6577. //////////////////// QCPItemPosition
  6578. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6579. /*! \class QCPItemPosition
  6580. \brief Manages the position of an item.
  6581. Every item has at least one public QCPItemPosition member pointer which provides ways to position
  6582. the item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect
  6583. has two: \a topLeft and \a bottomRight.
  6584. QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type
  6585. defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel
  6586. coordinates, as plot coordinates of certain axes, etc. For more advanced plots it is also
  6587. possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref
  6588. setTypeY). This way an item could be positioned at a fixed pixel distance from the top in the Y
  6589. direction, while following a plot coordinate in the X direction.
  6590. A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie
  6591. multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords)
  6592. are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0)
  6593. means directly ontop of the parent anchor. For example, You could attach the \a start position of
  6594. a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line
  6595. always be centered under the text label, no matter where the text is moved to. For more advanced
  6596. plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see
  6597. \ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X
  6598. direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B
  6599. in Y.
  6600. Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent
  6601. anchor for other positions.
  6602. To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPoint.
  6603. This works no matter what type this QCPItemPosition is or what parent-child situation it is in, as
  6604. \ref setPixelPoint transforms the coordinates appropriately, to make the position appear at the
  6605. specified pixel values.
  6606. */
  6607. /* start documentation of inline functions */
  6608. /*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const
  6609. Returns the current position type.
  6610. If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the
  6611. type of the X coordinate. In that case rather use \a typeX() and \a typeY().
  6612. \see setType
  6613. */
  6614. /*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const
  6615. Returns the current parent anchor.
  6616. If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY),
  6617. this method returns the parent anchor of the Y coordinate. In that case rather use \a
  6618. parentAnchorX() and \a parentAnchorY().
  6619. \see setParentAnchor
  6620. */
  6621. /* end documentation of inline functions */
  6622. /*!
  6623. Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if
  6624. you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as
  6625. explained in the subclassing section of the QCPAbstractItem documentation.
  6626. */
  6627. QCPItemPosition::QCPItemPosition(QCustomPlot* parentPlot, QCPAbstractItem* parentItem,
  6628. const QString name)
  6629. : QCPItemAnchor(parentPlot, parentItem, name)
  6630. , mPositionTypeX(ptAbsolute)
  6631. , mPositionTypeY(ptAbsolute)
  6632. , mKey(0)
  6633. , mValue(0)
  6634. , mParentAnchorX(0)
  6635. , mParentAnchorY(0)
  6636. {}
  6637. QCPItemPosition::~QCPItemPosition()
  6638. {
  6639. // unregister as parent at children:
  6640. // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it
  6641. // itself, because only then
  6642. // the setParentAnchor(0) call the correct QCPItemPosition::pixelPoint function instead of
  6643. // QCPItemAnchor::pixelPoint
  6644. foreach (QCPItemPosition* child, mChildrenX.toList()) {
  6645. if (child->parentAnchorX() == this)
  6646. child->setParentAnchorX(
  6647. 0); // this acts back on this anchor and child removes itself from mChildrenX
  6648. }
  6649. foreach (QCPItemPosition* child, mChildrenY.toList()) {
  6650. if (child->parentAnchorY() == this)
  6651. child->setParentAnchorY(
  6652. 0); // this acts back on this anchor and child removes itself from mChildrenY
  6653. }
  6654. // unregister as child in parent:
  6655. if (mParentAnchorX)
  6656. mParentAnchorX->removeChildX(this);
  6657. if (mParentAnchorY)
  6658. mParentAnchorY->removeChildY(this);
  6659. }
  6660. /* can't make this a header inline function, because QPointer breaks with forward declared types,
  6661. * see QTBUG-29588 */
  6662. QCPAxisRect* QCPItemPosition::axisRect() const
  6663. {
  6664. return mAxisRect.data();
  6665. }
  6666. /*!
  6667. Sets the type of the position. The type defines how the coordinates passed to \ref setCoords
  6668. should be handled and how the QCPItemPosition should behave in the plot.
  6669. The possible values for \a type can be separated in two main categories:
  6670. \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords
  6671. and requires two axes that define the plot coordinate system. They can be specified with \ref
  6672. setAxes. By default, the QCustomPlot's x- and yAxis are used.
  6673. \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This
  6674. corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref
  6675. ptAxisRectRatio. They differ only in the way the absolute position is described, see the
  6676. documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can
  6677. specify the axis rect with \ref setAxisRect. By default this is set to the main axis rect.
  6678. Note that the position type \ref ptPlotCoords is only available (and sensible) when the position
  6679. has no parent anchor (\ref setParentAnchor).
  6680. If the type is changed, the apparent pixel position on the plot is preserved. This means
  6681. the coordinates as retrieved with coords() and set with \ref setCoords may change in the process.
  6682. This method sets the type for both X and Y directions. It is also possible to set different types
  6683. for X and Y, see \ref setTypeX, \ref setTypeY.
  6684. */
  6685. void QCPItemPosition::setType(QCPItemPosition::PositionType type)
  6686. {
  6687. setTypeX(type);
  6688. setTypeY(type);
  6689. }
  6690. /*!
  6691. This method sets the position type of the X coordinate to \a type.
  6692. For a detailed description of what a position type is, see the documentation of \ref setType.
  6693. \see setType, setTypeY
  6694. */
  6695. void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type)
  6696. {
  6697. if (mPositionTypeX != type) {
  6698. // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
  6699. // were deleted), don't try to recover the pixelPoint() because it would output a qDebug
  6700. // warning.
  6701. bool retainPixelPosition = true;
  6702. if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
  6703. retainPixelPosition = false;
  6704. if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
  6705. retainPixelPosition = false;
  6706. QPointF pixel;
  6707. if (retainPixelPosition)
  6708. pixel = pixelPoint();
  6709. mPositionTypeX = type;
  6710. if (retainPixelPosition)
  6711. setPixelPoint(pixel);
  6712. }
  6713. }
  6714. /*!
  6715. This method sets the position type of the Y coordinate to \a type.
  6716. For a detailed description of what a position type is, see the documentation of \ref setType.
  6717. \see setType, setTypeX
  6718. */
  6719. void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type)
  6720. {
  6721. if (mPositionTypeY != type) {
  6722. // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
  6723. // were deleted), don't try to recover the pixelPoint() because it would output a qDebug
  6724. // warning.
  6725. bool retainPixelPosition = true;
  6726. if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
  6727. retainPixelPosition = false;
  6728. if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
  6729. retainPixelPosition = false;
  6730. QPointF pixel;
  6731. if (retainPixelPosition)
  6732. pixel = pixelPoint();
  6733. mPositionTypeY = type;
  6734. if (retainPixelPosition)
  6735. setPixelPoint(pixel);
  6736. }
  6737. }
  6738. /*!
  6739. Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now
  6740. follow any position changes of the anchor. The local coordinate system of positions with a parent
  6741. anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence
  6742. the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.)
  6743. if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved
  6744. during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position
  6745. will be exactly on top of the parent anchor.
  6746. To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0.
  6747. If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is
  6748. set to \ref ptAbsolute, to keep the position in a valid state.
  6749. This method sets the parent anchor for both X and Y directions. It is also possible to set
  6750. different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY.
  6751. */
  6752. bool QCPItemPosition::setParentAnchor(QCPItemAnchor* parentAnchor, bool keepPixelPosition)
  6753. {
  6754. bool successX = setParentAnchorX(parentAnchor, keepPixelPosition);
  6755. bool successY = setParentAnchorY(parentAnchor, keepPixelPosition);
  6756. return successX && successY;
  6757. }
  6758. /*!
  6759. This method sets the parent anchor of the X coordinate to \a parentAnchor.
  6760. For a detailed description of what a parent anchor is, see the documentation of \ref
  6761. setParentAnchor.
  6762. \see setParentAnchor, setParentAnchorY
  6763. */
  6764. bool QCPItemPosition::setParentAnchorX(QCPItemAnchor* parentAnchor, bool keepPixelPosition)
  6765. {
  6766. // make sure self is not assigned as parent:
  6767. if (parentAnchor == this) {
  6768. qDebug() << Q_FUNC_INFO << "can't set self as parent anchor"
  6769. << reinterpret_cast<quintptr>(parentAnchor);
  6770. return false;
  6771. }
  6772. // make sure no recursive parent-child-relationships are created:
  6773. QCPItemAnchor* currentParent = parentAnchor;
  6774. while (currentParent) {
  6775. if (QCPItemPosition* currentParentPos = currentParent->toQCPItemPosition()) {
  6776. // is a QCPItemPosition, might have further parent, so keep iterating
  6777. if (currentParentPos == this) {
  6778. qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship"
  6779. << reinterpret_cast<quintptr>(parentAnchor);
  6780. return false;
  6781. }
  6782. currentParent = currentParentPos->parentAnchorX();
  6783. } else {
  6784. // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't
  6785. // the same, to prevent a position being child of an anchor which itself depends on the
  6786. // position, because they're both on the same item:
  6787. if (currentParent->mParentItem == mParentItem) {
  6788. qDebug() << Q_FUNC_INFO
  6789. << "can't set parent to be an anchor which itself depends on this position"
  6790. << reinterpret_cast<quintptr>(parentAnchor);
  6791. return false;
  6792. }
  6793. break;
  6794. }
  6795. }
  6796. // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
  6797. if (!mParentAnchorX && mPositionTypeX == ptPlotCoords)
  6798. setTypeX(ptAbsolute);
  6799. // save pixel position:
  6800. QPointF pixelP;
  6801. if (keepPixelPosition)
  6802. pixelP = pixelPoint();
  6803. // unregister at current parent anchor:
  6804. if (mParentAnchorX)
  6805. mParentAnchorX->removeChildX(this);
  6806. // register at new parent anchor:
  6807. if (parentAnchor)
  6808. parentAnchor->addChildX(this);
  6809. mParentAnchorX = parentAnchor;
  6810. // restore pixel position under new parent:
  6811. if (keepPixelPosition)
  6812. setPixelPoint(pixelP);
  6813. else
  6814. setCoords(0, coords().y());
  6815. return true;
  6816. }
  6817. /*!
  6818. This method sets the parent anchor of the Y coordinate to \a parentAnchor.
  6819. For a detailed description of what a parent anchor is, see the documentation of \ref
  6820. setParentAnchor.
  6821. \see setParentAnchor, setParentAnchorX
  6822. */
  6823. bool QCPItemPosition::setParentAnchorY(QCPItemAnchor* parentAnchor, bool keepPixelPosition)
  6824. {
  6825. // make sure self is not assigned as parent:
  6826. if (parentAnchor == this) {
  6827. qDebug() << Q_FUNC_INFO << "can't set self as parent anchor"
  6828. << reinterpret_cast<quintptr>(parentAnchor);
  6829. return false;
  6830. }
  6831. // make sure no recursive parent-child-relationships are created:
  6832. QCPItemAnchor* currentParent = parentAnchor;
  6833. while (currentParent) {
  6834. if (QCPItemPosition* currentParentPos = currentParent->toQCPItemPosition()) {
  6835. // is a QCPItemPosition, might have further parent, so keep iterating
  6836. if (currentParentPos == this) {
  6837. qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship"
  6838. << reinterpret_cast<quintptr>(parentAnchor);
  6839. return false;
  6840. }
  6841. currentParent = currentParentPos->parentAnchorY();
  6842. } else {
  6843. // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't
  6844. // the same, to prevent a position being child of an anchor which itself depends on the
  6845. // position, because they're both on the same item:
  6846. if (currentParent->mParentItem == mParentItem) {
  6847. qDebug() << Q_FUNC_INFO
  6848. << "can't set parent to be an anchor which itself depends on this position"
  6849. << reinterpret_cast<quintptr>(parentAnchor);
  6850. return false;
  6851. }
  6852. break;
  6853. }
  6854. }
  6855. // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
  6856. if (!mParentAnchorY && mPositionTypeY == ptPlotCoords)
  6857. setTypeY(ptAbsolute);
  6858. // save pixel position:
  6859. QPointF pixelP;
  6860. if (keepPixelPosition)
  6861. pixelP = pixelPoint();
  6862. // unregister at current parent anchor:
  6863. if (mParentAnchorY)
  6864. mParentAnchorY->removeChildY(this);
  6865. // register at new parent anchor:
  6866. if (parentAnchor)
  6867. parentAnchor->addChildY(this);
  6868. mParentAnchorY = parentAnchor;
  6869. // restore pixel position under new parent:
  6870. if (keepPixelPosition)
  6871. setPixelPoint(pixelP);
  6872. else
  6873. setCoords(coords().x(), 0);
  6874. return true;
  6875. }
  6876. /*!
  6877. Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type
  6878. (\ref setType, \ref setTypeX, \ref setTypeY).
  6879. For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position
  6880. on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the
  6881. QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the
  6882. plot coordinate system defined by the axes set by \ref setAxes. By default those are the
  6883. QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available
  6884. coordinate types and their meaning.
  6885. If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a
  6886. value must also be provided in the different coordinate systems. Here, the X type refers to \a
  6887. key, and the Y type refers to \a value.
  6888. \see setPixelPoint
  6889. */
  6890. void QCPItemPosition::setCoords(double key, double value)
  6891. {
  6892. mKey = key;
  6893. mValue = value;
  6894. }
  6895. /*! \overload
  6896. Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the
  6897. meaning of \a value of the \ref setCoords(double key, double value) method.
  6898. */
  6899. void QCPItemPosition::setCoords(const QPointF& pos)
  6900. {
  6901. setCoords(pos.x(), pos.y());
  6902. }
  6903. /*!
  6904. Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It
  6905. includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor).
  6906. \see setPixelPoint
  6907. */
  6908. QPointF QCPItemPosition::pixelPoint() const
  6909. {
  6910. QPointF result;
  6911. // determine X:
  6912. switch (mPositionTypeX) {
  6913. case ptAbsolute: {
  6914. result.rx() = mKey;
  6915. if (mParentAnchorX)
  6916. result.rx() += mParentAnchorX->pixelPoint().x();
  6917. break;
  6918. }
  6919. case ptViewportRatio: {
  6920. result.rx() = mKey * mParentPlot->viewport().width();
  6921. if (mParentAnchorX)
  6922. result.rx() += mParentAnchorX->pixelPoint().x();
  6923. else
  6924. result.rx() += mParentPlot->viewport().left();
  6925. break;
  6926. }
  6927. case ptAxisRectRatio: {
  6928. if (mAxisRect) {
  6929. result.rx() = mKey * mAxisRect.data()->width();
  6930. if (mParentAnchorX)
  6931. result.rx() += mParentAnchorX->pixelPoint().x();
  6932. else
  6933. result.rx() += mAxisRect.data()->left();
  6934. } else
  6935. qDebug() << Q_FUNC_INFO
  6936. << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
  6937. break;
  6938. }
  6939. case ptPlotCoords: {
  6940. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
  6941. result.rx() = mKeyAxis.data()->coordToPixel(mKey);
  6942. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
  6943. result.rx() = mValueAxis.data()->coordToPixel(mValue);
  6944. else
  6945. qDebug() << Q_FUNC_INFO
  6946. << "Item position type x is ptPlotCoords, but no axes were defined";
  6947. break;
  6948. }
  6949. }
  6950. // determine Y:
  6951. switch (mPositionTypeY) {
  6952. case ptAbsolute: {
  6953. result.ry() = mValue;
  6954. if (mParentAnchorY)
  6955. result.ry() += mParentAnchorY->pixelPoint().y();
  6956. break;
  6957. }
  6958. case ptViewportRatio: {
  6959. result.ry() = mValue * mParentPlot->viewport().height();
  6960. if (mParentAnchorY)
  6961. result.ry() += mParentAnchorY->pixelPoint().y();
  6962. else
  6963. result.ry() += mParentPlot->viewport().top();
  6964. break;
  6965. }
  6966. case ptAxisRectRatio: {
  6967. if (mAxisRect) {
  6968. result.ry() = mValue * mAxisRect.data()->height();
  6969. if (mParentAnchorY)
  6970. result.ry() += mParentAnchorY->pixelPoint().y();
  6971. else
  6972. result.ry() += mAxisRect.data()->top();
  6973. } else
  6974. qDebug() << Q_FUNC_INFO
  6975. << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
  6976. break;
  6977. }
  6978. case ptPlotCoords: {
  6979. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
  6980. result.ry() = mKeyAxis.data()->coordToPixel(mKey);
  6981. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
  6982. result.ry() = mValueAxis.data()->coordToPixel(mValue);
  6983. else
  6984. qDebug() << Q_FUNC_INFO
  6985. << "Item position type y is ptPlotCoords, but no axes were defined";
  6986. break;
  6987. }
  6988. }
  6989. return result;
  6990. }
  6991. /*!
  6992. When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the
  6993. coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and
  6994. yAxis of the QCustomPlot.
  6995. */
  6996. void QCPItemPosition::setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis)
  6997. {
  6998. mKeyAxis = keyAxis;
  6999. mValueAxis = valueAxis;
  7000. }
  7001. /*!
  7002. When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the
  7003. coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of
  7004. the QCustomPlot.
  7005. */
  7006. void QCPItemPosition::setAxisRect(QCPAxisRect* axisRect)
  7007. {
  7008. mAxisRect = axisRect;
  7009. }
  7010. /*!
  7011. Sets the apparent pixel position. This works no matter what type (\ref setType) this
  7012. QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed
  7013. appropriately, to make the position finally appear at the specified pixel values.
  7014. Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is
  7015. identical to that of \ref setCoords.
  7016. \see pixelPoint, setCoords
  7017. */
  7018. void QCPItemPosition::setPixelPoint(const QPointF& pixelPoint)
  7019. {
  7020. double x = pixelPoint.x();
  7021. double y = pixelPoint.y();
  7022. switch (mPositionTypeX) {
  7023. case ptAbsolute: {
  7024. if (mParentAnchorX)
  7025. x -= mParentAnchorX->pixelPoint().x();
  7026. break;
  7027. }
  7028. case ptViewportRatio: {
  7029. if (mParentAnchorX)
  7030. x -= mParentAnchorX->pixelPoint().x();
  7031. else
  7032. x -= mParentPlot->viewport().left();
  7033. x /= (double)mParentPlot->viewport().width();
  7034. break;
  7035. }
  7036. case ptAxisRectRatio: {
  7037. if (mAxisRect) {
  7038. if (mParentAnchorX)
  7039. x -= mParentAnchorX->pixelPoint().x();
  7040. else
  7041. x -= mAxisRect.data()->left();
  7042. x /= (double)mAxisRect.data()->width();
  7043. } else
  7044. qDebug() << Q_FUNC_INFO
  7045. << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
  7046. break;
  7047. }
  7048. case ptPlotCoords: {
  7049. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
  7050. x = mKeyAxis.data()->pixelToCoord(x);
  7051. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
  7052. y = mValueAxis.data()->pixelToCoord(x);
  7053. else
  7054. qDebug() << Q_FUNC_INFO
  7055. << "Item position type x is ptPlotCoords, but no axes were defined";
  7056. break;
  7057. }
  7058. }
  7059. switch (mPositionTypeY) {
  7060. case ptAbsolute: {
  7061. if (mParentAnchorY)
  7062. y -= mParentAnchorY->pixelPoint().y();
  7063. break;
  7064. }
  7065. case ptViewportRatio: {
  7066. if (mParentAnchorY)
  7067. y -= mParentAnchorY->pixelPoint().y();
  7068. else
  7069. y -= mParentPlot->viewport().top();
  7070. y /= (double)mParentPlot->viewport().height();
  7071. break;
  7072. }
  7073. case ptAxisRectRatio: {
  7074. if (mAxisRect) {
  7075. if (mParentAnchorY)
  7076. y -= mParentAnchorY->pixelPoint().y();
  7077. else
  7078. y -= mAxisRect.data()->top();
  7079. y /= (double)mAxisRect.data()->height();
  7080. } else
  7081. qDebug() << Q_FUNC_INFO
  7082. << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
  7083. break;
  7084. }
  7085. case ptPlotCoords: {
  7086. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
  7087. x = mKeyAxis.data()->pixelToCoord(y);
  7088. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
  7089. y = mValueAxis.data()->pixelToCoord(y);
  7090. else
  7091. qDebug() << Q_FUNC_INFO
  7092. << "Item position type y is ptPlotCoords, but no axes were defined";
  7093. break;
  7094. }
  7095. }
  7096. setCoords(x, y);
  7097. }
  7098. ////////////////////////////////////////////////////////////////////////////////////////////////////
  7099. //////////////////// QCPAbstractItem
  7100. ////////////////////////////////////////////////////////////////////////////////////////////////////
  7101. /*! \class QCPAbstractItem
  7102. \brief The abstract base class for all items in a plot.
  7103. In QCustomPlot, items are supplemental graphical elements that are neither plottables
  7104. (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus
  7105. plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each
  7106. specific item has at least one QCPItemPosition member which controls the positioning. Some items
  7107. are defined by more than one coordinate and thus have two or more QCPItemPosition members (For
  7108. example, QCPItemRect has \a topLeft and \a bottomRight).
  7109. This abstract base class defines a very basic interface like visibility and clipping. Since this
  7110. class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass
  7111. yourself to create new items.
  7112. The built-in items are:
  7113. <table>
  7114. <tr><td>QCPItemLine</td><td>A line defined by a start and an end point. May have different ending
  7115. styles on each side (e.g. arrows).</td></tr> <tr><td>QCPItemStraightLine</td><td>A straight line
  7116. defined by a start and a direction point. Unlike QCPItemLine, the straight line is infinitely long
  7117. and has no endings.</td></tr> <tr><td>QCPItemCurve</td><td>A curve defined by start, end and two
  7118. intermediate control points. May have different ending styles on each side (e.g.
  7119. arrows).</td></tr> <tr><td>QCPItemRect</td><td>A rectangle</td></tr>
  7120. <tr><td>QCPItemEllipse</td><td>An ellipse</td></tr>
  7121. <tr><td>QCPItemPixmap</td><td>An arbitrary pixmap</td></tr>
  7122. <tr><td>QCPItemText</td><td>A text label</td></tr>
  7123. <tr><td>QCPItemBracket</td><td>A bracket which may be used to reference/highlight certain parts in
  7124. the plot.</td></tr> <tr><td>QCPItemTracer</td><td>An item that can be attached to a QCPGraph and
  7125. sticks to its data points, given a key coordinate.</td></tr>
  7126. </table>
  7127. \section items-clipping Clipping
  7128. Items are by default clipped to the main axis rect (they are only visible inside the axis rect).
  7129. To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect
  7130. "setClipToAxisRect(false)".
  7131. On the other hand if you want the item to be clipped to a different axis rect, specify it via
  7132. \ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour,
  7133. and in principle is independent of the coordinate axes the item might be tied to via its position
  7134. members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping
  7135. also contains the axes used for the item positions.
  7136. \section items-using Using items
  7137. First you instantiate the item you want to use and add it to the plot:
  7138. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1
  7139. by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just
  7140. set the plot coordinates where the line should start/end:
  7141. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-2
  7142. If we don't want the line to be positioned in plot coordinates but a different coordinate system,
  7143. e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like
  7144. this: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-3 Then we can
  7145. set the coordinates, this time in pixels: \snippet documentation/doc-code-snippets/mainwindow.cpp
  7146. qcpitemline-creation-4 and make the line visible on the entire QCustomPlot, by disabling clipping
  7147. to the axis rect: \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5
  7148. For more advanced plots, it is even possible to set different types and parent anchors per X/Y
  7149. coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref
  7150. QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition.
  7151. \section items-subclassing Creating own items
  7152. To create an own item, you implement a subclass of QCPAbstractItem. These are the pure
  7153. virtual functions, you must implement:
  7154. \li \ref selectTest
  7155. \li \ref draw
  7156. See the documentation of those functions for what they need to do.
  7157. \subsection items-positioning Allowing the item to be positioned
  7158. As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item
  7159. shall have only one point as its position (as opposed to two like a rect or multiple like a
  7160. polygon). You then add a public member of type QCPItemPosition like so:
  7161. \code QCPItemPosition * const myPosition;\endcode
  7162. the const makes sure the pointer itself can't be modified from the user of your new item (the
  7163. QCPItemPosition instance it points to, can be modified, of course). The initialization of this
  7164. pointer is made easy with the \ref createPosition function. Just assign the return value of this
  7165. function to each QCPItemPosition in the constructor of your item. \ref createPosition takes a
  7166. string which is the name of the position, typically this is identical to the variable name. For
  7167. example, the constructor of QCPItemExample could look like this:
  7168. \code
  7169. QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) :
  7170. QCPAbstractItem(parentPlot),
  7171. myPosition(createPosition("myPosition"))
  7172. {
  7173. // other constructor code
  7174. }
  7175. \endcode
  7176. \subsection items-drawing The draw function
  7177. To give your item a visual representation, reimplement the \ref draw function and use the passed
  7178. QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the
  7179. position member(s) via \ref QCPItemPosition::pixelPoint.
  7180. To optimize performance you should calculate a bounding rect first (don't forget to take the pen
  7181. width into account), check whether it intersects the \ref clipRect, and only draw the item at all
  7182. if this is the case.
  7183. \subsection items-selection The selectTest function
  7184. Your implementation of the \ref selectTest function may use the helpers \ref distSqrToLine and
  7185. \ref rectSelectTest. With these, the implementation of the selection test becomes significantly
  7186. simpler for most items. See the documentation of \ref selectTest for what the function parameters
  7187. mean and what the function should return.
  7188. \subsection anchors Providing anchors
  7189. Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public
  7190. member, e.g.
  7191. \code QCPItemAnchor * const bottom;\endcode
  7192. and create it in the constructor with the \ref createAnchor function, assigning it a name and an
  7193. anchor id (an integer enumerating all anchors on the item, you may create an own enum for this).
  7194. Since anchors can be placed anywhere, relative to the item's position(s), your item needs to
  7195. provide the position of every anchor with the reimplementation of the \ref anchorPixelPoint(int
  7196. anchorId) function.
  7197. In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel
  7198. position when anything attached to the anchor needs to know the coordinates.
  7199. */
  7200. /* start of documentation of inline functions */
  7201. /*! \fn QList<QCPItemPosition*> QCPAbstractItem::positions() const
  7202. Returns all positions of the item in a list.
  7203. \see anchors, position
  7204. */
  7205. /*! \fn QList<QCPItemAnchor*> QCPAbstractItem::anchors() const
  7206. Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always
  7207. also an anchor, the list will also contain the positions of this item.
  7208. \see positions, anchor
  7209. */
  7210. /* end of documentation of inline functions */
  7211. /* start documentation of pure virtual functions */
  7212. /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0
  7213. \internal
  7214. Draws this item with the provided \a painter.
  7215. The cliprect of the provided painter is set to the rect returned by \ref clipRect before this
  7216. function is called. The clipRect depends on the clipping settings defined by \ref
  7217. setClipToAxisRect and \ref setClipAxisRect.
  7218. */
  7219. /* end documentation of pure virtual functions */
  7220. /* start documentation of signals */
  7221. /*! \fn void QCPAbstractItem::selectionChanged(bool selected)
  7222. This signal is emitted when the selection state of this item has changed, either by user
  7223. interaction or by a direct call to \ref setSelected.
  7224. */
  7225. /* end documentation of signals */
  7226. /*!
  7227. Base class constructor which initializes base class members.
  7228. */
  7229. QCPAbstractItem::QCPAbstractItem(QCustomPlot* parentPlot)
  7230. : QCPLayerable(parentPlot), mClipToAxisRect(false), mSelectable(true), mSelected(false)
  7231. {
  7232. QList<QCPAxisRect*> rects = parentPlot->axisRects();
  7233. if (rects.size() > 0) {
  7234. setClipToAxisRect(true);
  7235. setClipAxisRect(rects.first());
  7236. }
  7237. }
  7238. QCPAbstractItem::~QCPAbstractItem()
  7239. {
  7240. // don't delete mPositions because every position is also an anchor and thus in mAnchors
  7241. qDeleteAll(mAnchors);
  7242. }
  7243. /* can't make this a header inline function, because QPointer breaks with forward declared types,
  7244. * see QTBUG-29588 */
  7245. QCPAxisRect* QCPAbstractItem::clipAxisRect() const
  7246. {
  7247. return mClipAxisRect.data();
  7248. }
  7249. /*!
  7250. Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the
  7251. entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect.
  7252. \see setClipAxisRect
  7253. */
  7254. void QCPAbstractItem::setClipToAxisRect(bool clip)
  7255. {
  7256. mClipToAxisRect = clip;
  7257. if (mClipToAxisRect)
  7258. setParentLayerable(mClipAxisRect.data());
  7259. }
  7260. /*!
  7261. Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref
  7262. setClipToAxisRect is set to true.
  7263. \see setClipToAxisRect
  7264. */
  7265. void QCPAbstractItem::setClipAxisRect(QCPAxisRect* rect)
  7266. {
  7267. mClipAxisRect = rect;
  7268. if (mClipToAxisRect)
  7269. setParentLayerable(mClipAxisRect.data());
  7270. }
  7271. /*!
  7272. Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface.
  7273. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.)
  7274. However, even when \a selectable was set to false, it is possible to set the selection manually,
  7275. by calling \ref setSelected.
  7276. \see QCustomPlot::setInteractions, setSelected
  7277. */
  7278. void QCPAbstractItem::setSelectable(bool selectable)
  7279. {
  7280. if (mSelectable != selectable) {
  7281. mSelectable = selectable;
  7282. emit selectableChanged(mSelectable);
  7283. }
  7284. }
  7285. /*!
  7286. Sets whether this item is selected or not. When selected, it might use a different visual
  7287. appearance (e.g. pen and brush), this depends on the specific item though.
  7288. The entire selection mechanism for items is handled automatically when \ref
  7289. QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this
  7290. function when you wish to change the selection state manually.
  7291. This function can change the selection state even when \ref setSelectable was set to false.
  7292. emits the \ref selectionChanged signal when \a selected is different from the previous selection
  7293. state.
  7294. \see setSelectable, selectTest
  7295. */
  7296. void QCPAbstractItem::setSelected(bool selected)
  7297. {
  7298. if (mSelected != selected) {
  7299. mSelected = selected;
  7300. emit selectionChanged(mSelected);
  7301. }
  7302. }
  7303. /*!
  7304. Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by
  7305. that name, returns 0.
  7306. This function provides an alternative way to access item positions. Normally, you access
  7307. positions direcly by their member pointers (which typically have the same variable name as \a
  7308. name).
  7309. \see positions, anchor
  7310. */
  7311. QCPItemPosition* QCPAbstractItem::position(const QString& name) const
  7312. {
  7313. for (int i = 0; i < mPositions.size(); ++i) {
  7314. if (mPositions.at(i)->name() == name)
  7315. return mPositions.at(i);
  7316. }
  7317. qDebug() << Q_FUNC_INFO << "position with name not found:" << name;
  7318. return 0;
  7319. }
  7320. /*!
  7321. Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by
  7322. that name, returns 0.
  7323. This function provides an alternative way to access item anchors. Normally, you access
  7324. anchors direcly by their member pointers (which typically have the same variable name as \a
  7325. name).
  7326. \see anchors, position
  7327. */
  7328. QCPItemAnchor* QCPAbstractItem::anchor(const QString& name) const
  7329. {
  7330. for (int i = 0; i < mAnchors.size(); ++i) {
  7331. if (mAnchors.at(i)->name() == name)
  7332. return mAnchors.at(i);
  7333. }
  7334. qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name;
  7335. return 0;
  7336. }
  7337. /*!
  7338. Returns whether this item has an anchor with the specified \a name.
  7339. Note that you can check for positions with this function, too. This is because every position is
  7340. also an anchor (QCPItemPosition inherits from QCPItemAnchor).
  7341. \see anchor, position
  7342. */
  7343. bool QCPAbstractItem::hasAnchor(const QString& name) const
  7344. {
  7345. for (int i = 0; i < mAnchors.size(); ++i) {
  7346. if (mAnchors.at(i)->name() == name)
  7347. return true;
  7348. }
  7349. return false;
  7350. }
  7351. /*! \internal
  7352. Returns the rect the visual representation of this item is clipped to. This depends on the
  7353. current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect.
  7354. If the item is not clipped to an axis rect, the \ref QCustomPlot::viewport rect is returned.
  7355. \see draw
  7356. */
  7357. QRect QCPAbstractItem::clipRect() const
  7358. {
  7359. if (mClipToAxisRect && mClipAxisRect)
  7360. return mClipAxisRect.data()->rect();
  7361. else
  7362. return mParentPlot->viewport();
  7363. }
  7364. /*! \internal
  7365. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  7366. before drawing item lines.
  7367. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  7368. This function takes into account the local setting of the antialiasing flag as well as the
  7369. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  7370. QCustomPlot::setNotAntialiasedElements.
  7371. \see setAntialiased
  7372. */
  7373. void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter* painter) const
  7374. {
  7375. applyAntialiasingHint(painter, mAntialiased, QCP::aeItems);
  7376. }
  7377. /*! \internal
  7378. Finds the shortest squared distance of \a point to the line segment defined by \a start and \a
  7379. end.
  7380. This function may be used to help with the implementation of the \ref selectTest function for
  7381. specific items.
  7382. \note This function is identical to QCPAbstractPlottable::distSqrToLine
  7383. \see rectSelectTest
  7384. */
  7385. double QCPAbstractItem::distSqrToLine(const QPointF& start, const QPointF& end,
  7386. const QPointF& point) const
  7387. {
  7388. QVector2D a(start);
  7389. QVector2D b(end);
  7390. QVector2D p(point);
  7391. QVector2D v(b - a);
  7392. double vLengthSqr = v.lengthSquared();
  7393. if (!qFuzzyIsNull(vLengthSqr)) {
  7394. double mu = QVector2D::dotProduct(p - a, v) / vLengthSqr;
  7395. if (mu < 0)
  7396. return (a - p).lengthSquared();
  7397. else if (mu > 1)
  7398. return (b - p).lengthSquared();
  7399. else
  7400. return ((a + mu * v) - p).lengthSquared();
  7401. } else
  7402. return (a - p).lengthSquared();
  7403. }
  7404. /*! \internal
  7405. A convenience function which returns the selectTest value for a specified \a rect and a specified
  7406. click position \a pos. \a filledRect defines whether a click inside the rect should also be
  7407. considered a hit or whether only the rect border is sensitive to hits.
  7408. This function may be used to help with the implementation of the \ref selectTest function for
  7409. specific items.
  7410. For example, if your item consists of four rects, call this function four times, once for each
  7411. rect, in your \ref selectTest reimplementation. Finally, return the minimum of all four returned
  7412. values.
  7413. \see distSqrToLine
  7414. */
  7415. double QCPAbstractItem::rectSelectTest(const QRectF& rect, const QPointF& pos,
  7416. bool filledRect) const
  7417. {
  7418. double result = -1;
  7419. // distance to border:
  7420. QList<QLineF> lines;
  7421. lines << QLineF(rect.topLeft(), rect.topRight())
  7422. << QLineF(rect.bottomLeft(), rect.bottomRight())
  7423. << QLineF(rect.topLeft(), rect.bottomLeft())
  7424. << QLineF(rect.topRight(), rect.bottomRight());
  7425. double minDistSqr = std::numeric_limits<double>::max();
  7426. for (int i = 0; i < lines.size(); ++i) {
  7427. double distSqr = distSqrToLine(lines.at(i).p1(), lines.at(i).p2(), pos);
  7428. if (distSqr < minDistSqr)
  7429. minDistSqr = distSqr;
  7430. }
  7431. result = qSqrt(minDistSqr);
  7432. // filled rect, allow click inside to count as hit:
  7433. if (filledRect && result > mParentPlot->selectionTolerance() * 0.99) {
  7434. if (rect.contains(pos))
  7435. result = mParentPlot->selectionTolerance() * 0.99;
  7436. }
  7437. return result;
  7438. }
  7439. /*! \internal
  7440. Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented
  7441. in item subclasses if they want to provide anchors (QCPItemAnchor).
  7442. For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor
  7443. ids and returns the respective pixel points of the specified anchor.
  7444. \see createAnchor
  7445. */
  7446. QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const
  7447. {
  7448. qDebug() << Q_FUNC_INFO
  7449. << "called on item which shouldn't have any anchors (this method not reimplemented). "
  7450. "anchorId"
  7451. << anchorId;
  7452. return QPointF();
  7453. }
  7454. /*! \internal
  7455. Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified
  7456. \a name must be a unique string that is usually identical to the variable name of the position
  7457. member (This is needed to provide the name-based \ref position access to positions).
  7458. Don't delete positions created by this function manually, as the item will take care of it.
  7459. Use this function in the constructor (initialization list) of the specific item subclass to
  7460. create each position member. Don't create QCPItemPositions with \b new yourself, because they
  7461. won't be registered with the item properly.
  7462. \see createAnchor
  7463. */
  7464. QCPItemPosition* QCPAbstractItem::createPosition(const QString& name)
  7465. {
  7466. if (hasAnchor(name))
  7467. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  7468. QCPItemPosition* newPosition = new QCPItemPosition(mParentPlot, this, name);
  7469. mPositions.append(newPosition);
  7470. mAnchors.append(newPosition); // every position is also an anchor
  7471. newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis);
  7472. newPosition->setType(QCPItemPosition::ptPlotCoords);
  7473. if (mParentPlot->axisRect())
  7474. newPosition->setAxisRect(mParentPlot->axisRect());
  7475. newPosition->setCoords(0, 0);
  7476. return newPosition;
  7477. }
  7478. /*! \internal
  7479. Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified
  7480. \a name must be a unique string that is usually identical to the variable name of the anchor
  7481. member (This is needed to provide the name based \ref anchor access to anchors).
  7482. The \a anchorId must be a number identifying the created anchor. It is recommended to create an
  7483. enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor
  7484. to identify itself when it calls QCPAbstractItem::anchorPixelPoint. That function then returns
  7485. the correct pixel coordinates for the passed anchor id.
  7486. Don't delete anchors created by this function manually, as the item will take care of it.
  7487. Use this function in the constructor (initialization list) of the specific item subclass to
  7488. create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they
  7489. won't be registered with the item properly.
  7490. \see createPosition
  7491. */
  7492. QCPItemAnchor* QCPAbstractItem::createAnchor(const QString& name, int anchorId)
  7493. {
  7494. if (hasAnchor(name))
  7495. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  7496. QCPItemAnchor* newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId);
  7497. mAnchors.append(newAnchor);
  7498. return newAnchor;
  7499. }
  7500. /* inherits documentation from base class */
  7501. void QCPAbstractItem::selectEvent(QMouseEvent* event, bool additive, const QVariant& details,
  7502. bool* selectionStateChanged)
  7503. {
  7504. Q_UNUSED(event)
  7505. Q_UNUSED(details)
  7506. if (mSelectable) {
  7507. bool selBefore = mSelected;
  7508. setSelected(additive ? !mSelected : true);
  7509. if (selectionStateChanged)
  7510. *selectionStateChanged = mSelected != selBefore;
  7511. }
  7512. }
  7513. /* inherits documentation from base class */
  7514. void QCPAbstractItem::deselectEvent(bool* selectionStateChanged)
  7515. {
  7516. if (mSelectable) {
  7517. bool selBefore = mSelected;
  7518. setSelected(false);
  7519. if (selectionStateChanged)
  7520. *selectionStateChanged = mSelected != selBefore;
  7521. }
  7522. }
  7523. /* inherits documentation from base class */
  7524. QCP::Interaction QCPAbstractItem::selectionCategory() const
  7525. {
  7526. return QCP::iSelectItems;
  7527. }
  7528. /*! \file */
  7529. ////////////////////////////////////////////////////////////////////////////////////////////////////
  7530. //////////////////// QCustomPlot
  7531. ////////////////////////////////////////////////////////////////////////////////////////////////////
  7532. /*! \class QCustomPlot
  7533. \brief The central class of the library. This is the QWidget which displays the plot and
  7534. interacts with the user.
  7535. For tutorials on how to use QCustomPlot, see the website\n
  7536. http://www.qcustomplot.com/
  7537. */
  7538. /* start of documentation of inline functions */
  7539. /*! \fn QRect QCustomPlot::viewport() const
  7540. Returns the viewport rect of this QCustomPlot instance. The viewport is the area the plot is
  7541. drawn in, all mechanisms, e.g. margin caluclation take the viewport to be the outer border of the
  7542. plot. The viewport normally is the rect() of the QCustomPlot widget, i.e. a rect with top left
  7543. (0, 0) and size of the QCustomPlot widget.
  7544. Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
  7545. an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
  7546. and contains also the axes themselves, their tick numbers, their labels, the plot title etc.
  7547. Only when saving to a file (see \ref savePng, \ref savePdf etc.) the viewport is temporarily
  7548. modified to allow saving plots with sizes independent of the current widget size.
  7549. */
  7550. /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const
  7551. Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially
  7552. containing just one cell with the main QCPAxisRect inside.
  7553. */
  7554. /* end of documentation of inline functions */
  7555. /* start of documentation of signals */
  7556. /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event)
  7557. This signal is emitted when the QCustomPlot receives a mouse double click event.
  7558. */
  7559. /*! \fn void QCustomPlot::mousePress(QMouseEvent *event)
  7560. This signal is emitted when the QCustomPlot receives a mouse press event.
  7561. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  7562. connected to this signal can still influence the behaviour e.g. with \ref
  7563. QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes.
  7564. */
  7565. /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event)
  7566. This signal is emitted when the QCustomPlot receives a mouse move event.
  7567. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  7568. connected to this signal can still influence the behaviour e.g. with \ref
  7569. QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes.
  7570. \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here,
  7571. because the dragging starting point was saved the moment the mouse was pressed. Thus it only has
  7572. a meaning for the range drag axes that were set at that moment. If you want to change the drag
  7573. axes, consider doing this in the \ref mousePress signal instead.
  7574. */
  7575. /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event)
  7576. This signal is emitted when the QCustomPlot receives a mouse release event.
  7577. It is emitted before QCustomPlot handles any other mechanisms like object selection. So a
  7578. slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or
  7579. \ref QCPAbstractPlottable::setSelectable.
  7580. */
  7581. /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event)
  7582. This signal is emitted when the QCustomPlot receives a mouse wheel event.
  7583. It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot
  7584. connected to this signal can still influence the behaviour e.g. with \ref
  7585. QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes or \ref
  7586. QCPAxisRect::setRangeZoomFactor.
  7587. */
  7588. /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event)
  7589. This signal is emitted when a plottable is clicked.
  7590. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  7591. the click.
  7592. \see plottableDoubleClick
  7593. */
  7594. /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event)
  7595. This signal is emitted when a plottable is double clicked.
  7596. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  7597. the click.
  7598. \see plottableClick
  7599. */
  7600. /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event)
  7601. This signal is emitted when an item is clicked.
  7602. \a event is the mouse event that caused the click and \a item is the item that received the
  7603. click.
  7604. \see itemDoubleClick
  7605. */
  7606. /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event)
  7607. This signal is emitted when an item is double clicked.
  7608. \a event is the mouse event that caused the click and \a item is the item that received the
  7609. click.
  7610. \see itemClick
  7611. */
  7612. /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  7613. This signal is emitted when an axis is clicked.
  7614. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  7615. \a part indicates the part of the axis that was clicked.
  7616. \see axisDoubleClick
  7617. */
  7618. /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent
  7619. *event)
  7620. This signal is emitted when an axis is double clicked.
  7621. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  7622. \a part indicates the part of the axis that was clicked.
  7623. \see axisClick
  7624. */
  7625. /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent
  7626. *event)
  7627. This signal is emitted when a legend (item) is clicked.
  7628. \a event is the mouse event that caused the click, \a legend is the legend that received the
  7629. click and \a item is the legend item that received the click. If only the legend and no item is
  7630. clicked, \a item is 0. This happens for a click inside the legend padding or the space between
  7631. two items.
  7632. \see legendDoubleClick
  7633. */
  7634. /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item,
  7635. QMouseEvent *event)
  7636. This signal is emitted when a legend (item) is double clicked.
  7637. \a event is the mouse event that caused the click, \a legend is the legend that received the
  7638. click and \a item is the legend item that received the click. If only the legend and no item is
  7639. clicked, \a item is 0. This happens for a click inside the legend padding or the space between
  7640. two items.
  7641. \see legendClick
  7642. */
  7643. /*! \fn void QCustomPlot:: titleClick(QMouseEvent *event, QCPPlotTitle *title)
  7644. This signal is emitted when a plot title is clicked.
  7645. \a event is the mouse event that caused the click and \a title is the plot title that received
  7646. the click.
  7647. \see titleDoubleClick
  7648. */
  7649. /*! \fn void QCustomPlot::titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title)
  7650. This signal is emitted when a plot title is double clicked.
  7651. \a event is the mouse event that caused the click and \a title is the plot title that received
  7652. the click.
  7653. \see titleClick
  7654. */
  7655. /*! \fn void QCustomPlot::selectionChangedByUser()
  7656. This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by
  7657. clicking. It is not emitted when the selection state of an object has changed programmatically by
  7658. a direct call to setSelected() on an object or by calling \ref deselectAll.
  7659. In addition to this signal, selectable objects also provide individual signals, for example
  7660. QCPAxis::selectionChanged or QCPAbstractPlottable::selectionChanged. Note that those signals are
  7661. emitted even if the selection state is changed programmatically.
  7662. See the documentation of \ref setInteractions for details about the selection mechanism.
  7663. \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends
  7664. */
  7665. /*! \fn void QCustomPlot::beforeReplot()
  7666. This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref
  7667. replot).
  7668. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  7669. replot synchronously, it won't cause an infinite recursion.
  7670. \see replot, afterReplot
  7671. */
  7672. /*! \fn void QCustomPlot::afterReplot()
  7673. This signal is emitted immediately after a replot has taken place (caused by a call to the slot
  7674. \ref replot).
  7675. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  7676. replot synchronously, it won't cause an infinite recursion.
  7677. \see replot, beforeReplot
  7678. */
  7679. /* end of documentation of signals */
  7680. /* start of documentation of public members */
  7681. /*! \var QCPAxis *QCustomPlot::xAxis
  7682. A pointer to the primary x Axis (bottom) of the main axis rect of the plot.
  7683. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7684. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7685. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7686. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  7687. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  7688. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7689. axis rect), the corresponding pointers become 0.
  7690. */
  7691. /*! \var QCPAxis *QCustomPlot::yAxis
  7692. A pointer to the primary y Axis (left) of the main axis rect of the plot.
  7693. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7694. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7695. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7696. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  7697. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  7698. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7699. axis rect), the corresponding pointers become 0.
  7700. */
  7701. /*! \var QCPAxis *QCustomPlot::xAxis2
  7702. A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are
  7703. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  7704. QCPAxisRect::setupFullAxesBox).
  7705. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7706. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7707. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7708. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  7709. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  7710. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7711. axis rect), the corresponding pointers become 0.
  7712. */
  7713. /*! \var QCPAxis *QCustomPlot::yAxis2
  7714. A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are
  7715. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  7716. QCPAxisRect::setupFullAxesBox).
  7717. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7718. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7719. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7720. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  7721. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  7722. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7723. axis rect), the corresponding pointers become 0.
  7724. */
  7725. /*! \var QCPLegend *QCustomPlot::legend
  7726. A pointer to the default legend of the main axis rect. The legend is invisible by default. Use
  7727. QCPLegend::setVisible to change this.
  7728. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  7729. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  7730. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  7731. layout system\endlink to add multiple legends to the plot, use the layout system interface to
  7732. access the new legend. For example, legends can be placed inside an axis rect's \ref
  7733. QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If
  7734. the default legend is removed due to manipulation of the layout system (e.g. by removing the main
  7735. axis rect), the corresponding pointer becomes 0.
  7736. */
  7737. /* end of documentation of public members */
  7738. /*!
  7739. Constructs a QCustomPlot and sets reasonable default values.
  7740. */
  7741. QCustomPlot::QCustomPlot(QWidget* parent)
  7742. : QWidget(parent)
  7743. , xAxis(0)
  7744. , yAxis(0)
  7745. , xAxis2(0)
  7746. , yAxis2(0)
  7747. , legend(0)
  7748. , mPlotLayout(0)
  7749. , mAutoAddPlottableToLegend(true)
  7750. , mAntialiasedElements(QCP::aeNone)
  7751. , mNotAntialiasedElements(QCP::aeNone)
  7752. , mInteractions(0)
  7753. , mSelectionTolerance(8)
  7754. , mNoAntialiasingOnDrag(false)
  7755. , mBackgroundBrush(Qt::white, Qt::SolidPattern)
  7756. , mBackgroundScaled(true)
  7757. , mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding)
  7758. , mCurrentLayer(0)
  7759. , mPlottingHints(QCP::phCacheLabels | QCP::phForceRepaint)
  7760. , mMultiSelectModifier(Qt::ControlModifier)
  7761. , mPaintBuffer(size())
  7762. , mMouseEventElement(0)
  7763. , mReplotting(false)
  7764. // 增加游标
  7765. //, m_isShowTracer(false)
  7766. //, m_xTracer(Q_NULLPTR)
  7767. //, m_yTracer(Q_NULLPTR)
  7768. //, m_dataTracers(QList<XxwTracer*>())
  7769. //, m_lineTracer(Q_NULLPTR)
  7770. {
  7771. setAttribute(Qt::WA_NoMousePropagation);
  7772. setAttribute(Qt::WA_OpaquePaintEvent);
  7773. setMouseTracking(true);
  7774. QLocale currentLocale = locale();
  7775. currentLocale.setNumberOptions(QLocale::OmitGroupSeparator);
  7776. setLocale(currentLocale);
  7777. // create initial layers:
  7778. mLayers.append(new QCPLayer(this, QLatin1String("background")));
  7779. mLayers.append(new QCPLayer(this, QLatin1String("grid")));
  7780. mLayers.append(new QCPLayer(this, QLatin1String("main")));
  7781. mLayers.append(new QCPLayer(this, QLatin1String("axes")));
  7782. mLayers.append(new QCPLayer(this, QLatin1String("legend")));
  7783. updateLayerIndices();
  7784. setCurrentLayer(QLatin1String("main"));
  7785. // create initial layout, axis rect and legend:
  7786. mPlotLayout = new QCPLayoutGrid;
  7787. mPlotLayout->initializeParentPlot(this);
  7788. mPlotLayout->setParent(
  7789. this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will
  7790. // call QWidget::updateGeometry
  7791. mPlotLayout->setLayer(QLatin1String("main"));
  7792. QCPAxisRect* defaultAxisRect = new QCPAxisRect(this, true);
  7793. mPlotLayout->addElement(0, 0, defaultAxisRect);
  7794. xAxis = defaultAxisRect->axis(QCPAxis::atBottom);
  7795. yAxis = defaultAxisRect->axis(QCPAxis::atLeft);
  7796. xAxis2 = defaultAxisRect->axis(QCPAxis::atTop);
  7797. yAxis2 = defaultAxisRect->axis(QCPAxis::atRight);
  7798. legend = new QCPLegend;
  7799. legend->setVisible(false);
  7800. defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight | Qt::AlignTop);
  7801. defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12));
  7802. defaultAxisRect->setLayer(QLatin1String("background"));
  7803. xAxis->setLayer(QLatin1String("axes"));
  7804. yAxis->setLayer(QLatin1String("axes"));
  7805. xAxis2->setLayer(QLatin1String("axes"));
  7806. yAxis2->setLayer(QLatin1String("axes"));
  7807. xAxis->grid()->setLayer(QLatin1String("grid"));
  7808. yAxis->grid()->setLayer(QLatin1String("grid"));
  7809. xAxis2->grid()->setLayer(QLatin1String("grid"));
  7810. yAxis2->grid()->setLayer(QLatin1String("grid"));
  7811. legend->setLayer(QLatin1String("legend"));
  7812. setViewport(rect()); // needs to be called after mPlotLayout has been created
  7813. replot();
  7814. }
  7815. QCustomPlot::~QCustomPlot()
  7816. {
  7817. clearPlottables();
  7818. clearItems();
  7819. if (mPlotLayout) {
  7820. delete mPlotLayout;
  7821. mPlotLayout = 0;
  7822. }
  7823. mCurrentLayer = 0;
  7824. qDeleteAll(
  7825. mLayers); // don't use removeLayer, because it would prevent the last layer to be removed
  7826. mLayers.clear();
  7827. }
  7828. /*!
  7829. Sets which elements are forcibly drawn antialiased as an \a or combination of
  7830. QCP::AntialiasedElement.
  7831. This overrides the antialiasing settings for whole element groups, normally controlled with the
  7832. \a setAntialiasing function on the individual elements. If an element is neither specified in
  7833. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  7834. each individual element instance is used.
  7835. For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be
  7836. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  7837. to.
  7838. if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is
  7839. removed from there.
  7840. \see setNotAntialiasedElements
  7841. */
  7842. void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements& antialiasedElements)
  7843. {
  7844. mAntialiasedElements = antialiasedElements;
  7845. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  7846. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  7847. mNotAntialiasedElements |= ~mAntialiasedElements;
  7848. }
  7849. /*!
  7850. Sets whether the specified \a antialiasedElement is forcibly drawn antialiased.
  7851. See \ref setAntialiasedElements for details.
  7852. \see setNotAntialiasedElement
  7853. */
  7854. void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled)
  7855. {
  7856. if (!enabled && mAntialiasedElements.testFlag(antialiasedElement))
  7857. mAntialiasedElements &= ~antialiasedElement;
  7858. else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement))
  7859. mAntialiasedElements |= antialiasedElement;
  7860. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  7861. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  7862. mNotAntialiasedElements |= ~mAntialiasedElements;
  7863. }
  7864. /*!
  7865. Sets which elements are forcibly drawn not antialiased as an \a or combination of
  7866. QCP::AntialiasedElement.
  7867. This overrides the antialiasing settings for whole element groups, normally controlled with the
  7868. \a setAntialiasing function on the individual elements. If an element is neither specified in
  7869. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  7870. each individual element instance is used.
  7871. For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be
  7872. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  7873. to.
  7874. if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is
  7875. removed from there.
  7876. \see setAntialiasedElements
  7877. */
  7878. void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements& notAntialiasedElements)
  7879. {
  7880. mNotAntialiasedElements = notAntialiasedElements;
  7881. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  7882. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  7883. mAntialiasedElements |= ~mNotAntialiasedElements;
  7884. }
  7885. /*!
  7886. Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased.
  7887. See \ref setNotAntialiasedElements for details.
  7888. \see setAntialiasedElement
  7889. */
  7890. void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement,
  7891. bool enabled)
  7892. {
  7893. if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement))
  7894. mNotAntialiasedElements &= ~notAntialiasedElement;
  7895. else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement))
  7896. mNotAntialiasedElements |= notAntialiasedElement;
  7897. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  7898. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  7899. mAntialiasedElements |= ~mNotAntialiasedElements;
  7900. }
  7901. /*!
  7902. If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the
  7903. plottable to the legend (QCustomPlot::legend).
  7904. \see addPlottable, addGraph, QCPLegend::addItem
  7905. */
  7906. void QCustomPlot::setAutoAddPlottableToLegend(bool on)
  7907. {
  7908. mAutoAddPlottableToLegend = on;
  7909. }
  7910. /*!
  7911. Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction
  7912. enums. There are the following types of interactions:
  7913. <b>Axis range manipulation</b> is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom.
  7914. When the respective interaction is enabled, the user may drag axes ranges and zoom with the mouse
  7915. wheel. For details how to control which axes the user may drag/zoom and in what orientations, see
  7916. \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref
  7917. QCPAxisRect::setRangeDragAxes, \ref QCPAxisRect::setRangeZoomAxes.
  7918. <b>Plottable selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref
  7919. QCP::iSelectPlottables is set, the user may select plottables (graphs, curves, bars,...) by
  7920. clicking on them or in their vicinity (\ref setSelectionTolerance). Whether the user can actually
  7921. select a plottable can further be restricted with the \ref QCPAbstractPlottable::setSelectable
  7922. function on the specific plottable. To find out whether a specific plottable is selected, call
  7923. QCPAbstractPlottable::selected(). To retrieve a list of all currently selected plottables, call
  7924. \ref selectedPlottables. If you're only interested in QCPGraphs, you may use the convenience
  7925. function \ref selectedGraphs.
  7926. <b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set,
  7927. the user may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity.
  7928. To find out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a
  7929. list of all currently selected items, call \ref selectedItems.
  7930. <b>Axis selection</b> is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set,
  7931. the user may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base
  7932. line, tick labels, axis label) are selectable can be controlled via \ref
  7933. QCPAxis::setSelectableParts for each axis. To retrieve a list of all axes that currently contain
  7934. selected parts, call \ref selectedAxes. Which parts of an axis are selected, can be retrieved with
  7935. QCPAxis::selectedParts().
  7936. <b>Legend selection</b> is controlled with \ref QCP::iSelectLegend. If this is set, the user may
  7937. select the legend itself or individual items by clicking on them. What parts exactly are
  7938. selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the
  7939. legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To
  7940. find out which child items are selected, call \ref QCPLegend::selectedItems.
  7941. <b>All other selectable elements</b> The selection of all other selectable objects (e.g.
  7942. QCPPlotTitle, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set,
  7943. the user may select those objects by clicking on them. To find out which are currently selected,
  7944. you need to check their selected state explicitly.
  7945. If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is
  7946. emitted. Each selectable object additionally emits an individual selectionChanged signal whenever
  7947. their selection state has changed, i.e. not only by user interaction.
  7948. To allow multiple objects to be selected by holding the selection modifier (\ref
  7949. setMultiSelectModifier), set the flag \ref QCP::iMultiSelect.
  7950. \note In addition to the selection mechanism presented here, QCustomPlot always emits
  7951. corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and
  7952. \ref plottableDoubleClick for example.
  7953. \see setInteraction, setSelectionTolerance
  7954. */
  7955. void QCustomPlot::setInteractions(const QCP::Interactions& interactions)
  7956. {
  7957. mInteractions = interactions;
  7958. }
  7959. /*!
  7960. Sets the single \a interaction of this QCustomPlot to \a enabled.
  7961. For details about the interaction system, see \ref setInteractions.
  7962. \see setInteractions
  7963. */
  7964. void QCustomPlot::setInteraction(const QCP::Interaction& interaction, bool enabled)
  7965. {
  7966. if (!enabled && mInteractions.testFlag(interaction))
  7967. mInteractions &= ~interaction;
  7968. else if (enabled && !mInteractions.testFlag(interaction))
  7969. mInteractions |= interaction;
  7970. }
  7971. /*!
  7972. Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or
  7973. not.
  7974. If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a
  7975. potential selection when the minimum distance between the click position and the graph line is
  7976. smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks
  7977. directly inside the area and ignore this selection tolerance. In other words, it only has meaning
  7978. for parts of objects that are too thin to exactly hit with a click and thus need such a
  7979. tolerance.
  7980. \see setInteractions, QCPLayerable::selectTest
  7981. */
  7982. void QCustomPlot::setSelectionTolerance(int pixels)
  7983. {
  7984. mSelectionTolerance = pixels;
  7985. }
  7986. /*!
  7987. Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes
  7988. ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves
  7989. performance during dragging. Thus it creates a more responsive user experience. As soon as the
  7990. user stops dragging, the last replot is done with normal antialiasing, to restore high image
  7991. quality.
  7992. \see setAntialiasedElements, setNotAntialiasedElements
  7993. */
  7994. void QCustomPlot::setNoAntialiasingOnDrag(bool enabled)
  7995. {
  7996. mNoAntialiasingOnDrag = enabled;
  7997. }
  7998. /*!
  7999. Sets the plotting hints for this QCustomPlot instance as an \a or combination of
  8000. QCP::PlottingHint.
  8001. \see setPlottingHint
  8002. */
  8003. void QCustomPlot::setPlottingHints(const QCP::PlottingHints& hints)
  8004. {
  8005. mPlottingHints = hints;
  8006. }
  8007. /*!
  8008. Sets the specified plotting \a hint to \a enabled.
  8009. \see setPlottingHints
  8010. */
  8011. void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled)
  8012. {
  8013. QCP::PlottingHints newHints = mPlottingHints;
  8014. if (!enabled)
  8015. newHints &= ~hint;
  8016. else
  8017. newHints |= hint;
  8018. if (newHints != mPlottingHints)
  8019. setPlottingHints(newHints);
  8020. }
  8021. /*!
  8022. Sets the keyboard modifier that will be recognized as multi-select-modifier.
  8023. If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple
  8024. objects by clicking on them one after the other while holding down \a modifier.
  8025. By default the multi-select-modifier is set to Qt::ControlModifier.
  8026. \see setInteractions
  8027. */
  8028. void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier)
  8029. {
  8030. mMultiSelectModifier = modifier;
  8031. }
  8032. /*!
  8033. Sets the viewport of this QCustomPlot. The Viewport is the area that the top level layout
  8034. (QCustomPlot::plotLayout()) uses as its rect. Normally, the viewport is the entire widget rect.
  8035. This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref
  8036. savePdf, etc. by temporarily changing the viewport size.
  8037. */
  8038. void QCustomPlot::setViewport(const QRect& rect)
  8039. {
  8040. mViewport = rect;
  8041. if (mPlotLayout)
  8042. mPlotLayout->setOuterRect(mViewport);
  8043. }
  8044. /*!
  8045. Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn
  8046. below all other objects in the plot.
  8047. For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be
  8048. enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is
  8049. preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  8050. consider using the overloaded version of this function.
  8051. If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will
  8052. first be filled with that brush, before drawing the background pixmap. This can be useful for
  8053. background pixmaps with translucent areas.
  8054. \see setBackgroundScaled, setBackgroundScaledMode
  8055. */
  8056. void QCustomPlot::setBackground(const QPixmap& pm)
  8057. {
  8058. mBackgroundPixmap = pm;
  8059. mScaledBackgroundPixmap = QPixmap();
  8060. }
  8061. /*!
  8062. Sets the background brush of the viewport (see \ref setViewport).
  8063. Before drawing everything else, the background is filled with \a brush. If a background pixmap
  8064. was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport
  8065. before the background pixmap is drawn. This can be useful for background pixmaps with translucent
  8066. areas.
  8067. Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be
  8068. useful for exporting to image formats which support transparency, e.g. \ref savePng.
  8069. \see setBackgroundScaled, setBackgroundScaledMode
  8070. */
  8071. void QCustomPlot::setBackground(const QBrush& brush)
  8072. {
  8073. mBackgroundBrush = brush;
  8074. }
  8075. /*! \overload
  8076. Allows setting the background pixmap of the viewport, whether it shall be scaled and how it
  8077. shall be scaled in one call.
  8078. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  8079. */
  8080. void QCustomPlot::setBackground(const QPixmap& pm, bool scaled, Qt::AspectRatioMode mode)
  8081. {
  8082. mBackgroundPixmap = pm;
  8083. mScaledBackgroundPixmap = QPixmap();
  8084. mBackgroundScaled = scaled;
  8085. mBackgroundScaledMode = mode;
  8086. }
  8087. /*!
  8088. Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is
  8089. set to true, control whether and how the aspect ratio of the original pixmap is preserved with
  8090. \ref setBackgroundScaledMode.
  8091. Note that the scaled version of the original pixmap is buffered, so there is no performance
  8092. penalty on replots. (Except when the viewport dimensions are changed continuously.)
  8093. \see setBackground, setBackgroundScaledMode
  8094. */
  8095. void QCustomPlot::setBackgroundScaled(bool scaled)
  8096. {
  8097. mBackgroundScaled = scaled;
  8098. }
  8099. /*!
  8100. If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this
  8101. function to define whether and how the aspect ratio of the original pixmap is preserved.
  8102. \see setBackground, setBackgroundScaled
  8103. */
  8104. void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  8105. {
  8106. mBackgroundScaledMode = mode;
  8107. }
  8108. /*!
  8109. Returns the plottable with \a index. If the index is invalid, returns 0.
  8110. There is an overloaded version of this function with no parameter which returns the last added
  8111. plottable, see QCustomPlot::plottable()
  8112. \see plottableCount, addPlottable
  8113. */
  8114. QCPAbstractPlottable* QCustomPlot::plottable(int index)
  8115. {
  8116. if (index >= 0 && index < mPlottables.size()) {
  8117. return mPlottables.at(index);
  8118. } else {
  8119. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8120. return 0;
  8121. }
  8122. }
  8123. /*! \overload
  8124. Returns the last plottable that was added with \ref addPlottable. If there are no plottables in
  8125. the plot, returns 0.
  8126. \see plottableCount, addPlottable
  8127. */
  8128. QCPAbstractPlottable* QCustomPlot::plottable()
  8129. {
  8130. if (!mPlottables.isEmpty()) {
  8131. return mPlottables.last();
  8132. } else
  8133. return 0;
  8134. }
  8135. /*!
  8136. Adds the specified plottable to the plot and, if \ref setAutoAddPlottableToLegend is enabled, to
  8137. the legend (QCustomPlot::legend). QCustomPlot takes ownership of the plottable.
  8138. Returns true on success, i.e. when \a plottable isn't already in the plot and the parent plot of
  8139. \a plottable is this QCustomPlot (the latter is controlled by what axes were passed in the
  8140. plottable's constructor).
  8141. \see plottable, plottableCount, removePlottable, clearPlottables
  8142. */
  8143. bool QCustomPlot::addPlottable(QCPAbstractPlottable* plottable)
  8144. {
  8145. if (mPlottables.contains(plottable)) {
  8146. qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:"
  8147. << reinterpret_cast<quintptr>(plottable);
  8148. return false;
  8149. }
  8150. if (plottable->parentPlot() != this) {
  8151. qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:"
  8152. << reinterpret_cast<quintptr>(plottable);
  8153. return false;
  8154. }
  8155. mPlottables.append(plottable);
  8156. // possibly add plottable to legend:
  8157. if (mAutoAddPlottableToLegend)
  8158. plottable->addToLegend();
  8159. // special handling for QCPGraphs to maintain the simple graph interface:
  8160. if (QCPGraph* graph = qobject_cast<QCPGraph*>(plottable))
  8161. mGraphs.append(graph);
  8162. if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable
  8163. // (via QCPLayerable constructor)
  8164. plottable->setLayer(currentLayer());
  8165. return true;
  8166. }
  8167. /*!
  8168. Removes the specified plottable from the plot and, if necessary, from the legend
  8169. (QCustomPlot::legend).
  8170. Returns true on success.
  8171. \see addPlottable, clearPlottables
  8172. */
  8173. bool QCustomPlot::removePlottable(QCPAbstractPlottable* plottable)
  8174. {
  8175. if (!mPlottables.contains(plottable)) {
  8176. qDebug() << Q_FUNC_INFO
  8177. << "plottable not in list:" << reinterpret_cast<quintptr>(plottable);
  8178. return false;
  8179. }
  8180. // remove plottable from legend:
  8181. plottable->removeFromLegend();
  8182. // special handling for QCPGraphs to maintain the simple graph interface:
  8183. if (QCPGraph* graph = qobject_cast<QCPGraph*>(plottable))
  8184. mGraphs.removeOne(graph);
  8185. // remove plottable:
  8186. delete plottable;
  8187. mPlottables.removeOne(plottable);
  8188. return true;
  8189. }
  8190. /*! \overload
  8191. Removes the plottable by its \a index.
  8192. */
  8193. bool QCustomPlot::removePlottable(int index)
  8194. {
  8195. if (index >= 0 && index < mPlottables.size())
  8196. return removePlottable(mPlottables[index]);
  8197. else {
  8198. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8199. return false;
  8200. }
  8201. }
  8202. /*!
  8203. Removes all plottables from the plot (and the QCustomPlot::legend, if necessary).
  8204. Returns the number of plottables removed.
  8205. \see removePlottable
  8206. */
  8207. int QCustomPlot::clearPlottables()
  8208. {
  8209. int c = mPlottables.size();
  8210. for (int i = c - 1; i >= 0; --i)
  8211. removePlottable(mPlottables[i]);
  8212. return c;
  8213. }
  8214. /*!
  8215. Returns the number of currently existing plottables in the plot
  8216. \see plottable, addPlottable
  8217. */
  8218. int QCustomPlot::plottableCount() const
  8219. {
  8220. return mPlottables.size();
  8221. }
  8222. /*!
  8223. Returns a list of the selected plottables. If no plottables are currently selected, the list is
  8224. empty.
  8225. There is a convenience function if you're only interested in selected graphs, see \ref
  8226. selectedGraphs.
  8227. \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected
  8228. */
  8229. QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const
  8230. {
  8231. QList<QCPAbstractPlottable*> result;
  8232. foreach (QCPAbstractPlottable* plottable, mPlottables) {
  8233. if (plottable->selected())
  8234. result.append(plottable);
  8235. }
  8236. return result;
  8237. }
  8238. /*!
  8239. Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines
  8240. (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple
  8241. plottables come into consideration, the one closest to \a pos is returned.
  8242. If \a onlySelectable is true, only plottables that are selectable
  8243. (QCPAbstractPlottable::setSelectable) are considered.
  8244. If there is no plottable at \a pos, the return value is 0.
  8245. \see itemAt, layoutElementAt
  8246. */
  8247. QCPAbstractPlottable* QCustomPlot::plottableAt(const QPointF& pos, bool onlySelectable) const
  8248. {
  8249. QCPAbstractPlottable* resultPlottable = 0;
  8250. double resultDistance =
  8251. mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance
  8252. // as selections, so initialize with that value
  8253. foreach (QCPAbstractPlottable* plottable, mPlottables) {
  8254. if (onlySelectable
  8255. && !plottable
  8256. ->selectable()) // we could have also passed onlySelectable to the selectTest
  8257. // function, but checking here is faster, because we have access
  8258. // to QCPabstractPlottable::selectable
  8259. continue;
  8260. if ((plottable->keyAxis()->axisRect()->rect() & plottable->valueAxis()->axisRect()->rect())
  8261. .contains(pos.toPoint())) // only consider clicks inside the rect that is spanned by
  8262. // the plottable's key/value axes
  8263. {
  8264. double currentDistance = plottable->selectTest(pos, false);
  8265. if (currentDistance >= 0 && currentDistance < resultDistance) {
  8266. resultPlottable = plottable;
  8267. resultDistance = currentDistance;
  8268. }
  8269. }
  8270. }
  8271. return resultPlottable;
  8272. }
  8273. /*!
  8274. Returns whether this QCustomPlot instance contains the \a plottable.
  8275. \see addPlottable
  8276. */
  8277. bool QCustomPlot::hasPlottable(QCPAbstractPlottable* plottable) const
  8278. {
  8279. return mPlottables.contains(plottable);
  8280. }
  8281. /*!
  8282. Returns the graph with \a index. If the index is invalid, returns 0.
  8283. There is an overloaded version of this function with no parameter which returns the last created
  8284. graph, see QCustomPlot::graph()
  8285. \see graphCount, addGraph
  8286. */
  8287. QCPGraph* QCustomPlot::graph(int index) const
  8288. {
  8289. if (index >= 0 && index < mGraphs.size()) {
  8290. return mGraphs.at(index);
  8291. } else {
  8292. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8293. return 0;
  8294. }
  8295. }
  8296. /*! \overload
  8297. Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot,
  8298. returns 0.
  8299. \see graphCount, addGraph
  8300. */
  8301. QCPGraph* QCustomPlot::graph() const
  8302. {
  8303. if (!mGraphs.isEmpty()) {
  8304. return mGraphs.last();
  8305. } else
  8306. return 0;
  8307. }
  8308. /*!
  8309. Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the
  8310. bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a
  8311. keyAxis and \a valueAxis must reside in this QCustomPlot.
  8312. \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically
  8313. "y") for the graph.
  8314. Returns a pointer to the newly created graph, or 0 if adding the graph failed.
  8315. \see graph, graphCount, removeGraph, clearGraphs
  8316. */
  8317. QCPGraph* QCustomPlot::addGraph(QCPAxis* keyAxis, QCPAxis* valueAxis)
  8318. {
  8319. if (!keyAxis)
  8320. keyAxis = xAxis;
  8321. if (!valueAxis)
  8322. valueAxis = yAxis;
  8323. if (!keyAxis || !valueAxis) {
  8324. qDebug() << Q_FUNC_INFO
  8325. << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid "
  8326. "(has been deleted)";
  8327. return 0;
  8328. }
  8329. if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this) {
  8330. qDebug() << Q_FUNC_INFO
  8331. << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent";
  8332. return 0;
  8333. }
  8334. QCPGraph* newGraph = new QCPGraph(keyAxis, valueAxis);
  8335. if (addPlottable(newGraph)) {
  8336. newGraph->setName(QLatin1String("Graph ") + QString::number(mGraphs.size()));
  8337. return newGraph;
  8338. } else {
  8339. delete newGraph;
  8340. return 0;
  8341. }
  8342. }
  8343. /*!
  8344. Removes the specified \a graph from the plot and, if necessary, from the QCustomPlot::legend. If
  8345. any other graphs in the plot have a channel fill set towards the removed graph, the channel fill
  8346. property of those graphs is reset to zero (no channel fill).
  8347. Returns true on success.
  8348. \see clearGraphs
  8349. */
  8350. bool QCustomPlot::removeGraph(QCPGraph* graph)
  8351. {
  8352. return removePlottable(graph);
  8353. }
  8354. /*! \overload
  8355. Removes the graph by its \a index.
  8356. */
  8357. bool QCustomPlot::removeGraph(int index)
  8358. {
  8359. if (index >= 0 && index < mGraphs.size())
  8360. return removeGraph(mGraphs[index]);
  8361. else
  8362. return false;
  8363. }
  8364. /*!
  8365. Removes all graphs from the plot (and the QCustomPlot::legend, if necessary).
  8366. Returns the number of graphs removed.
  8367. \see removeGraph
  8368. */
  8369. int QCustomPlot::clearGraphs()
  8370. {
  8371. int c = mGraphs.size();
  8372. for (int i = c - 1; i >= 0; --i)
  8373. removeGraph(mGraphs[i]);
  8374. return c;
  8375. }
  8376. /*!
  8377. Returns the number of currently existing graphs in the plot
  8378. \see graph, addGraph
  8379. */
  8380. int QCustomPlot::graphCount() const
  8381. {
  8382. return mGraphs.size();
  8383. }
  8384. /*!
  8385. Returns a list of the selected graphs. If no graphs are currently selected, the list is empty.
  8386. If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars,
  8387. etc., use \ref selectedPlottables.
  8388. \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable,
  8389. QCPAbstractPlottable::setSelected
  8390. */
  8391. QList<QCPGraph*> QCustomPlot::selectedGraphs() const
  8392. {
  8393. QList<QCPGraph*> result;
  8394. foreach (QCPGraph* graph, mGraphs) {
  8395. if (graph->selected())
  8396. result.append(graph);
  8397. }
  8398. return result;
  8399. }
  8400. /*!
  8401. Returns the item with \a index. If the index is invalid, returns 0.
  8402. There is an overloaded version of this function with no parameter which returns the last added
  8403. item, see QCustomPlot::item()
  8404. \see itemCount, addItem
  8405. */
  8406. QCPAbstractItem* QCustomPlot::item(int index) const
  8407. {
  8408. if (index >= 0 && index < mItems.size()) {
  8409. return mItems.at(index);
  8410. } else {
  8411. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8412. return 0;
  8413. }
  8414. }
  8415. /*! \overload
  8416. Returns the last item, that was added with \ref addItem. If there are no items in the plot,
  8417. returns 0.
  8418. \see itemCount, addItem
  8419. */
  8420. QCPAbstractItem* QCustomPlot::item() const
  8421. {
  8422. if (!mItems.isEmpty()) {
  8423. return mItems.last();
  8424. } else
  8425. return 0;
  8426. }
  8427. /*!
  8428. Adds the specified item to the plot. QCustomPlot takes ownership of the item.
  8429. Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
  8430. item is this QCustomPlot.
  8431. \see item, itemCount, removeItem, clearItems
  8432. */
  8433. bool QCustomPlot::addItem(QCPAbstractItem* item)
  8434. {
  8435. if (!mItems.contains(item) && item->parentPlot() == this) {
  8436. mItems.append(item);
  8437. return true;
  8438. } else {
  8439. qDebug() << Q_FUNC_INFO
  8440. << "item either already in list or not created with this QCustomPlot as parent:"
  8441. << reinterpret_cast<quintptr>(item);
  8442. return false;
  8443. }
  8444. }
  8445. /*!
  8446. Removes the specified item from the plot.
  8447. Returns true on success.
  8448. \see addItem, clearItems
  8449. */
  8450. bool QCustomPlot::removeItem(QCPAbstractItem* item)
  8451. {
  8452. if (mItems.contains(item)) {
  8453. delete item;
  8454. mItems.removeOne(item);
  8455. return true;
  8456. } else {
  8457. qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast<quintptr>(item);
  8458. return false;
  8459. }
  8460. }
  8461. /*! \overload
  8462. Removes the item by its \a index.
  8463. */
  8464. bool QCustomPlot::removeItem(int index)
  8465. {
  8466. if (index >= 0 && index < mItems.size())
  8467. return removeItem(mItems[index]);
  8468. else {
  8469. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8470. return false;
  8471. }
  8472. }
  8473. /*!
  8474. Removes all items from the plot.
  8475. Returns the number of items removed.
  8476. \see removeItem
  8477. */
  8478. int QCustomPlot::clearItems()
  8479. {
  8480. int c = mItems.size();
  8481. for (int i = c - 1; i >= 0; --i)
  8482. removeItem(mItems[i]);
  8483. return c;
  8484. }
  8485. /*!
  8486. Returns the number of currently existing items in the plot
  8487. \see item, addItem
  8488. */
  8489. int QCustomPlot::itemCount() const
  8490. {
  8491. return mItems.size();
  8492. }
  8493. /*!
  8494. Returns a list of the selected items. If no items are currently selected, the list is empty.
  8495. \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected
  8496. */
  8497. QList<QCPAbstractItem*> QCustomPlot::selectedItems() const
  8498. {
  8499. QList<QCPAbstractItem*> result;
  8500. foreach (QCPAbstractItem* item, mItems) {
  8501. if (item->selected())
  8502. result.append(item);
  8503. }
  8504. return result;
  8505. }
  8506. /*!
  8507. Returns the item at the pixel position \a pos. Items that only consist of single lines (e.g. \ref
  8508. QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref
  8509. setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is
  8510. returned.
  8511. If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are
  8512. considered.
  8513. If there is no item at \a pos, the return value is 0.
  8514. \see plottableAt, layoutElementAt
  8515. */
  8516. QCPAbstractItem* QCustomPlot::itemAt(const QPointF& pos, bool onlySelectable) const
  8517. {
  8518. QCPAbstractItem* resultItem = 0;
  8519. double resultDistance =
  8520. mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance
  8521. // as selections, so initialize with that value
  8522. foreach (QCPAbstractItem* item, mItems) {
  8523. if (onlySelectable
  8524. && !item->selectable()) // we could have also passed onlySelectable to the selectTest
  8525. // function, but checking here is faster, because we have access
  8526. // to QCPAbstractItem::selectable
  8527. continue;
  8528. if (!item->clipToAxisRect()
  8529. || item->clipRect().contains(
  8530. pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually
  8531. // clipped to it
  8532. {
  8533. double currentDistance = item->selectTest(pos, false);
  8534. if (currentDistance >= 0 && currentDistance < resultDistance) {
  8535. resultItem = item;
  8536. resultDistance = currentDistance;
  8537. }
  8538. }
  8539. }
  8540. return resultItem;
  8541. }
  8542. /*!
  8543. Returns whether this QCustomPlot contains the \a item.
  8544. \see addItem
  8545. */
  8546. bool QCustomPlot::hasItem(QCPAbstractItem* item) const
  8547. {
  8548. return mItems.contains(item);
  8549. }
  8550. /*!
  8551. Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is
  8552. returned.
  8553. Layer names are case-sensitive.
  8554. \see addLayer, moveLayer, removeLayer
  8555. */
  8556. QCPLayer* QCustomPlot::layer(const QString& name) const
  8557. {
  8558. foreach (QCPLayer* layer, mLayers) {
  8559. if (layer->name() == name)
  8560. return layer;
  8561. }
  8562. return 0;
  8563. }
  8564. /*! \overload
  8565. Returns the layer by \a index. If the index is invalid, 0 is returned.
  8566. \see addLayer, moveLayer, removeLayer
  8567. */
  8568. QCPLayer* QCustomPlot::layer(int index) const
  8569. {
  8570. if (index >= 0 && index < mLayers.size()) {
  8571. return mLayers.at(index);
  8572. } else {
  8573. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  8574. return 0;
  8575. }
  8576. }
  8577. /*!
  8578. Returns the layer that is set as current layer (see \ref setCurrentLayer).
  8579. */
  8580. QCPLayer* QCustomPlot::currentLayer() const
  8581. {
  8582. return mCurrentLayer;
  8583. }
  8584. /*!
  8585. Sets the layer with the specified \a name to be the current layer. All layerables (\ref
  8586. QCPLayerable), e.g. plottables and items, are created on the current layer.
  8587. Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot.
  8588. Layer names are case-sensitive.
  8589. \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer
  8590. */
  8591. bool QCustomPlot::setCurrentLayer(const QString& name)
  8592. {
  8593. if (QCPLayer* newCurrentLayer = layer(name)) {
  8594. return setCurrentLayer(newCurrentLayer);
  8595. } else {
  8596. qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name;
  8597. return false;
  8598. }
  8599. }
  8600. /*! \overload
  8601. Sets the provided \a layer to be the current layer.
  8602. Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot.
  8603. \see addLayer, moveLayer, removeLayer
  8604. */
  8605. bool QCustomPlot::setCurrentLayer(QCPLayer* layer)
  8606. {
  8607. if (!mLayers.contains(layer)) {
  8608. qDebug() << Q_FUNC_INFO
  8609. << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  8610. return false;
  8611. }
  8612. mCurrentLayer = layer;
  8613. return true;
  8614. }
  8615. /*!
  8616. Returns the number of currently existing layers in the plot
  8617. \see layer, addLayer
  8618. */
  8619. int QCustomPlot::layerCount() const
  8620. {
  8621. return mLayers.size();
  8622. }
  8623. /*!
  8624. Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which
  8625. must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer.
  8626. Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a
  8627. valid layer inside this QCustomPlot.
  8628. If \a otherLayer is 0, the highest layer in the QCustomPlot will be used.
  8629. For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer.
  8630. \see layer, moveLayer, removeLayer
  8631. */
  8632. bool QCustomPlot::addLayer(const QString& name, QCPLayer* otherLayer,
  8633. QCustomPlot::LayerInsertMode insertMode)
  8634. {
  8635. if (!otherLayer)
  8636. otherLayer = mLayers.last();
  8637. if (!mLayers.contains(otherLayer)) {
  8638. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:"
  8639. << reinterpret_cast<quintptr>(otherLayer);
  8640. return false;
  8641. }
  8642. if (layer(name)) {
  8643. qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name;
  8644. return false;
  8645. }
  8646. QCPLayer* newLayer = new QCPLayer(this, name);
  8647. mLayers.insert(otherLayer->index() + (insertMode == limAbove ? 1 : 0), newLayer);
  8648. updateLayerIndices();
  8649. return true;
  8650. }
  8651. /*!
  8652. Removes the specified \a layer and returns true on success.
  8653. All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below
  8654. \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both
  8655. cases, the total rendering order of all layerables in the QCustomPlot is preserved.
  8656. If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom
  8657. layer) becomes the new current layer.
  8658. It is not possible to remove the last layer of the plot.
  8659. \see layer, addLayer, moveLayer
  8660. */
  8661. bool QCustomPlot::removeLayer(QCPLayer* layer)
  8662. {
  8663. if (!mLayers.contains(layer)) {
  8664. qDebug() << Q_FUNC_INFO
  8665. << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  8666. return false;
  8667. }
  8668. if (mLayers.size() < 2) {
  8669. qDebug() << Q_FUNC_INFO << "can't remove last layer";
  8670. return false;
  8671. }
  8672. // append all children of this layer to layer below (if this is lowest layer, prepend to layer
  8673. // above)
  8674. int removedIndex = layer->index();
  8675. bool isFirstLayer = removedIndex == 0;
  8676. QCPLayer* targetLayer =
  8677. isFirstLayer ? mLayers.at(removedIndex + 1) : mLayers.at(removedIndex - 1);
  8678. QList<QCPLayerable*> children = layer->children();
  8679. if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same)
  8680. {
  8681. for (int i = children.size() - 1; i >= 0; --i)
  8682. children.at(i)->moveToLayer(targetLayer, true);
  8683. } else // append normally
  8684. {
  8685. for (int i = 0; i < children.size(); ++i)
  8686. children.at(i)->moveToLayer(targetLayer, false);
  8687. }
  8688. // if removed layer is current layer, change current layer to layer below/above:
  8689. if (layer == mCurrentLayer)
  8690. setCurrentLayer(targetLayer);
  8691. // remove layer:
  8692. delete layer;
  8693. mLayers.removeOne(layer);
  8694. updateLayerIndices();
  8695. return true;
  8696. }
  8697. /*!
  8698. Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or
  8699. below is controlled with \a insertMode.
  8700. Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the
  8701. QCustomPlot.
  8702. \see layer, addLayer, moveLayer
  8703. */
  8704. bool QCustomPlot::moveLayer(QCPLayer* layer, QCPLayer* otherLayer,
  8705. QCustomPlot::LayerInsertMode insertMode)
  8706. {
  8707. if (!mLayers.contains(layer)) {
  8708. qDebug() << Q_FUNC_INFO
  8709. << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  8710. return false;
  8711. }
  8712. if (!mLayers.contains(otherLayer)) {
  8713. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:"
  8714. << reinterpret_cast<quintptr>(otherLayer);
  8715. return false;
  8716. }
  8717. if (layer->index() > otherLayer->index())
  8718. mLayers.move(layer->index(), otherLayer->index() + (insertMode == limAbove ? 1 : 0));
  8719. else if (layer->index() < otherLayer->index())
  8720. mLayers.move(layer->index(), otherLayer->index() + (insertMode == limAbove ? 0 : -1));
  8721. updateLayerIndices();
  8722. return true;
  8723. }
  8724. /*!
  8725. Returns the number of axis rects in the plot.
  8726. All axis rects can be accessed via QCustomPlot::axisRect().
  8727. Initially, only one axis rect exists in the plot.
  8728. \see axisRect, axisRects
  8729. */
  8730. int QCustomPlot::axisRectCount() const
  8731. {
  8732. return axisRects().size();
  8733. }
  8734. /*!
  8735. Returns the axis rect with \a index.
  8736. Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were
  8737. added, all of them may be accessed with this function in a linear fashion (even when they are
  8738. nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout).
  8739. \see axisRectCount, axisRects
  8740. */
  8741. QCPAxisRect* QCustomPlot::axisRect(int index) const
  8742. {
  8743. const QList<QCPAxisRect*> rectList = axisRects();
  8744. if (index >= 0 && index < rectList.size()) {
  8745. return rectList.at(index);
  8746. } else {
  8747. qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index;
  8748. return 0;
  8749. }
  8750. }
  8751. /*!
  8752. Returns all axis rects in the plot.
  8753. \see axisRectCount, axisRect
  8754. */
  8755. QList<QCPAxisRect*> QCustomPlot::axisRects() const
  8756. {
  8757. QList<QCPAxisRect*> result;
  8758. QStack<QCPLayoutElement*> elementStack;
  8759. if (mPlotLayout)
  8760. elementStack.push(mPlotLayout);
  8761. while (!elementStack.isEmpty()) {
  8762. foreach (QCPLayoutElement* element, elementStack.pop()->elements(false)) {
  8763. if (element) {
  8764. elementStack.push(element);
  8765. if (QCPAxisRect* ar = qobject_cast<QCPAxisRect*>(element))
  8766. result.append(ar);
  8767. }
  8768. }
  8769. }
  8770. return result;
  8771. }
  8772. /*!
  8773. Returns the layout element at pixel position \a pos. If there is no element at that position,
  8774. returns 0.
  8775. Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on
  8776. any of its parent elements is set to false, it will not be considered.
  8777. \see itemAt, plottableAt
  8778. */
  8779. QCPLayoutElement* QCustomPlot::layoutElementAt(const QPointF& pos) const
  8780. {
  8781. QCPLayoutElement* currentElement = mPlotLayout;
  8782. bool searchSubElements = true;
  8783. while (searchSubElements && currentElement) {
  8784. searchSubElements = false;
  8785. foreach (QCPLayoutElement* subElement, currentElement->elements(false)) {
  8786. if (subElement && subElement->realVisibility()
  8787. && subElement->selectTest(pos, false) >= 0) {
  8788. currentElement = subElement;
  8789. searchSubElements = true;
  8790. break;
  8791. }
  8792. }
  8793. }
  8794. return currentElement;
  8795. }
  8796. /*!
  8797. Returns the axes that currently have selected parts, i.e. whose selection state is not \ref
  8798. QCPAxis::spNone.
  8799. \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts,
  8800. QCPAxis::setSelectableParts
  8801. */
  8802. QList<QCPAxis*> QCustomPlot::selectedAxes() const
  8803. {
  8804. QList<QCPAxis*> result, allAxes;
  8805. foreach (QCPAxisRect* rect, axisRects())
  8806. allAxes << rect->axes();
  8807. foreach (QCPAxis* axis, allAxes) {
  8808. if (axis->selectedParts() != QCPAxis::spNone)
  8809. result.append(axis);
  8810. }
  8811. return result;
  8812. }
  8813. /*!
  8814. Returns the legends that currently have selected parts, i.e. whose selection state is not \ref
  8815. QCPLegend::spNone.
  8816. \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts,
  8817. QCPLegend::setSelectableParts, QCPLegend::selectedItems
  8818. */
  8819. QList<QCPLegend*> QCustomPlot::selectedLegends() const
  8820. {
  8821. QList<QCPLegend*> result;
  8822. QStack<QCPLayoutElement*> elementStack;
  8823. if (mPlotLayout)
  8824. elementStack.push(mPlotLayout);
  8825. while (!elementStack.isEmpty()) {
  8826. foreach (QCPLayoutElement* subElement, elementStack.pop()->elements(false)) {
  8827. if (subElement) {
  8828. elementStack.push(subElement);
  8829. if (QCPLegend* leg = qobject_cast<QCPLegend*>(subElement)) {
  8830. if (leg->selectedParts() != QCPLegend::spNone)
  8831. result.append(leg);
  8832. }
  8833. }
  8834. }
  8835. }
  8836. return result;
  8837. }
  8838. /*!
  8839. Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot.
  8840. Since calling this function is not a user interaction, this does not emit the \ref
  8841. selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the
  8842. objects were previously selected.
  8843. \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends
  8844. */
  8845. void QCustomPlot::deselectAll()
  8846. {
  8847. foreach (QCPLayer* layer, mLayers) {
  8848. foreach (QCPLayerable* layerable, layer->children())
  8849. layerable->deselectEvent(0);
  8850. }
  8851. }
  8852. /*!
  8853. Causes a complete replot into the internal buffer. Finally, update() is called, to redraw the
  8854. buffer on the QCustomPlot widget surface. This is the method that must be called to make changes,
  8855. for example on the axis ranges or data points of graphs, visible.
  8856. Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the
  8857. QCustomPlot widget and user interactions (object selection and range dragging/zooming).
  8858. Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref
  8859. afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two
  8860. signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite
  8861. recursion.
  8862. */
  8863. void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority)
  8864. {
  8865. if (mReplotting) // incase signals loop back to replot slot
  8866. return;
  8867. mReplotting = true;
  8868. emit beforeReplot();
  8869. mPaintBuffer.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color()
  8870. : Qt::transparent);
  8871. QCPPainter painter;
  8872. painter.begin(&mPaintBuffer);
  8873. if (painter.isActive()) {
  8874. painter.setRenderHint(
  8875. QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the
  8876. // OpenGL graphicssystem
  8877. if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush)
  8878. painter.fillRect(mViewport, mBackgroundBrush);
  8879. draw(&painter);
  8880. painter.end();
  8881. if ((refreshPriority == rpHint && mPlottingHints.testFlag(QCP::phForceRepaint))
  8882. || refreshPriority == rpImmediate)
  8883. repaint();
  8884. else
  8885. update();
  8886. } else // might happen if QCustomPlot has width or height zero
  8887. qDebug() << Q_FUNC_INFO
  8888. << "Couldn't activate painter on buffer. This usually happens because QCustomPlot "
  8889. "has width or height zero.";
  8890. emit afterReplot();
  8891. mReplotting = false;
  8892. }
  8893. /*!
  8894. Rescales the axes such that all plottables (like graphs) in the plot are fully visible.
  8895. if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to
  8896. true (QCPLayerable::setVisible), will be used to rescale the axes.
  8897. \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale
  8898. */
  8899. void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
  8900. {
  8901. QList<QCPAxis*> allAxes;
  8902. foreach (QCPAxisRect* rect, axisRects())
  8903. allAxes << rect->axes();
  8904. foreach (QCPAxis* axis, allAxes)
  8905. axis->rescale(onlyVisiblePlottables);
  8906. }
  8907. /*!
  8908. Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale
  8909. of texts and lines will be derived from the specified \a width and \a height. This means, the
  8910. output will look like the normal on-screen output of a QCustomPlot widget with the corresponding
  8911. pixel width and height. If either \a width or \a height is zero, the exported image will have the
  8912. same dimensions as the QCustomPlot widget currently has.
  8913. \a noCosmeticPen disables the use of cosmetic pens when drawing to the PDF file. Cosmetic pens
  8914. are pens with numerical width 0, which are always drawn as a one pixel wide line, no matter what
  8915. zoom factor is set in the PDF-Viewer. For more information about cosmetic pens, see the QPainter
  8916. and QPen documentation.
  8917. The objects of the plot will appear in the current selection state. If you don't want any
  8918. selected objects to be painted in their selected look, deselect everything with \ref deselectAll
  8919. before calling this function.
  8920. Returns true on success.
  8921. \warning
  8922. \li If you plan on editing the exported PDF file with a vector graphics editor like
  8923. Inkscape, it is advised to set \a noCosmeticPen to true to avoid losing those cosmetic lines
  8924. (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks).
  8925. \li If calling this function inside the constructor of the parent of the QCustomPlot widget
  8926. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  8927. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  8928. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  8929. aren't defined yet inside the constructor, so you would get an image that has strange
  8930. widths/heights.
  8931. \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting
  8932. PDF file.
  8933. \note On Android systems, this method does nothing and issues an according qDebug warning
  8934. message. This is also the case if for other reasons the define flag QT_NO_PRINTER is set.
  8935. \see savePng, saveBmp, saveJpg, saveRastered
  8936. */
  8937. bool QCustomPlot::savePdf(const QString& fileName, bool noCosmeticPen, int width, int height,
  8938. const QString& pdfCreator, const QString& pdfTitle)
  8939. {
  8940. bool success = false;
  8941. #ifdef QT_NO_PRINTER
  8942. Q_UNUSED(fileName)
  8943. Q_UNUSED(noCosmeticPen)
  8944. Q_UNUSED(width)
  8945. Q_UNUSED(height)
  8946. Q_UNUSED(pdfCreator)
  8947. Q_UNUSED(pdfTitle)
  8948. qDebug() << Q_FUNC_INFO
  8949. << "Qt was built without printer support (QT_NO_PRINTER). PDF not created.";
  8950. #else
  8951. int newWidth, newHeight;
  8952. if (width == 0 || height == 0) {
  8953. newWidth = this->width();
  8954. newHeight = this->height();
  8955. } else {
  8956. newWidth = width;
  8957. newHeight = height;
  8958. }
  8959. QPrinter printer(QPrinter::ScreenResolution);
  8960. printer.setOutputFileName(fileName);
  8961. printer.setOutputFormat(QPrinter::PdfFormat);
  8962. printer.setColorMode(QPrinter::Color);
  8963. printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator);
  8964. printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle);
  8965. QRect oldViewport = viewport();
  8966. setViewport(QRect(0, 0, newWidth, newHeight));
  8967. #if QT_VERSION < QT_VERSION_CHECK(5, 3, 0)
  8968. printer.setFullPage(true);
  8969. printer.setPaperSize(viewport().size(), QPrinter::DevicePixel);
  8970. #else
  8971. QPageLayout pageLayout;
  8972. pageLayout.setMode(QPageLayout::FullPageMode);
  8973. pageLayout.setOrientation(QPageLayout::Portrait);
  8974. pageLayout.setMargins(QMarginsF(0, 0, 0, 0));
  8975. pageLayout.setPageSize(
  8976. QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch));
  8977. printer.setPageLayout(pageLayout);
  8978. #endif
  8979. QCPPainter printpainter;
  8980. if (printpainter.begin(&printer)) {
  8981. printpainter.setMode(QCPPainter::pmVectorized);
  8982. printpainter.setMode(QCPPainter::pmNoCaching);
  8983. printpainter.setMode(QCPPainter::pmNonCosmetic, noCosmeticPen);
  8984. printpainter.setWindow(mViewport);
  8985. if (mBackgroundBrush.style() != Qt::NoBrush && mBackgroundBrush.color() != Qt::white
  8986. && mBackgroundBrush.color() != Qt::transparent
  8987. && mBackgroundBrush.color().alpha()
  8988. > 0) // draw pdf background color if not white/transparent
  8989. printpainter.fillRect(viewport(), mBackgroundBrush);
  8990. draw(&printpainter);
  8991. printpainter.end();
  8992. success = true;
  8993. }
  8994. setViewport(oldViewport);
  8995. #endif // QT_NO_PRINTER
  8996. return success;
  8997. }
  8998. /*!
  8999. Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width
  9000. and \a height in pixels. If either \a width or \a height is zero, the exported image will have
  9001. the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
  9002. scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  9003. parameter.
  9004. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with
  9005. an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line
  9006. widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have
  9007. full 200*200 pixel resolution.
  9008. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
  9009. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  9010. QCustomPlot to place objects with sub-pixel accuracy.
  9011. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  9012. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  9013. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  9014. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  9015. aren't defined yet inside the constructor, so you would get an image that has strange
  9016. widths/heights.
  9017. The objects of the plot will appear in the current selection state. If you don't want any selected
  9018. objects to be painted in their selected look, deselect everything with \ref deselectAll before
  9019. calling this function.
  9020. If you want the PNG to have a transparent background, call \ref setBackground(const QBrush
  9021. &brush) with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
  9022. PNG compression can be controlled with the \a quality parameter which must be between 0 and 100 or
  9023. -1 to use the default setting.
  9024. Returns true on success. If this function fails, most likely the PNG format isn't supported by
  9025. the system, see Qt docs about QImageWriter::supportedImageFormats().
  9026. \see savePdf, saveBmp, saveJpg, saveRastered
  9027. */
  9028. bool QCustomPlot::savePng(const QString& fileName, int width, int height, double scale, int quality)
  9029. {
  9030. return saveRastered(fileName, width, height, scale, "PNG", quality);
  9031. }
  9032. /*!
  9033. Saves a JPG image file to \a fileName on disc. The output plot will have the dimensions \a width
  9034. and \a height in pixels. If either \a width or \a height is zero, the exported image will have
  9035. the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
  9036. scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  9037. parameter.
  9038. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with
  9039. an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line
  9040. widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have
  9041. full 200*200 pixel resolution.
  9042. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
  9043. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  9044. QCustomPlot to place objects with sub-pixel accuracy.
  9045. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  9046. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  9047. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  9048. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  9049. aren't defined yet inside the constructor, so you would get an image that has strange
  9050. widths/heights.
  9051. The objects of the plot will appear in the current selection state. If you don't want any selected
  9052. objects to be painted in their selected look, deselect everything with \ref deselectAll before
  9053. calling this function.
  9054. JPG compression can be controlled with the \a quality parameter which must be between 0 and 100 or
  9055. -1 to use the default setting.
  9056. Returns true on success. If this function fails, most likely the JPG format isn't supported by
  9057. the system, see Qt docs about QImageWriter::supportedImageFormats().
  9058. \see savePdf, savePng, saveBmp, saveRastered
  9059. */
  9060. bool QCustomPlot::saveJpg(const QString& fileName, int width, int height, double scale, int quality)
  9061. {
  9062. return saveRastered(fileName, width, height, scale, "JPG", quality);
  9063. }
  9064. /*!
  9065. Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width
  9066. and \a height in pixels. If either \a width or \a height is zero, the exported image will have
  9067. the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not
  9068. scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  9069. parameter.
  9070. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with
  9071. an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line
  9072. widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have
  9073. full 200*200 pixel resolution.
  9074. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via
  9075. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  9076. QCustomPlot to place objects with sub-pixel accuracy.
  9077. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  9078. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  9079. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  9080. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  9081. aren't defined yet inside the constructor, so you would get an image that has strange
  9082. widths/heights.
  9083. The objects of the plot will appear in the current selection state. If you don't want any selected
  9084. objects to be painted in their selected look, deselect everything with \ref deselectAll before
  9085. calling this function.
  9086. Returns true on success. If this function fails, most likely the BMP format isn't supported by
  9087. the system, see Qt docs about QImageWriter::supportedImageFormats().
  9088. \see savePdf, savePng, saveJpg, saveRastered
  9089. */
  9090. bool QCustomPlot::saveBmp(const QString& fileName, int width, int height, double scale)
  9091. {
  9092. return saveRastered(fileName, width, height, scale, "BMP");
  9093. }
  9094. /*! \internal
  9095. Returns a minimum size hint that corresponds to the minimum size of the top level layout
  9096. (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum
  9097. size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot.
  9098. This is especially important, when placed in a QLayout where other components try to take in as
  9099. much space as possible (e.g. QMdiArea).
  9100. */
  9101. QSize QCustomPlot::minimumSizeHint() const
  9102. {
  9103. return mPlotLayout->minimumSizeHint();
  9104. }
  9105. /*! \internal
  9106. Returns a size hint that is the same as \ref minimumSizeHint.
  9107. */
  9108. QSize QCustomPlot::sizeHint() const
  9109. {
  9110. return mPlotLayout->minimumSizeHint();
  9111. }
  9112. /*! \internal
  9113. Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot,
  9114. but draws the internal buffer on the widget surface.
  9115. */
  9116. void QCustomPlot::paintEvent(QPaintEvent* event)
  9117. {
  9118. Q_UNUSED(event);
  9119. QPainter painter(this);
  9120. painter.drawPixmap(0, 0, mPaintBuffer);
  9121. }
  9122. /*! \internal
  9123. Event handler for a resize of the QCustomPlot widget. Causes the internal buffer to be resized to
  9124. the new size. The viewport (which becomes the outer rect of mPlotLayout) is resized
  9125. appropriately. Finally a \ref replot is performed.
  9126. */
  9127. void QCustomPlot::resizeEvent(QResizeEvent* event)
  9128. {
  9129. // resize and repaint the buffer:
  9130. mPaintBuffer = QPixmap(event->size());
  9131. setViewport(rect());
  9132. replot(
  9133. rpQueued); // queued update is important here, to prevent painting issues in some contexts
  9134. }
  9135. /*! \internal
  9136. Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then emits
  9137. the specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
  9138. axisDoubleClick, etc.). Finally determines the affected layout element and forwards the event to
  9139. it.
  9140. \see mousePressEvent, mouseReleaseEvent
  9141. */
  9142. void QCustomPlot::mouseDoubleClickEvent(QMouseEvent* event)
  9143. {
  9144. emit mouseDoubleClick(event);
  9145. QVariant details;
  9146. QCPLayerable* clickedLayerable = layerableAt(event->pos(), false, &details);
  9147. // emit specialized object double click signals:
  9148. if (QCPAbstractPlottable* ap = qobject_cast<QCPAbstractPlottable*>(clickedLayerable))
  9149. emit plottableDoubleClick(ap, event);
  9150. else if (QCPAxis* ax = qobject_cast<QCPAxis*>(clickedLayerable))
  9151. emit axisDoubleClick(ax, details.value<QCPAxis::SelectablePart>(), event);
  9152. else if (QCPAbstractItem* ai = qobject_cast<QCPAbstractItem*>(clickedLayerable))
  9153. emit itemDoubleClick(ai, event);
  9154. else if (QCPLegend* lg = qobject_cast<QCPLegend*>(clickedLayerable))
  9155. emit legendDoubleClick(lg, 0, event);
  9156. else if (QCPAbstractLegendItem* li = qobject_cast<QCPAbstractLegendItem*>(clickedLayerable))
  9157. emit legendDoubleClick(li->parentLegend(), li, event);
  9158. else if (QCPPlotTitle* pt = qobject_cast<QCPPlotTitle*>(clickedLayerable))
  9159. emit titleDoubleClick(event, pt);
  9160. // call double click event of affected layout element:
  9161. if (QCPLayoutElement* el = layoutElementAt(event->pos()))
  9162. el->mouseDoubleClickEvent(event);
  9163. // call release event of affected layout element (as in mouseReleaseEvent, since the
  9164. // mouseDoubleClick replaces the second release event in double click case):
  9165. if (mMouseEventElement) {
  9166. mMouseEventElement->mouseReleaseEvent(event);
  9167. mMouseEventElement = 0;
  9168. }
  9169. // QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would
  9170. // just cause a mousePress/ReleaseEvent, which we don't want.
  9171. }
  9172. /*! \internal
  9173. Event handler for when a mouse button is pressed. Emits the mousePress signal. Then determines
  9174. the affected layout element and forwards the event to it.
  9175. \see mouseMoveEvent, mouseReleaseEvent
  9176. */
  9177. void QCustomPlot::mousePressEvent(QMouseEvent* event)
  9178. {
  9179. emit mousePress(event);
  9180. mMousePressPos = event->pos(); // need this to determine in releaseEvent whether it was a click
  9181. // (no position change between press and release)
  9182. // call event of affected layout element:
  9183. mMouseEventElement = layoutElementAt(event->pos());
  9184. if (mMouseEventElement)
  9185. mMouseEventElement->mousePressEvent(event);
  9186. QWidget::mousePressEvent(event);
  9187. }
  9188. /*! \internal
  9189. Event handler for when the cursor is moved. Emits the \ref mouseMove signal.
  9190. If a layout element has mouse capture focus (a mousePressEvent happened on top of the layout
  9191. element before), the mouseMoveEvent is forwarded to that element.
  9192. \see mousePressEvent, mouseReleaseEvent
  9193. */
  9194. void QCustomPlot::mouseMoveEvent(QMouseEvent* event)
  9195. {
  9196. emit mouseMove(event);
  9197. // call event of affected layout element:
  9198. if (mMouseEventElement)
  9199. mMouseEventElement->mouseMoveEvent(event);
  9200. QWidget::mouseMoveEvent(event);
  9201. /*
  9202. //增加游标
  9203. if (m_isShowTracer)
  9204. {
  9205. //当前鼠标位置(像素坐标)
  9206. int x_pos = event->pos().x();
  9207. int y_pos = event->pos().y();
  9208. //像素坐标转成实际的x,y轴的坐标
  9209. float x_val = this->xAxis->pixelToCoord(x_pos);
  9210. float y_val = this->yAxis->pixelToCoord(y_pos);
  9211. if (Q_NULLPTR == m_xTracer)
  9212. m_xTracer = new XxwTracer(this, XxwTracer::DataTracer);//x轴
  9213. m_xTracer->updatePosition(x_val, y_val);
  9214. if (Q_NULLPTR == m_lineTracer)
  9215. m_lineTracer = new XxwTraceLine(this, XxwTraceLine::Both);//直线
  9216. m_lineTracer->updatePosition(x_val, y_val);
  9217. this->replot();//曲线重绘
  9218. }
  9219. */
  9220. }
  9221. /*! \internal
  9222. Event handler for when a mouse button is released. Emits the \ref mouseRelease signal.
  9223. If the mouse was moved less than a certain threshold in any direction since the \ref
  9224. mousePressEvent, it is considered a click which causes the selection mechanism (if activated via
  9225. \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse
  9226. click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.)
  9227. If a layout element has mouse capture focus (a \ref mousePressEvent happened on top of the layout
  9228. element before), the \ref mouseReleaseEvent is forwarded to that element.
  9229. \see mousePressEvent, mouseMoveEvent
  9230. */
  9231. void QCustomPlot::mouseReleaseEvent(QMouseEvent* event)
  9232. {
  9233. emit mouseRelease(event);
  9234. bool doReplot = false;
  9235. if ((mMousePressPos - event->pos()).manhattanLength()
  9236. < 5) // determine whether it was a click operation
  9237. {
  9238. if (event->button() == Qt::LeftButton) {
  9239. // handle selection mechanism:
  9240. QVariant details;
  9241. QCPLayerable* clickedLayerable = layerableAt(event->pos(), true, &details);
  9242. bool selectionStateChanged = false;
  9243. bool additive = mInteractions.testFlag(QCP::iMultiSelect)
  9244. && event->modifiers().testFlag(mMultiSelectModifier);
  9245. // deselect all other layerables if not additive selection:
  9246. if (!additive) {
  9247. foreach (QCPLayer* layer, mLayers) {
  9248. foreach (QCPLayerable* layerable, layer->children()) {
  9249. if (layerable != clickedLayerable
  9250. && mInteractions.testFlag(layerable->selectionCategory())) {
  9251. bool selChanged = false;
  9252. layerable->deselectEvent(&selChanged);
  9253. selectionStateChanged |= selChanged;
  9254. }
  9255. }
  9256. }
  9257. }
  9258. if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory())) {
  9259. // a layerable was actually clicked, call its selectEvent:
  9260. bool selChanged = false;
  9261. clickedLayerable->selectEvent(event, additive, details, &selChanged);
  9262. selectionStateChanged |= selChanged;
  9263. }
  9264. if (selectionStateChanged) {
  9265. doReplot = true;
  9266. emit selectionChangedByUser();
  9267. }
  9268. }
  9269. // emit specialized object click signals:
  9270. QVariant details;
  9271. QCPLayerable* clickedLayerable =
  9272. layerableAt(event->pos(), false,
  9273. &details); // for these signals, selectability is ignored, that's why we
  9274. // call this again with onlySelectable set to false
  9275. if (QCPAbstractPlottable* ap = qobject_cast<QCPAbstractPlottable*>(clickedLayerable))
  9276. emit plottableClick(ap, event);
  9277. else if (QCPAxis* ax = qobject_cast<QCPAxis*>(clickedLayerable))
  9278. emit axisClick(ax, details.value<QCPAxis::SelectablePart>(), event);
  9279. else if (QCPAbstractItem* ai = qobject_cast<QCPAbstractItem*>(clickedLayerable))
  9280. emit itemClick(ai, event);
  9281. else if (QCPLegend* lg = qobject_cast<QCPLegend*>(clickedLayerable))
  9282. emit legendClick(lg, 0, event);
  9283. else if (QCPAbstractLegendItem* li = qobject_cast<QCPAbstractLegendItem*>(clickedLayerable))
  9284. emit legendClick(li->parentLegend(), li, event);
  9285. else if (QCPPlotTitle* pt = qobject_cast<QCPPlotTitle*>(clickedLayerable))
  9286. emit titleClick(event, pt);
  9287. }
  9288. // call event of affected layout element:
  9289. if (mMouseEventElement) {
  9290. mMouseEventElement->mouseReleaseEvent(event);
  9291. mMouseEventElement = 0;
  9292. }
  9293. if (doReplot || noAntialiasingOnDrag())
  9294. replot();
  9295. QWidget::mouseReleaseEvent(event);
  9296. }
  9297. /*! \internal
  9298. Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then
  9299. determines the affected layout element and forwards the event to it.
  9300. */
  9301. void QCustomPlot::wheelEvent(QWheelEvent* event)
  9302. {
  9303. emit mouseWheel(event);
  9304. // call event of affected layout element:
  9305. if (QCPLayoutElement* el = layoutElementAt(event->pos()))
  9306. el->wheelEvent(event);
  9307. QWidget::wheelEvent(event);
  9308. }
  9309. /*! \internal
  9310. This is the main draw function. It draws the entire plot, including background pixmap, with the
  9311. specified \a painter. Note that it does not fill the background with the background brush (as the
  9312. user may specify with \ref setBackground(const QBrush &brush)), this is up to the respective
  9313. functions calling this method (e.g. \ref replot, \ref toPixmap and \ref toPainter).
  9314. */
  9315. void QCustomPlot::draw(QCPPainter* painter)
  9316. {
  9317. // run through layout phases:
  9318. mPlotLayout->update(QCPLayoutElement::upPreparation);
  9319. mPlotLayout->update(QCPLayoutElement::upMargins);
  9320. mPlotLayout->update(QCPLayoutElement::upLayout);
  9321. // draw viewport background pixmap:
  9322. drawBackground(painter);
  9323. // draw all layered objects (grid, axes, plottables, items, legend,...):
  9324. foreach (QCPLayer* layer, mLayers) {
  9325. foreach (QCPLayerable* child, layer->children()) {
  9326. if (child->realVisibility()) {
  9327. painter->save();
  9328. painter->setClipRect(child->clipRect().translated(0, -1));
  9329. child->applyDefaultAntialiasingHint(painter);
  9330. child->draw(painter);
  9331. painter->restore();
  9332. }
  9333. }
  9334. }
  9335. /* Debug code to draw all layout element rects
  9336. foreach (QCPLayoutElement* el, findChildren<QCPLayoutElement*>())
  9337. {
  9338. painter->setBrush(Qt::NoBrush);
  9339. painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine));
  9340. painter->drawRect(el->rect());
  9341. painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine));
  9342. painter->drawRect(el->outerRect());
  9343. }
  9344. */
  9345. }
  9346. /*! \internal
  9347. Draws the viewport background pixmap of the plot.
  9348. If a pixmap was provided via \ref setBackground, this function buffers the scaled version
  9349. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  9350. the viewport with the provided \a painter. The scaled version is buffered in
  9351. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  9352. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  9353. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  9354. set.
  9355. Note that this function does not draw a fill with the background brush (\ref setBackground(const
  9356. QBrush &brush)) beneath the pixmap.
  9357. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  9358. */
  9359. void QCustomPlot::drawBackground(QCPPainter* painter)
  9360. {
  9361. // Note: background color is handled in individual replot/save functions
  9362. // draw background pixmap (on top of fill, if brush specified):
  9363. if (!mBackgroundPixmap.isNull()) {
  9364. if (mBackgroundScaled) {
  9365. // check whether mScaledBackground needs to be updated:
  9366. QSize scaledSize(mBackgroundPixmap.size());
  9367. scaledSize.scale(mViewport.size(), mBackgroundScaledMode);
  9368. if (mScaledBackgroundPixmap.size() != scaledSize)
  9369. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(
  9370. mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  9371. painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap,
  9372. QRect(0, 0, mViewport.width(), mViewport.height())
  9373. & mScaledBackgroundPixmap.rect());
  9374. } else {
  9375. painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap,
  9376. QRect(0, 0, mViewport.width(), mViewport.height()));
  9377. }
  9378. }
  9379. }
  9380. /*! \internal
  9381. This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot
  9382. so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly.
  9383. */
  9384. void QCustomPlot::axisRemoved(QCPAxis* axis)
  9385. {
  9386. if (xAxis == axis)
  9387. xAxis = 0;
  9388. if (xAxis2 == axis)
  9389. xAxis2 = 0;
  9390. if (yAxis == axis)
  9391. yAxis = 0;
  9392. if (yAxis2 == axis)
  9393. yAxis2 = 0;
  9394. // Note: No need to take care of range drag axes and range zoom axes, because they are stored in
  9395. // smart pointers
  9396. }
  9397. /*! \internal
  9398. This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so
  9399. it may clear its QCustomPlot::legend member accordingly.
  9400. */
  9401. void QCustomPlot::legendRemoved(QCPLegend* legend)
  9402. {
  9403. if (this->legend == legend)
  9404. this->legend = 0;
  9405. }
  9406. /*! \internal
  9407. Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called
  9408. after every operation that changes the layer indices, like layer removal, layer creation, layer
  9409. moving.
  9410. */
  9411. void QCustomPlot::updateLayerIndices() const
  9412. {
  9413. for (int i = 0; i < mLayers.size(); ++i)
  9414. mLayers.at(i)->mIndex = i;
  9415. }
  9416. /*! \internal
  9417. Returns the layerable at pixel position \a pos. If \a onlySelectable is set to true, only those
  9418. layerables that are selectable will be considered. (Layerable subclasses communicate their
  9419. selectability via the QCPLayerable::selectTest method, by returning -1.)
  9420. \a selectionDetails is an output parameter that contains selection specifics of the affected
  9421. layerable. This is useful if the respective layerable shall be given a subsequent
  9422. QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
  9423. information about which part of the layerable was hit, in multi-part layerables (e.g.
  9424. QCPAxis::SelectablePart).
  9425. */
  9426. QCPLayerable* QCustomPlot::layerableAt(const QPointF& pos, bool onlySelectable,
  9427. QVariant* selectionDetails) const
  9428. {
  9429. for (int layerIndex = mLayers.size() - 1; layerIndex >= 0; --layerIndex) {
  9430. const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
  9431. double minimumDistance = selectionTolerance() * 1.1;
  9432. QCPLayerable* minimumDistanceLayerable = 0;
  9433. for (int i = layerables.size() - 1; i >= 0; --i) {
  9434. if (!layerables.at(i)->realVisibility())
  9435. continue;
  9436. QVariant details;
  9437. double dist = layerables.at(i)->selectTest(pos, onlySelectable, &details);
  9438. if (dist >= 0 && dist < minimumDistance) {
  9439. minimumDistance = dist;
  9440. minimumDistanceLayerable = layerables.at(i);
  9441. if (selectionDetails)
  9442. *selectionDetails = details;
  9443. }
  9444. }
  9445. if (minimumDistance < selectionTolerance())
  9446. return minimumDistanceLayerable;
  9447. }
  9448. return 0;
  9449. }
  9450. /*!
  9451. Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is
  9452. sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead
  9453. to a full resolution file with width 200.) If the \a format supports compression, \a quality may
  9454. be between 0 and 100 to control it.
  9455. Returns true on success. If this function fails, most likely the given \a format isn't supported
  9456. by the system, see Qt docs about QImageWriter::supportedImageFormats().
  9457. \see saveBmp, saveJpg, savePng, savePdf
  9458. */
  9459. bool QCustomPlot::saveRastered(const QString& fileName, int width, int height, double scale,
  9460. const char* format, int quality)
  9461. {
  9462. QPixmap buffer = toPixmap(width, height, scale);
  9463. if (!buffer.isNull())
  9464. return buffer.save(fileName, format, quality);
  9465. else
  9466. return false;
  9467. }
  9468. /*!
  9469. Renders the plot to a pixmap and returns it.
  9470. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and
  9471. scale 2.0 lead to a full resolution pixmap with width 200.)
  9472. \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf
  9473. */
  9474. QPixmap QCustomPlot::toPixmap(int width, int height, double scale)
  9475. {
  9476. // this method is somewhat similar to toPainter. Change something here, and a change in
  9477. // toPainter might be necessary, too.
  9478. int newWidth, newHeight;
  9479. if (width == 0 || height == 0) {
  9480. newWidth = this->width();
  9481. newHeight = this->height();
  9482. } else {
  9483. newWidth = width;
  9484. newHeight = height;
  9485. }
  9486. int scaledWidth = qRound(scale * newWidth);
  9487. int scaledHeight = qRound(scale * newHeight);
  9488. QPixmap result(scaledWidth, scaledHeight);
  9489. result.fill(mBackgroundBrush.style() == Qt::SolidPattern
  9490. ? mBackgroundBrush.color()
  9491. : Qt::transparent); // if using non-solid pattern, make transparent now and draw
  9492. // brush pattern later
  9493. QCPPainter painter;
  9494. painter.begin(&result);
  9495. if (painter.isActive()) {
  9496. QRect oldViewport = viewport();
  9497. setViewport(QRect(0, 0, newWidth, newHeight));
  9498. painter.setMode(QCPPainter::pmNoCaching);
  9499. if (!qFuzzyCompare(scale, 1.0)) {
  9500. if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because
  9501. // else lines might disappear for very small scales
  9502. painter.setMode(QCPPainter::pmNonCosmetic);
  9503. painter.scale(scale, scale);
  9504. }
  9505. if (mBackgroundBrush.style() != Qt::SolidPattern
  9506. && mBackgroundBrush.style()
  9507. != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill
  9508. painter.fillRect(mViewport, mBackgroundBrush);
  9509. draw(&painter);
  9510. setViewport(oldViewport);
  9511. painter.end();
  9512. } else // might happen if pixmap has width or height zero
  9513. {
  9514. qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap";
  9515. return QPixmap();
  9516. }
  9517. return result;
  9518. }
  9519. /*!
  9520. Renders the plot using the passed \a painter.
  9521. The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the
  9522. resulting plot will appear scaled accordingly.
  9523. \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary
  9524. QPicture and open a QCPPainter on it. Then call \ref toPainter with this QCPPainter. After ending
  9525. the paint operation on the picture, draw it with the QPainter. This will reproduce the painter
  9526. actions the QCPPainter took, with a QPainter.
  9527. \see toPixmap
  9528. */
  9529. void QCustomPlot::toPainter(QCPPainter* painter, int width, int height)
  9530. {
  9531. // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap
  9532. // might be necessary, too.
  9533. int newWidth, newHeight;
  9534. if (width == 0 || height == 0) {
  9535. newWidth = this->width();
  9536. newHeight = this->height();
  9537. } else {
  9538. newWidth = width;
  9539. newHeight = height;
  9540. }
  9541. if (painter->isActive()) {
  9542. QRect oldViewport = viewport();
  9543. setViewport(QRect(0, 0, newWidth, newHeight));
  9544. painter->setMode(QCPPainter::pmNoCaching);
  9545. if (mBackgroundBrush.style()
  9546. != Qt::NoBrush) // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern
  9547. // brush style, so we also draw solid fills with fillRect here
  9548. painter->fillRect(mViewport, mBackgroundBrush);
  9549. draw(painter);
  9550. setViewport(oldViewport);
  9551. } else
  9552. qDebug() << Q_FUNC_INFO << "Passed painter is not active";
  9553. }
  9554. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9555. //////////////////// QCPColorGradient
  9556. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9557. /*! \class QCPColorGradient
  9558. \brief Defines a color gradient for use with e.g. \ref QCPColorMap
  9559. This class describes a color gradient which can be used to encode data with color. For example,
  9560. QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which
  9561. take an instance of this class. Colors are set with \ref setColorStopAt(double position, const
  9562. QColor &color) with a \a position from 0 to 1. In between these defined color positions, the color
  9563. will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation.
  9564. Alternatively, load one of the preset color gradients shown in the image below, with \ref
  9565. loadPreset, or by directly specifying the preset in the constructor.
  9566. \image html QCPColorGradient.png
  9567. The fact that the \ref QCPColorGradient(GradientPreset preset) constructor allows directly
  9568. converting a \ref GradientPreset to a QCPColorGradient, you can also directly pass \ref
  9569. GradientPreset to all the \a setGradient methods, e.g.:
  9570. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient
  9571. The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the
  9572. color gradient shall be applied periodically (wrapping around) to data values that lie outside
  9573. the data range specified on the plottable instance can be controlled with \ref setPeriodic.
  9574. */
  9575. /*!
  9576. Constructs a new QCPColorGradient initialized with the colors and color interpolation according
  9577. to \a preset.
  9578. The color level count is initialized to 350.
  9579. */
  9580. QCPColorGradient::QCPColorGradient(GradientPreset preset)
  9581. : mLevelCount(350), mColorInterpolation(ciRGB), mPeriodic(false), mColorBufferInvalidated(true)
  9582. {
  9583. mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
  9584. loadPreset(preset);
  9585. }
  9586. /* undocumented operator */
  9587. bool QCPColorGradient::operator==(const QCPColorGradient& other) const
  9588. {
  9589. return ((other.mLevelCount == this->mLevelCount)
  9590. && (other.mColorInterpolation == this->mColorInterpolation)
  9591. && (other.mPeriodic == this->mPeriodic) && (other.mColorStops == this->mColorStops));
  9592. }
  9593. /*!
  9594. Sets the number of discretization levels of the color gradient to \a n. The default is 350 which
  9595. is typically enough to create a smooth appearance.
  9596. \image html QCPColorGradient-levelcount.png
  9597. */
  9598. void QCPColorGradient::setLevelCount(int n)
  9599. {
  9600. if (n < 2) {
  9601. qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n;
  9602. n = 2;
  9603. }
  9604. if (n != mLevelCount) {
  9605. mLevelCount = n;
  9606. mColorBufferInvalidated = true;
  9607. }
  9608. }
  9609. /*!
  9610. Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the
  9611. colors are the values of the passed QMap \a colorStops. In between these color stops, the color
  9612. is interpolated according to \ref setColorInterpolation.
  9613. A more convenient way to create a custom gradient may be to clear all color stops with \ref
  9614. clearColorStops and then adding them one by one with \ref setColorStopAt.
  9615. \see clearColorStops
  9616. */
  9617. void QCPColorGradient::setColorStops(const QMap<double, QColor>& colorStops)
  9618. {
  9619. mColorStops = colorStops;
  9620. mColorBufferInvalidated = true;
  9621. }
  9622. /*!
  9623. Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between
  9624. these color stops, the color is interpolated according to \ref setColorInterpolation.
  9625. \see setColorStops, clearColorStops
  9626. */
  9627. void QCPColorGradient::setColorStopAt(double position, const QColor& color)
  9628. {
  9629. mColorStops.insert(position, color);
  9630. mColorBufferInvalidated = true;
  9631. }
  9632. /*!
  9633. Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be
  9634. interpolated linearly in RGB or in HSV color space.
  9635. For example, a sweep in RGB space from red to green will have a muddy brown intermediate color,
  9636. whereas in HSV space the intermediate color is yellow.
  9637. */
  9638. void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation)
  9639. {
  9640. if (interpolation != mColorInterpolation) {
  9641. mColorInterpolation = interpolation;
  9642. mColorBufferInvalidated = true;
  9643. }
  9644. }
  9645. /*!
  9646. Sets whether data points that are outside the configured data range (e.g. \ref
  9647. QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether
  9648. they all have the same color, corresponding to the respective gradient boundary color.
  9649. \image html QCPColorGradient-periodic.png
  9650. As shown in the image above, gradients that have the same start and end color are especially
  9651. suitable for a periodic gradient mapping, since they produce smooth color transitions throughout
  9652. the color map. A preset that has this property is \ref gpHues.
  9653. In practice, using periodic color gradients makes sense when the data corresponds to a periodic
  9654. dimension, such as an angle or a phase. If this is not the case, the color encoding might become
  9655. ambiguous, because multiple different data values are shown as the same color.
  9656. */
  9657. void QCPColorGradient::setPeriodic(bool enabled)
  9658. {
  9659. mPeriodic = enabled;
  9660. }
  9661. /*!
  9662. This method is used to quickly convert a \a data array to colors. The colors will be output in
  9663. the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this
  9664. function. The data range that shall be used for mapping the data value to the gradient is passed
  9665. in \a range. \a logarithmic indicates whether the data values shall be mapped to colors
  9666. logarithmically.
  9667. if \a data actually contains 2D-data linearized via <tt>[row*columnCount + column]</tt>, you can
  9668. set \a dataIndexFactor to <tt>columnCount</tt> to convert a column instead of a row of the data
  9669. array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data
  9670. is addressed <tt>data[i*dataIndexFactor]</tt>.
  9671. */
  9672. void QCPColorGradient::colorize(const double* data, const QCPRange& range, QRgb* scanLine, int n,
  9673. int dataIndexFactor, bool logarithmic)
  9674. {
  9675. // If you change something here, make sure to also adapt ::color()
  9676. if (!data) {
  9677. qDebug() << Q_FUNC_INFO << "null pointer given as data";
  9678. return;
  9679. }
  9680. if (!scanLine) {
  9681. qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
  9682. return;
  9683. }
  9684. if (mColorBufferInvalidated)
  9685. updateColorBuffer();
  9686. if (!logarithmic) {
  9687. const double posToIndexFactor = (mLevelCount - 1) / range.size();
  9688. if (mPeriodic) {
  9689. for (int i = 0; i < n; ++i) {
  9690. int index = (int)((data[dataIndexFactor * i] - range.lower) * posToIndexFactor)
  9691. % mLevelCount;
  9692. if (index < 0)
  9693. index += mLevelCount;
  9694. scanLine[i] = mColorBuffer.at(index);
  9695. }
  9696. } else {
  9697. for (int i = 0; i < n; ++i) {
  9698. int index = (data[dataIndexFactor * i] - range.lower) * posToIndexFactor;
  9699. if (index < 0)
  9700. index = 0;
  9701. else if (index >= mLevelCount)
  9702. index = mLevelCount - 1;
  9703. scanLine[i] = mColorBuffer.at(index);
  9704. }
  9705. }
  9706. } else // logarithmic == true
  9707. {
  9708. if (mPeriodic) {
  9709. for (int i = 0; i < n; ++i) {
  9710. int index = (int)(qLn(data[dataIndexFactor * i] / range.lower)
  9711. / qLn(range.upper / range.lower) * (mLevelCount - 1))
  9712. % mLevelCount;
  9713. if (index < 0)
  9714. index += mLevelCount;
  9715. scanLine[i] = mColorBuffer.at(index);
  9716. }
  9717. } else {
  9718. for (int i = 0; i < n; ++i) {
  9719. int index = qLn(data[dataIndexFactor * i] / range.lower)
  9720. / qLn(range.upper / range.lower) * (mLevelCount - 1);
  9721. if (index < 0)
  9722. index = 0;
  9723. else if (index >= mLevelCount)
  9724. index = mLevelCount - 1;
  9725. scanLine[i] = mColorBuffer.at(index);
  9726. }
  9727. }
  9728. }
  9729. }
  9730. /*! \internal
  9731. This method is used to colorize a single data value given in \a position, to colors. The data
  9732. range that shall be used for mapping the data value to the gradient is passed in \a range. \a
  9733. logarithmic indicates whether the data value shall be mapped to a color logarithmically.
  9734. If an entire array of data values shall be converted, rather use \ref colorize, for better
  9735. performance.
  9736. */
  9737. QRgb QCPColorGradient::color(double position, const QCPRange& range, bool logarithmic)
  9738. {
  9739. // If you change something here, make sure to also adapt ::colorize()
  9740. if (mColorBufferInvalidated)
  9741. updateColorBuffer();
  9742. int index = 0;
  9743. if (!logarithmic)
  9744. index = (position - range.lower) * (mLevelCount - 1) / range.size();
  9745. else
  9746. index = qLn(position / range.lower) / qLn(range.upper / range.lower) * (mLevelCount - 1);
  9747. if (mPeriodic) {
  9748. index = index % mLevelCount;
  9749. if (index < 0)
  9750. index += mLevelCount;
  9751. } else {
  9752. if (index < 0)
  9753. index = 0;
  9754. else if (index >= mLevelCount)
  9755. index = mLevelCount - 1;
  9756. }
  9757. return mColorBuffer.at(index);
  9758. }
  9759. /*!
  9760. Clears the current color stops and loads the specified \a preset. A preset consists of predefined
  9761. color stops and the corresponding color interpolation method.
  9762. The available presets are:
  9763. \image html QCPColorGradient.png
  9764. */
  9765. void QCPColorGradient::loadPreset(GradientPreset preset)
  9766. {
  9767. clearColorStops();
  9768. switch (preset) {
  9769. case gpGrayscale:
  9770. setColorInterpolation(ciRGB);
  9771. setColorStopAt(0, Qt::black);
  9772. setColorStopAt(1, Qt::white);
  9773. break;
  9774. case gpHot:
  9775. setColorInterpolation(ciRGB);
  9776. setColorStopAt(0, QColor(50, 0, 0));
  9777. setColorStopAt(0.2, QColor(180, 10, 0));
  9778. setColorStopAt(0.4, QColor(245, 50, 0));
  9779. setColorStopAt(0.6, QColor(255, 150, 10));
  9780. setColorStopAt(0.8, QColor(255, 255, 50));
  9781. setColorStopAt(1, QColor(255, 255, 255));
  9782. break;
  9783. case gpCold:
  9784. setColorInterpolation(ciRGB);
  9785. setColorStopAt(0, QColor(0, 0, 50));
  9786. setColorStopAt(0.2, QColor(0, 10, 180));
  9787. setColorStopAt(0.4, QColor(0, 50, 245));
  9788. setColorStopAt(0.6, QColor(10, 150, 255));
  9789. setColorStopAt(0.8, QColor(50, 255, 255));
  9790. setColorStopAt(1, QColor(255, 255, 255));
  9791. break;
  9792. case gpNight:
  9793. setColorInterpolation(ciHSV);
  9794. setColorStopAt(0, QColor(10, 20, 30));
  9795. setColorStopAt(1, QColor(250, 255, 250));
  9796. break;
  9797. case gpCandy:
  9798. setColorInterpolation(ciHSV);
  9799. setColorStopAt(0, QColor(0, 0, 255));
  9800. setColorStopAt(1, QColor(255, 250, 250));
  9801. break;
  9802. case gpGeography:
  9803. setColorInterpolation(ciRGB);
  9804. setColorStopAt(0, QColor(70, 170, 210));
  9805. setColorStopAt(0.20, QColor(90, 160, 180));
  9806. setColorStopAt(0.25, QColor(45, 130, 175));
  9807. setColorStopAt(0.30, QColor(100, 140, 125));
  9808. setColorStopAt(0.5, QColor(100, 140, 100));
  9809. setColorStopAt(0.6, QColor(130, 145, 120));
  9810. setColorStopAt(0.7, QColor(140, 130, 120));
  9811. setColorStopAt(0.9, QColor(180, 190, 190));
  9812. setColorStopAt(1, QColor(210, 210, 230));
  9813. break;
  9814. case gpIon:
  9815. setColorInterpolation(ciHSV);
  9816. setColorStopAt(0, QColor(50, 10, 10));
  9817. setColorStopAt(0.45, QColor(0, 0, 255));
  9818. setColorStopAt(0.8, QColor(0, 255, 255));
  9819. setColorStopAt(1, QColor(0, 255, 0));
  9820. break;
  9821. case gpThermal:
  9822. setColorInterpolation(ciRGB);
  9823. setColorStopAt(0, QColor(0, 0, 50));
  9824. setColorStopAt(0.15, QColor(20, 0, 120));
  9825. setColorStopAt(0.33, QColor(200, 30, 140));
  9826. setColorStopAt(0.6, QColor(255, 100, 0));
  9827. setColorStopAt(0.85, QColor(255, 255, 40));
  9828. setColorStopAt(1, QColor(255, 255, 255));
  9829. break;
  9830. case gpPolar:
  9831. setColorInterpolation(ciRGB);
  9832. setColorStopAt(0, QColor(50, 255, 255));
  9833. setColorStopAt(0.18, QColor(10, 70, 255));
  9834. setColorStopAt(0.28, QColor(10, 10, 190));
  9835. setColorStopAt(0.5, QColor(0, 0, 0));
  9836. setColorStopAt(0.72, QColor(190, 10, 10));
  9837. setColorStopAt(0.82, QColor(255, 70, 10));
  9838. setColorStopAt(1, QColor(255, 255, 50));
  9839. break;
  9840. case gpSpectrum:
  9841. setColorInterpolation(ciHSV);
  9842. setColorStopAt(0, QColor(50, 0, 50));
  9843. setColorStopAt(0.15, QColor(0, 0, 255));
  9844. setColorStopAt(0.35, QColor(0, 255, 255));
  9845. setColorStopAt(0.6, QColor(255, 255, 0));
  9846. setColorStopAt(0.75, QColor(255, 30, 0));
  9847. setColorStopAt(1, QColor(50, 0, 0));
  9848. break;
  9849. case gpJet:
  9850. setColorInterpolation(ciRGB);
  9851. setColorStopAt(0, QColor(0, 0, 100));
  9852. setColorStopAt(0.15, QColor(0, 50, 255));
  9853. setColorStopAt(0.35, QColor(0, 255, 255));
  9854. setColorStopAt(0.65, QColor(255, 255, 0));
  9855. setColorStopAt(0.85, QColor(255, 30, 0));
  9856. setColorStopAt(1, QColor(100, 0, 0));
  9857. break;
  9858. case gpHues:
  9859. setColorInterpolation(ciHSV);
  9860. setColorStopAt(0, QColor(255, 0, 0));
  9861. setColorStopAt(1.0 / 3.0, QColor(0, 0, 255));
  9862. setColorStopAt(2.0 / 3.0, QColor(0, 255, 0));
  9863. setColorStopAt(1, QColor(255, 0, 0));
  9864. break;
  9865. }
  9866. }
  9867. /*!
  9868. Clears all color stops.
  9869. \see setColorStops, setColorStopAt
  9870. */
  9871. void QCPColorGradient::clearColorStops()
  9872. {
  9873. mColorStops.clear();
  9874. mColorBufferInvalidated = true;
  9875. }
  9876. /*!
  9877. Returns an inverted gradient. The inverted gradient has all properties as this \ref
  9878. QCPColorGradient, but the order of the color stops is inverted.
  9879. \see setColorStops, setColorStopAt
  9880. */
  9881. QCPColorGradient QCPColorGradient::inverted() const
  9882. {
  9883. QCPColorGradient result(*this);
  9884. result.clearColorStops();
  9885. for (QMap<double, QColor>::const_iterator it = mColorStops.constBegin();
  9886. it != mColorStops.constEnd(); ++it)
  9887. result.setColorStopAt(1.0 - it.key(), it.value());
  9888. return result;
  9889. }
  9890. /*! \internal
  9891. Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly
  9892. convert positions to colors. This is where the interpolation between color stops is calculated.
  9893. */
  9894. void QCPColorGradient::updateColorBuffer()
  9895. {
  9896. if (mColorBuffer.size() != mLevelCount)
  9897. mColorBuffer.resize(mLevelCount);
  9898. if (mColorStops.size() > 1) {
  9899. double indexToPosFactor = 1.0 / (double)(mLevelCount - 1);
  9900. for (int i = 0; i < mLevelCount; ++i) {
  9901. double position = i * indexToPosFactor;
  9902. QMap<double, QColor>::const_iterator it = mColorStops.lowerBound(position);
  9903. if (it
  9904. == mColorStops
  9905. .constEnd()) // position is on or after last stop, use color of last stop
  9906. {
  9907. mColorBuffer[i] = (it - 1).value().rgb();
  9908. } else if (it == mColorStops.constBegin()) // position is on or before first stop, use
  9909. // color of first stop
  9910. {
  9911. mColorBuffer[i] = it.value().rgb();
  9912. } else // position is in between stops (or on an intermediate stop), interpolate color
  9913. {
  9914. QMap<double, QColor>::const_iterator high = it;
  9915. QMap<double, QColor>::const_iterator low = it - 1;
  9916. double t =
  9917. (position - low.key()) / (high.key() - low.key()); // interpolation factor 0..1
  9918. switch (mColorInterpolation) {
  9919. case ciRGB: {
  9920. mColorBuffer[i] = qRgb((1 - t) * low.value().red() + t * high.value().red(),
  9921. (1 - t) * low.value().green() + t * high.value().green(),
  9922. (1 - t) * low.value().blue() + t * high.value().blue());
  9923. break;
  9924. }
  9925. case ciHSV: {
  9926. QColor lowHsv = low.value().toHsv();
  9927. QColor highHsv = high.value().toHsv();
  9928. double hue = 0;
  9929. double hueDiff = highHsv.hueF() - lowHsv.hueF();
  9930. if (hueDiff > 0.5)
  9931. hue = lowHsv.hueF() - t * (1.0 - hueDiff);
  9932. else if (hueDiff < -0.5)
  9933. hue = lowHsv.hueF() + t * (1.0 + hueDiff);
  9934. else
  9935. hue = lowHsv.hueF() + t * hueDiff;
  9936. if (hue < 0)
  9937. hue += 1.0;
  9938. else if (hue >= 1.0)
  9939. hue -= 1.0;
  9940. mColorBuffer[i] =
  9941. QColor::fromHsvF(hue,
  9942. (1 - t) * lowHsv.saturationF() + t * highHsv.saturationF(),
  9943. (1 - t) * lowHsv.valueF() + t * highHsv.valueF())
  9944. .rgb();
  9945. break;
  9946. }
  9947. }
  9948. }
  9949. }
  9950. } else if (mColorStops.size() == 1) {
  9951. mColorBuffer.fill(mColorStops.constBegin().value().rgb());
  9952. } else // mColorStops is empty, fill color buffer with black
  9953. {
  9954. mColorBuffer.fill(qRgb(0, 0, 0));
  9955. }
  9956. mColorBufferInvalidated = false;
  9957. }
  9958. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9959. //////////////////// QCPAxisRect
  9960. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9961. /*! \class QCPAxisRect
  9962. \brief Holds multiple axes and arranges them in a rectangular shape.
  9963. This class represents an axis rect, a rectangular area that is bounded on all sides with an
  9964. arbitrary number of axes.
  9965. Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the
  9966. layout system allows to have multiple axis rects, e.g. arranged in a grid layout
  9967. (QCustomPlot::plotLayout).
  9968. By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be
  9969. accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index.
  9970. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be
  9971. invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref
  9972. addAxes. To remove an axis, use \ref removeAxis.
  9973. The axis rect layerable itself only draws a background pixmap or color, if specified (\ref
  9974. setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an
  9975. explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be
  9976. placed on other layers, independently of the axis rect.
  9977. Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref
  9978. insetLayout and can be used to have other layout elements (or even other layouts with multiple
  9979. elements) hovering inside the axis rect.
  9980. If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The
  9981. behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel
  9982. is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable
  9983. via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are
  9984. only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref
  9985. QCP::iRangeZoom.
  9986. \image html AxisRectSpacingOverview.png
  9987. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed
  9988. line on the far left indicates the viewport/widget border.</center>
  9989. */
  9990. /* start documentation of inline functions */
  9991. /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const
  9992. Returns the inset layout of this axis rect. It can be used to place other layout elements (or
  9993. even layouts with multiple other elements) inside/on top of an axis rect.
  9994. \see QCPLayoutInset
  9995. */
  9996. /*! \fn int QCPAxisRect::left() const
  9997. Returns the pixel position of the left border of this axis rect. Margins are not taken into
  9998. account here, so the returned value is with respect to the inner \ref rect.
  9999. */
  10000. /*! \fn int QCPAxisRect::right() const
  10001. Returns the pixel position of the right border of this axis rect. Margins are not taken into
  10002. account here, so the returned value is with respect to the inner \ref rect.
  10003. */
  10004. /*! \fn int QCPAxisRect::top() const
  10005. Returns the pixel position of the top border of this axis rect. Margins are not taken into
  10006. account here, so the returned value is with respect to the inner \ref rect.
  10007. */
  10008. /*! \fn int QCPAxisRect::bottom() const
  10009. Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
  10010. account here, so the returned value is with respect to the inner \ref rect.
  10011. */
  10012. /*! \fn int QCPAxisRect::width() const
  10013. Returns the pixel width of this axis rect. Margins are not taken into account here, so the
  10014. returned value is with respect to the inner \ref rect.
  10015. */
  10016. /*! \fn int QCPAxisRect::height() const
  10017. Returns the pixel height of this axis rect. Margins are not taken into account here, so the
  10018. returned value is with respect to the inner \ref rect.
  10019. */
  10020. /*! \fn QSize QCPAxisRect::size() const
  10021. Returns the pixel size of this axis rect. Margins are not taken into account here, so the
  10022. returned value is with respect to the inner \ref rect.
  10023. */
  10024. /*! \fn QPoint QCPAxisRect::topLeft() const
  10025. Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
  10026. so the returned value is with respect to the inner \ref rect.
  10027. */
  10028. /*! \fn QPoint QCPAxisRect::topRight() const
  10029. Returns the top right corner of this axis rect in pixels. Margins are not taken into account
  10030. here, so the returned value is with respect to the inner \ref rect.
  10031. */
  10032. /*! \fn QPoint QCPAxisRect::bottomLeft() const
  10033. Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
  10034. here, so the returned value is with respect to the inner \ref rect.
  10035. */
  10036. /*! \fn QPoint QCPAxisRect::bottomRight() const
  10037. Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
  10038. here, so the returned value is with respect to the inner \ref rect.
  10039. */
  10040. /*! \fn QPoint QCPAxisRect::center() const
  10041. Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
  10042. returned value is with respect to the inner \ref rect.
  10043. */
  10044. /* end documentation of inline functions */
  10045. /*!
  10046. Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four
  10047. sides, the top and right axes are set invisible initially.
  10048. */
  10049. QCPAxisRect::QCPAxisRect(QCustomPlot* parentPlot, bool setupDefaultAxes)
  10050. : QCPLayoutElement(parentPlot)
  10051. , mBackgroundBrush(Qt::NoBrush)
  10052. , mBackgroundScaled(true)
  10053. , mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding)
  10054. , mInsetLayout(new QCPLayoutInset)
  10055. , mRangeDrag(Qt::Horizontal | Qt::Vertical)
  10056. , mRangeZoom(Qt::Horizontal | Qt::Vertical)
  10057. , mRangeZoomFactorHorz(0.85)
  10058. , mRangeZoomFactorVert(0.85)
  10059. , mDragging(false)
  10060. {
  10061. mInsetLayout->initializeParentPlot(mParentPlot);
  10062. mInsetLayout->setParentLayerable(this);
  10063. mInsetLayout->setParent(this);
  10064. setMinimumSize(50, 50);
  10065. setMinimumMargins(QMargins(15, 15, 15, 15));
  10066. mAxes.insert(QCPAxis::atLeft, QList<QCPAxis*>());
  10067. mAxes.insert(QCPAxis::atRight, QList<QCPAxis*>());
  10068. mAxes.insert(QCPAxis::atTop, QList<QCPAxis*>());
  10069. mAxes.insert(QCPAxis::atBottom, QList<QCPAxis*>());
  10070. if (setupDefaultAxes) {
  10071. QCPAxis* xAxis = addAxis(QCPAxis::atBottom);
  10072. QCPAxis* yAxis = addAxis(QCPAxis::atLeft);
  10073. QCPAxis* xAxis2 = addAxis(QCPAxis::atTop);
  10074. QCPAxis* yAxis2 = addAxis(QCPAxis::atRight);
  10075. setRangeDragAxes(xAxis, yAxis);
  10076. setRangeZoomAxes(xAxis, yAxis);
  10077. xAxis2->setVisible(false);
  10078. yAxis2->setVisible(false);
  10079. xAxis->grid()->setVisible(true);
  10080. yAxis->grid()->setVisible(true);
  10081. xAxis2->grid()->setVisible(false);
  10082. yAxis2->grid()->setVisible(false);
  10083. xAxis2->grid()->setZeroLinePen(Qt::NoPen);
  10084. yAxis2->grid()->setZeroLinePen(Qt::NoPen);
  10085. xAxis2->grid()->setVisible(false);
  10086. yAxis2->grid()->setVisible(false);
  10087. }
  10088. }
  10089. QCPAxisRect::~QCPAxisRect()
  10090. {
  10091. delete mInsetLayout;
  10092. mInsetLayout = 0;
  10093. QList<QCPAxis*> axesList = axes();
  10094. for (int i = 0; i < axesList.size(); ++i)
  10095. removeAxis(axesList.at(i));
  10096. }
  10097. /*!
  10098. Returns the number of axes on the axis rect side specified with \a type.
  10099. \see axis
  10100. */
  10101. int QCPAxisRect::axisCount(QCPAxis::AxisType type) const
  10102. {
  10103. return mAxes.value(type).size();
  10104. }
  10105. /*!
  10106. Returns the axis with the given \a index on the axis rect side specified with \a type.
  10107. \see axisCount, axes
  10108. */
  10109. QCPAxis* QCPAxisRect::axis(QCPAxis::AxisType type, int index) const
  10110. {
  10111. QList<QCPAxis*> ax(mAxes.value(type));
  10112. if (index >= 0 && index < ax.size()) {
  10113. return ax.at(index);
  10114. } else {
  10115. qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
  10116. return 0;
  10117. }
  10118. }
  10119. /*!
  10120. Returns all axes on the axis rect sides specified with \a types.
  10121. \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
  10122. multiple sides.
  10123. \see axis
  10124. */
  10125. QList<QCPAxis*> QCPAxisRect::axes(QCPAxis::AxisTypes types) const
  10126. {
  10127. QList<QCPAxis*> result;
  10128. if (types.testFlag(QCPAxis::atLeft))
  10129. result << mAxes.value(QCPAxis::atLeft);
  10130. if (types.testFlag(QCPAxis::atRight))
  10131. result << mAxes.value(QCPAxis::atRight);
  10132. if (types.testFlag(QCPAxis::atTop))
  10133. result << mAxes.value(QCPAxis::atTop);
  10134. if (types.testFlag(QCPAxis::atBottom))
  10135. result << mAxes.value(QCPAxis::atBottom);
  10136. return result;
  10137. }
  10138. /*! \overload
  10139. Returns all axes of this axis rect.
  10140. */
  10141. QList<QCPAxis*> QCPAxisRect::axes() const
  10142. {
  10143. QList<QCPAxis*> result;
  10144. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*>> it(mAxes);
  10145. while (it.hasNext()) {
  10146. it.next();
  10147. result << it.value();
  10148. }
  10149. return result;
  10150. }
  10151. /*!
  10152. Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
  10153. new QCPAxis instance is created internally.
  10154. You may inject QCPAxis instances (or sublasses of QCPAxis) by setting \a axis to an axis that was
  10155. previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
  10156. of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
  10157. with this axis rect as parent and with the same axis type as specified in \a type. If this is not
  10158. the case, a debug output is generated, the axis is not added, and the method returns 0.
  10159. This method can not be used to move \a axis between axis rects. The same \a axis instance must
  10160. not be added multiple times to the same or different axis rects.
  10161. If an axis rect side already contains one or more axes, the lower and upper endings of the new
  10162. axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
  10163. QCPLineEnding::esHalfBar.
  10164. \see addAxes, setupFullAxesBox
  10165. */
  10166. QCPAxis* QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis* axis)
  10167. {
  10168. QCPAxis* newAxis = axis;
  10169. if (!newAxis) {
  10170. newAxis = new QCPAxis(this, type);
  10171. } else // user provided existing axis instance, do some sanity checks
  10172. {
  10173. if (newAxis->axisType() != type) {
  10174. qDebug() << Q_FUNC_INFO
  10175. << "passed axis has different axis type than specified in type parameter";
  10176. return 0;
  10177. }
  10178. if (newAxis->axisRect() != this) {
  10179. qDebug() << Q_FUNC_INFO
  10180. << "passed axis doesn't have this axis rect as parent axis rect";
  10181. return 0;
  10182. }
  10183. if (axes().contains(newAxis)) {
  10184. qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect";
  10185. return 0;
  10186. }
  10187. }
  10188. if (mAxes[type].size()
  10189. > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset
  10190. {
  10191. bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom);
  10192. newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert));
  10193. newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert));
  10194. }
  10195. mAxes[type].append(newAxis);
  10196. return newAxis;
  10197. }
  10198. /*!
  10199. Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an
  10200. <tt>or</tt>-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once.
  10201. Returns a list of the added axes.
  10202. \see addAxis, setupFullAxesBox
  10203. */
  10204. QList<QCPAxis*> QCPAxisRect::addAxes(QCPAxis::AxisTypes types)
  10205. {
  10206. QList<QCPAxis*> result;
  10207. if (types.testFlag(QCPAxis::atLeft))
  10208. result << addAxis(QCPAxis::atLeft);
  10209. if (types.testFlag(QCPAxis::atRight))
  10210. result << addAxis(QCPAxis::atRight);
  10211. if (types.testFlag(QCPAxis::atTop))
  10212. result << addAxis(QCPAxis::atTop);
  10213. if (types.testFlag(QCPAxis::atBottom))
  10214. result << addAxis(QCPAxis::atBottom);
  10215. return result;
  10216. }
  10217. /*!
  10218. Removes the specified \a axis from the axis rect and deletes it.
  10219. Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
  10220. \see addAxis
  10221. */
  10222. bool QCPAxisRect::removeAxis(QCPAxis* axis)
  10223. {
  10224. // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go
  10225. // through all axis containers:
  10226. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*>> it(mAxes);
  10227. while (it.hasNext()) {
  10228. it.next();
  10229. if (it.value().contains(axis)) {
  10230. mAxes[it.key()].removeOne(axis);
  10231. if (qobject_cast<QCustomPlot*>(
  10232. parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot
  10233. // is already destructed (happens when the axis rect is not in
  10234. // any layout and thus QObject-child of QCustomPlot)
  10235. parentPlot()->axisRemoved(axis);
  10236. delete axis;
  10237. return true;
  10238. }
  10239. }
  10240. qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast<quintptr>(axis);
  10241. return false;
  10242. }
  10243. /*!
  10244. Convenience function to create an axis on each side that doesn't have any axes yet and set their
  10245. visibility to true. Further, the top/right axes are assigned the following properties of the
  10246. bottom/left axes:
  10247. \li range (\ref QCPAxis::setRange)
  10248. \li range reversed (\ref QCPAxis::setRangeReversed)
  10249. \li scale type (\ref QCPAxis::setScaleType)
  10250. \li scale log base (\ref QCPAxis::setScaleLogBase)
  10251. \li ticks (\ref QCPAxis::setTicks)
  10252. \li auto (major) tick count (\ref QCPAxis::setAutoTickCount)
  10253. \li sub tick count (\ref QCPAxis::setSubTickCount)
  10254. \li auto sub ticks (\ref QCPAxis::setAutoSubTicks)
  10255. \li tick step (\ref QCPAxis::setTickStep)
  10256. \li auto tick step (\ref QCPAxis::setAutoTickStep)
  10257. \li number format (\ref QCPAxis::setNumberFormat)
  10258. \li number precision (\ref QCPAxis::setNumberPrecision)
  10259. \li tick label type (\ref QCPAxis::setTickLabelType)
  10260. \li date time format (\ref QCPAxis::setDateTimeFormat)
  10261. \li date time spec (\ref QCPAxis::setDateTimeSpec)
  10262. Tick labels (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
  10263. If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom
  10264. and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes.
  10265. */
  10266. void QCPAxisRect::setupFullAxesBox(bool connectRanges)
  10267. {
  10268. QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
  10269. if (axisCount(QCPAxis::atBottom) == 0)
  10270. xAxis = addAxis(QCPAxis::atBottom);
  10271. else
  10272. xAxis = axis(QCPAxis::atBottom);
  10273. if (axisCount(QCPAxis::atLeft) == 0)
  10274. yAxis = addAxis(QCPAxis::atLeft);
  10275. else
  10276. yAxis = axis(QCPAxis::atLeft);
  10277. if (axisCount(QCPAxis::atTop) == 0)
  10278. xAxis2 = addAxis(QCPAxis::atTop);
  10279. else
  10280. xAxis2 = axis(QCPAxis::atTop);
  10281. if (axisCount(QCPAxis::atRight) == 0)
  10282. yAxis2 = addAxis(QCPAxis::atRight);
  10283. else
  10284. yAxis2 = axis(QCPAxis::atRight);
  10285. xAxis->setVisible(true);
  10286. yAxis->setVisible(true);
  10287. xAxis2->setVisible(true);
  10288. yAxis2->setVisible(true);
  10289. xAxis2->setTickLabels(false);
  10290. yAxis2->setTickLabels(false);
  10291. xAxis2->setRange(xAxis->range());
  10292. xAxis2->setRangeReversed(xAxis->rangeReversed());
  10293. xAxis2->setScaleType(xAxis->scaleType());
  10294. xAxis2->setScaleLogBase(xAxis->scaleLogBase());
  10295. xAxis2->setTicks(xAxis->ticks());
  10296. xAxis2->setAutoTickCount(xAxis->autoTickCount());
  10297. xAxis2->setSubTickCount(xAxis->subTickCount());
  10298. xAxis2->setAutoSubTicks(xAxis->autoSubTicks());
  10299. xAxis2->setTickStep(xAxis->tickStep());
  10300. xAxis2->setAutoTickStep(xAxis->autoTickStep());
  10301. xAxis2->setNumberFormat(xAxis->numberFormat());
  10302. xAxis2->setNumberPrecision(xAxis->numberPrecision());
  10303. xAxis2->setTickLabelType(xAxis->tickLabelType());
  10304. xAxis2->setDateTimeFormat(xAxis->dateTimeFormat());
  10305. xAxis2->setDateTimeSpec(xAxis->dateTimeSpec());
  10306. yAxis2->setRange(yAxis->range());
  10307. yAxis2->setRangeReversed(yAxis->rangeReversed());
  10308. yAxis2->setScaleType(yAxis->scaleType());
  10309. yAxis2->setScaleLogBase(yAxis->scaleLogBase());
  10310. yAxis2->setTicks(yAxis->ticks());
  10311. yAxis2->setAutoTickCount(yAxis->autoTickCount());
  10312. yAxis2->setSubTickCount(yAxis->subTickCount());
  10313. yAxis2->setAutoSubTicks(yAxis->autoSubTicks());
  10314. yAxis2->setTickStep(yAxis->tickStep());
  10315. yAxis2->setAutoTickStep(yAxis->autoTickStep());
  10316. yAxis2->setNumberFormat(yAxis->numberFormat());
  10317. yAxis2->setNumberPrecision(yAxis->numberPrecision());
  10318. yAxis2->setTickLabelType(yAxis->tickLabelType());
  10319. yAxis2->setDateTimeFormat(yAxis->dateTimeFormat());
  10320. yAxis2->setDateTimeSpec(yAxis->dateTimeSpec());
  10321. if (connectRanges) {
  10322. connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange)));
  10323. connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange)));
  10324. }
  10325. }
  10326. /*!
  10327. Returns a list of all the plottables that are associated with this axis rect.
  10328. A plottable is considered associated with an axis rect if its key or value axis (or both) is in
  10329. this axis rect.
  10330. \see graphs, items
  10331. */
  10332. QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const
  10333. {
  10334. // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate
  10335. // entries
  10336. QList<QCPAbstractPlottable*> result;
  10337. for (int i = 0; i < mParentPlot->mPlottables.size(); ++i) {
  10338. if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this
  10339. || mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this)
  10340. result.append(mParentPlot->mPlottables.at(i));
  10341. }
  10342. return result;
  10343. }
  10344. /*!
  10345. Returns a list of all the graphs that are associated with this axis rect.
  10346. A graph is considered associated with an axis rect if its key or value axis (or both) is in
  10347. this axis rect.
  10348. \see plottables, items
  10349. */
  10350. QList<QCPGraph*> QCPAxisRect::graphs() const
  10351. {
  10352. // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries
  10353. QList<QCPGraph*> result;
  10354. for (int i = 0; i < mParentPlot->mGraphs.size(); ++i) {
  10355. if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this
  10356. || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this)
  10357. result.append(mParentPlot->mGraphs.at(i));
  10358. }
  10359. return result;
  10360. }
  10361. /*!
  10362. Returns a list of all the items that are associated with this axis rect.
  10363. An item is considered associated with an axis rect if any of its positions has key or value axis
  10364. set to an axis that is in this axis rect, or if any of its positions has \ref
  10365. QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref
  10366. QCPAbstractItem::setClipAxisRect) is set to this axis rect.
  10367. \see plottables, graphs
  10368. */
  10369. QList<QCPAbstractItem*> QCPAxisRect::items() const
  10370. {
  10371. // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate
  10372. // entries
  10373. // and miss those items that have this axis rect as clipAxisRect.
  10374. QList<QCPAbstractItem*> result;
  10375. for (int itemId = 0; itemId < mParentPlot->mItems.size(); ++itemId) {
  10376. if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this) {
  10377. result.append(mParentPlot->mItems.at(itemId));
  10378. continue;
  10379. }
  10380. QList<QCPItemPosition*> positions = mParentPlot->mItems.at(itemId)->positions();
  10381. for (int posId = 0; posId < positions.size(); ++posId) {
  10382. if (positions.at(posId)->axisRect() == this
  10383. || positions.at(posId)->keyAxis()->axisRect() == this
  10384. || positions.at(posId)->valueAxis()->axisRect() == this) {
  10385. result.append(mParentPlot->mItems.at(itemId));
  10386. break;
  10387. }
  10388. }
  10389. }
  10390. return result;
  10391. }
  10392. /*!
  10393. This method is called automatically upon replot and doesn't need to be called by users of
  10394. QCPAxisRect.
  10395. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
  10396. and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
  10397. QCPInsetLayout::update function.
  10398. */
  10399. void QCPAxisRect::update(UpdatePhase phase)
  10400. {
  10401. QCPLayoutElement::update(phase);
  10402. switch (phase) {
  10403. case upPreparation: {
  10404. QList<QCPAxis*> allAxes = axes();
  10405. for (int i = 0; i < allAxes.size(); ++i)
  10406. allAxes.at(i)->setupTickVectors();
  10407. break;
  10408. }
  10409. case upLayout: {
  10410. mInsetLayout->setOuterRect(rect());
  10411. break;
  10412. }
  10413. default:
  10414. break;
  10415. }
  10416. // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect
  10417. // doesn't derive from QCPLayout):
  10418. mInsetLayout->update(phase);
  10419. }
  10420. /* inherits documentation from base class */
  10421. QList<QCPLayoutElement*> QCPAxisRect::elements(bool recursive) const
  10422. {
  10423. QList<QCPLayoutElement*> result;
  10424. if (mInsetLayout) {
  10425. result << mInsetLayout;
  10426. if (recursive)
  10427. result << mInsetLayout->elements(recursive);
  10428. }
  10429. return result;
  10430. }
  10431. /* inherits documentation from base class */
  10432. void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter* painter) const
  10433. {
  10434. painter->setAntialiasing(false);
  10435. }
  10436. /* inherits documentation from base class */
  10437. void QCPAxisRect::draw(QCPPainter* painter)
  10438. {
  10439. drawBackground(painter);
  10440. }
  10441. /*!
  10442. Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
  10443. axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
  10444. backgrounds are usually drawn below everything else.
  10445. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
  10446. enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
  10447. is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  10448. consider using the overloaded version of this function.
  10449. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
  10450. setBackground(const QBrush &brush).
  10451. \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
  10452. */
  10453. void QCPAxisRect::setBackground(const QPixmap& pm)
  10454. {
  10455. mBackgroundPixmap = pm;
  10456. mScaledBackgroundPixmap = QPixmap();
  10457. }
  10458. /*! \overload
  10459. Sets \a brush as the background brush. The axis rect background will be filled with this brush.
  10460. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
  10461. are usually drawn below everything else.
  10462. The brush will be drawn before (under) any background pixmap, which may be specified with \ref
  10463. setBackground(const QPixmap &pm).
  10464. To disable drawing of a background brush, set \a brush to Qt::NoBrush.
  10465. \see setBackground(const QPixmap &pm)
  10466. */
  10467. void QCPAxisRect::setBackground(const QBrush& brush)
  10468. {
  10469. mBackgroundBrush = brush;
  10470. }
  10471. /*! \overload
  10472. Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
  10473. shall be scaled in one call.
  10474. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  10475. */
  10476. void QCPAxisRect::setBackground(const QPixmap& pm, bool scaled, Qt::AspectRatioMode mode)
  10477. {
  10478. mBackgroundPixmap = pm;
  10479. mScaledBackgroundPixmap = QPixmap();
  10480. mBackgroundScaled = scaled;
  10481. mBackgroundScaledMode = mode;
  10482. }
  10483. /*!
  10484. Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
  10485. is set to true, you may control whether and how the aspect ratio of the original pixmap is
  10486. preserved with \ref setBackgroundScaledMode.
  10487. Note that the scaled version of the original pixmap is buffered, so there is no performance
  10488. penalty on replots. (Except when the axis rect dimensions are changed continuously.)
  10489. \see setBackground, setBackgroundScaledMode
  10490. */
  10491. void QCPAxisRect::setBackgroundScaled(bool scaled)
  10492. {
  10493. mBackgroundScaled = scaled;
  10494. }
  10495. /*!
  10496. If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function
  10497. to define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is
  10498. preserved. \see setBackground, setBackgroundScaled
  10499. */
  10500. void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  10501. {
  10502. mBackgroundScaledMode = mode;
  10503. }
  10504. /*!
  10505. Returns the range drag axis of the \a orientation provided.
  10506. \see setRangeDragAxes
  10507. */
  10508. QCPAxis* QCPAxisRect::rangeDragAxis(Qt::Orientation orientation)
  10509. {
  10510. return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data());
  10511. }
  10512. /*!
  10513. Returns the range zoom axis of the \a orientation provided.
  10514. \see setRangeZoomAxes
  10515. */
  10516. QCPAxis* QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation)
  10517. {
  10518. return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data());
  10519. }
  10520. /*!
  10521. Returns the range zoom factor of the \a orientation provided.
  10522. \see setRangeZoomFactor
  10523. */
  10524. double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation)
  10525. {
  10526. return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert);
  10527. }
  10528. /*!
  10529. Sets which axis orientation may be range dragged by the user with mouse interaction.
  10530. What orientation corresponds to which specific axis can be set with
  10531. \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By
  10532. default, the horizontal axis is the bottom axis (xAxis) and the vertical axis
  10533. is the left axis (yAxis).
  10534. To disable range dragging entirely, pass 0 as \a orientations or remove \ref QCP::iRangeDrag from
  10535. \ref QCustomPlot::setInteractions. To enable range dragging for both directions, pass
  10536. <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations.
  10537. In addition to setting \a orientations to a non-zero value, make sure \ref
  10538. QCustomPlot::setInteractions contains \ref QCP::iRangeDrag to enable the range dragging
  10539. interaction.
  10540. \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag
  10541. */
  10542. void QCPAxisRect::setRangeDrag(Qt::Orientations orientations)
  10543. {
  10544. mRangeDrag = orientations;
  10545. }
  10546. /*!
  10547. Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation
  10548. corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal,
  10549. QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical
  10550. axis is the left axis (yAxis).
  10551. To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from
  10552. \ref QCustomPlot::setInteractions. To enable range zooming for both directions, pass
  10553. <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations.
  10554. In addition to setting \a orientations to a non-zero value, make sure \ref
  10555. QCustomPlot::setInteractions contains \ref QCP::iRangeZoom to enable the range zooming
  10556. interaction.
  10557. \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag
  10558. */
  10559. void QCPAxisRect::setRangeZoom(Qt::Orientations orientations)
  10560. {
  10561. mRangeZoom = orientations;
  10562. }
  10563. /*!
  10564. Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging
  10565. on the QCustomPlot widget.
  10566. \see setRangeZoomAxes
  10567. */
  10568. void QCPAxisRect::setRangeDragAxes(QCPAxis* horizontal, QCPAxis* vertical)
  10569. {
  10570. mRangeDragHorzAxis = horizontal;
  10571. mRangeDragVertAxis = vertical;
  10572. }
  10573. /*!
  10574. Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on the
  10575. QCustomPlot widget. The two axes can be zoomed with different strengths, when different factors
  10576. are passed to \ref setRangeZoomFactor(double horizontalFactor, double verticalFactor).
  10577. \see setRangeDragAxes
  10578. */
  10579. void QCPAxisRect::setRangeZoomAxes(QCPAxis* horizontal, QCPAxis* vertical)
  10580. {
  10581. mRangeZoomHorzAxis = horizontal;
  10582. mRangeZoomVertAxis = vertical;
  10583. }
  10584. /*!
  10585. Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with
  10586. \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to
  10587. let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal
  10588. and which is vertical, can be set with \ref setRangeZoomAxes.
  10589. When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user)
  10590. will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the
  10591. same scrolling direction will zoom out.
  10592. */
  10593. void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor)
  10594. {
  10595. mRangeZoomFactorHorz = horizontalFactor;
  10596. mRangeZoomFactorVert = verticalFactor;
  10597. }
  10598. /*! \overload
  10599. Sets both the horizontal and vertical zoom \a factor.
  10600. */
  10601. void QCPAxisRect::setRangeZoomFactor(double factor)
  10602. {
  10603. mRangeZoomFactorHorz = factor;
  10604. mRangeZoomFactorVert = factor;
  10605. }
  10606. /*! \internal
  10607. Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
  10608. pixmap.
  10609. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
  10610. according filling inside the axis rect with the provided \a painter.
  10611. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
  10612. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  10613. the axis rect with the provided \a painter. The scaled version is buffered in
  10614. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  10615. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  10616. dependant on the \ref setBackgroundScaledMode), or when a differend axis backgroud pixmap was
  10617. set.
  10618. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  10619. */
  10620. void QCPAxisRect::drawBackground(QCPPainter* painter)
  10621. {
  10622. // draw background fill:
  10623. if (mBackgroundBrush != Qt::NoBrush)
  10624. painter->fillRect(mRect, mBackgroundBrush);
  10625. // draw background pixmap (on top of fill, if brush specified):
  10626. if (!mBackgroundPixmap.isNull()) {
  10627. if (mBackgroundScaled) {
  10628. // check whether mScaledBackground needs to be updated:
  10629. QSize scaledSize(mBackgroundPixmap.size());
  10630. scaledSize.scale(mRect.size(), mBackgroundScaledMode);
  10631. if (mScaledBackgroundPixmap.size() != scaledSize)
  10632. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(
  10633. mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  10634. painter->drawPixmap(
  10635. mRect.topLeft() + QPoint(0, -1), mScaledBackgroundPixmap,
  10636. QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
  10637. } else {
  10638. painter->drawPixmap(mRect.topLeft() + QPoint(0, -1), mBackgroundPixmap,
  10639. QRect(0, 0, mRect.width(), mRect.height()));
  10640. }
  10641. }
  10642. }
  10643. /*! \internal
  10644. This function makes sure multiple axes on the side specified with \a type don't collide, but are
  10645. distributed according to their respective space requirement (QCPAxis::calculateMargin).
  10646. It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the
  10647. one with index zero.
  10648. This function is called by \ref calculateAutoMargin.
  10649. */
  10650. void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type)
  10651. {
  10652. const QList<QCPAxis*> axesList = mAxes.value(type);
  10653. if (axesList.isEmpty())
  10654. return;
  10655. bool isFirstVisible =
  10656. !axesList.first()
  10657. ->visible(); // if the first axis is visible, the second axis (which is where the loop
  10658. // starts) isn't the first visible axis, so initialize with false
  10659. for (int i = 1; i < axesList.size(); ++i) {
  10660. int offset = axesList.at(i - 1)->offset() + axesList.at(i - 1)->calculateMargin();
  10661. if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is
  10662. // visible and it's not the first visible one (might happen
  10663. // if true first axis is invisible)
  10664. {
  10665. if (!isFirstVisible)
  10666. offset += axesList.at(i)->tickLengthIn();
  10667. isFirstVisible = false;
  10668. }
  10669. axesList.at(i)->setOffset(offset);
  10670. }
  10671. }
  10672. /* inherits documentation from base class */
  10673. int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
  10674. {
  10675. if (!mAutoMargins.testFlag(side))
  10676. qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin";
  10677. updateAxesOffset(QCPAxis::marginSideToAxisType(side));
  10678. // note: only need to look at the last (outer most) axis to determine the total margin, due to
  10679. // updateAxisOffset call
  10680. const QList<QCPAxis*> axesList = mAxes.value(QCPAxis::marginSideToAxisType(side));
  10681. if (axesList.size() > 0)
  10682. return axesList.last()->offset() + axesList.last()->calculateMargin();
  10683. else
  10684. return 0;
  10685. }
  10686. /*! \internal
  10687. Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
  10688. pressed, the range dragging interaction is initialized (the actual range manipulation happens in
  10689. the \ref mouseMoveEvent).
  10690. The mDragging flag is set to true and some anchor points are set that are needed to determine the
  10691. distance the mouse was dragged in the mouse move/release events later.
  10692. \see mouseMoveEvent, mouseReleaseEvent
  10693. */
  10694. void QCPAxisRect::mousePressEvent(QMouseEvent* event)
  10695. {
  10696. mDragStart =
  10697. event->pos(); // need this even when not LeftButton is pressed, to determine in releaseEvent
  10698. // whether it was a full click (no position change between press and release)
  10699. if (event->buttons() & Qt::LeftButton) {
  10700. mDragging = true;
  10701. // initialize antialiasing backup in case we start dragging:
  10702. if (mParentPlot->noAntialiasingOnDrag()) {
  10703. mAADragBackup = mParentPlot->antialiasedElements();
  10704. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  10705. }
  10706. // Mouse range dragging interaction:
  10707. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) {
  10708. if (mRangeDragHorzAxis)
  10709. mDragStartHorzRange = mRangeDragHorzAxis.data()->range();
  10710. if (mRangeDragVertAxis)
  10711. mDragStartVertRange = mRangeDragVertAxis.data()->range();
  10712. }
  10713. }
  10714. }
  10715. /*! \internal
  10716. Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
  10717. preceding \ref mousePressEvent, the range is moved accordingly.
  10718. \see mousePressEvent, mouseReleaseEvent
  10719. */
  10720. void QCPAxisRect::mouseMoveEvent(QMouseEvent* event)
  10721. {
  10722. // Mouse range dragging interaction:
  10723. if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) {
  10724. if (mRangeDrag.testFlag(Qt::Horizontal)) {
  10725. if (QCPAxis* rangeDragHorzAxis = mRangeDragHorzAxis.data()) {
  10726. if (rangeDragHorzAxis->mScaleType == QCPAxis::stLinear) {
  10727. double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x())
  10728. - rangeDragHorzAxis->pixelToCoord(event->pos().x());
  10729. rangeDragHorzAxis->setRange(mDragStartHorzRange.lower + diff,
  10730. mDragStartHorzRange.upper + diff);
  10731. } else if (rangeDragHorzAxis->mScaleType == QCPAxis::stLogarithmic) {
  10732. double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x())
  10733. / rangeDragHorzAxis->pixelToCoord(event->pos().x());
  10734. rangeDragHorzAxis->setRange(mDragStartHorzRange.lower * diff,
  10735. mDragStartHorzRange.upper * diff);
  10736. }
  10737. }
  10738. }
  10739. if (mRangeDrag.testFlag(Qt::Vertical)) {
  10740. if (QCPAxis* rangeDragVertAxis = mRangeDragVertAxis.data()) {
  10741. if (rangeDragVertAxis->mScaleType == QCPAxis::stLinear) {
  10742. double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y())
  10743. - rangeDragVertAxis->pixelToCoord(event->pos().y());
  10744. rangeDragVertAxis->setRange(mDragStartVertRange.lower + diff,
  10745. mDragStartVertRange.upper + diff);
  10746. } else if (rangeDragVertAxis->mScaleType == QCPAxis::stLogarithmic) {
  10747. double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y())
  10748. / rangeDragVertAxis->pixelToCoord(event->pos().y());
  10749. rangeDragVertAxis->setRange(mDragStartVertRange.lower * diff,
  10750. mDragStartVertRange.upper * diff);
  10751. }
  10752. }
  10753. }
  10754. if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot
  10755. {
  10756. if (mParentPlot->noAntialiasingOnDrag())
  10757. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  10758. mParentPlot->replot();
  10759. }
  10760. }
  10761. }
  10762. /* inherits documentation from base class */
  10763. void QCPAxisRect::mouseReleaseEvent(QMouseEvent* event)
  10764. {
  10765. Q_UNUSED(event)
  10766. mDragging = false;
  10767. if (mParentPlot->noAntialiasingOnDrag()) {
  10768. mParentPlot->setAntialiasedElements(mAADragBackup);
  10769. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  10770. }
  10771. }
  10772. /*! \internal
  10773. Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
  10774. ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
  10775. the scaling operation is the current cursor position inside the axis rect. The scaling factor is
  10776. dependant on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
  10777. zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
  10778. Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse
  10779. wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be
  10780. multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as
  10781. exponent of the range zoom factor. This takes care of the wheel direction automatically, by
  10782. inverting the factor, when the wheel step is negative (f^-1 = 1/f).
  10783. */
  10784. void QCPAxisRect::wheelEvent(QWheelEvent* event)
  10785. {
  10786. // Mouse range zooming interaction:
  10787. if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) {
  10788. if (mRangeZoom != 0) {
  10789. double factor;
  10790. double wheelSteps = event->delta() / 120.0; // a single step delta is +/-120 usually
  10791. if (mRangeZoom.testFlag(Qt::Horizontal)) {
  10792. factor = qPow(mRangeZoomFactorHorz, wheelSteps);
  10793. if (mRangeZoomHorzAxis.data())
  10794. mRangeZoomHorzAxis.data()->scaleRange(
  10795. factor, mRangeZoomHorzAxis.data()->pixelToCoord(event->pos().x()));
  10796. }
  10797. if (mRangeZoom.testFlag(Qt::Vertical)) {
  10798. factor = qPow(mRangeZoomFactorVert, wheelSteps);
  10799. if (mRangeZoomVertAxis.data())
  10800. mRangeZoomVertAxis.data()->scaleRange(
  10801. factor, mRangeZoomVertAxis.data()->pixelToCoord(event->pos().y()));
  10802. }
  10803. mParentPlot->replot();
  10804. }
  10805. }
  10806. }
  10807. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10808. //////////////////// QCPAbstractLegendItem
  10809. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10810. /*! \class QCPAbstractLegendItem
  10811. \brief The abstract base class for all entries in a QCPLegend.
  10812. It defines a very basic interface for entries in a QCPLegend. For representing plottables in the
  10813. legend, the subclass \ref QCPPlottableLegendItem is more suitable.
  10814. Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry
  10815. that's not even associated with a plottable).
  10816. You must implement the following pure virtual functions:
  10817. \li \ref draw (from QCPLayerable)
  10818. You inherit the following members you may use:
  10819. <table>
  10820. <tr>
  10821. <td>QCPLegend *\b mParentLegend</td>
  10822. <td>A pointer to the parent QCPLegend.</td>
  10823. </tr><tr>
  10824. <td>QFont \b mFont</td>
  10825. <td>The generic font of the item. You should use this font for all or at least the most
  10826. prominent text of the item.</td>
  10827. </tr>
  10828. </table>
  10829. */
  10830. /* start of documentation of signals */
  10831. /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected)
  10832. This signal is emitted when the selection state of this legend item has changed, either by user
  10833. interaction or by a direct call to \ref setSelected.
  10834. */
  10835. /* end of documentation of signals */
  10836. /*!
  10837. Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not
  10838. cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately.
  10839. */
  10840. QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend* parent)
  10841. : QCPLayoutElement(parent->parentPlot())
  10842. , mParentLegend(parent)
  10843. , mFont(parent->font())
  10844. , mTextColor(parent->textColor())
  10845. , mSelectedFont(parent->selectedFont())
  10846. , mSelectedTextColor(parent->selectedTextColor())
  10847. , mSelectable(true)
  10848. , mSelected(false)
  10849. {
  10850. setLayer(QLatin1String("legend"));
  10851. setMargins(QMargins(8, 2, 8, 2));
  10852. }
  10853. /*!
  10854. Sets the default font of this specific legend item to \a font.
  10855. \see setTextColor, QCPLegend::setFont
  10856. */
  10857. void QCPAbstractLegendItem::setFont(const QFont& font)
  10858. {
  10859. mFont = font;
  10860. }
  10861. /*!
  10862. Sets the default text color of this specific legend item to \a color.
  10863. \see setFont, QCPLegend::setTextColor
  10864. */
  10865. void QCPAbstractLegendItem::setTextColor(const QColor& color)
  10866. {
  10867. mTextColor = color;
  10868. }
  10869. /*!
  10870. When this legend item is selected, \a font is used to draw generic text, instead of the normal
  10871. font set with \ref setFont.
  10872. \see setFont, QCPLegend::setSelectedFont
  10873. */
  10874. void QCPAbstractLegendItem::setSelectedFont(const QFont& font)
  10875. {
  10876. mSelectedFont = font;
  10877. }
  10878. /*!
  10879. When this legend item is selected, \a color is used to draw generic text, instead of the normal
  10880. color set with \ref setTextColor.
  10881. \see setTextColor, QCPLegend::setSelectedTextColor
  10882. */
  10883. void QCPAbstractLegendItem::setSelectedTextColor(const QColor& color)
  10884. {
  10885. mSelectedTextColor = color;
  10886. }
  10887. /*!
  10888. Sets whether this specific legend item is selectable.
  10889. \see setSelectedParts, QCustomPlot::setInteractions
  10890. */
  10891. void QCPAbstractLegendItem::setSelectable(bool selectable)
  10892. {
  10893. if (mSelectable != selectable) {
  10894. mSelectable = selectable;
  10895. emit selectableChanged(mSelectable);
  10896. }
  10897. }
  10898. /*!
  10899. Sets whether this specific legend item is selected.
  10900. It is possible to set the selection state of this item by calling this function directly, even if
  10901. setSelectable is set to false.
  10902. \see setSelectableParts, QCustomPlot::setInteractions
  10903. */
  10904. void QCPAbstractLegendItem::setSelected(bool selected)
  10905. {
  10906. if (mSelected != selected) {
  10907. mSelected = selected;
  10908. emit selectionChanged(mSelected);
  10909. }
  10910. }
  10911. /* inherits documentation from base class */
  10912. double QCPAbstractLegendItem::selectTest(const QPointF& pos, bool onlySelectable,
  10913. QVariant* details) const
  10914. {
  10915. Q_UNUSED(details)
  10916. if (!mParentPlot)
  10917. return -1;
  10918. if (onlySelectable
  10919. && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems)))
  10920. return -1;
  10921. if (mRect.contains(pos.toPoint()))
  10922. return mParentPlot->selectionTolerance() * 0.99;
  10923. else
  10924. return -1;
  10925. }
  10926. /* inherits documentation from base class */
  10927. void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter* painter) const
  10928. {
  10929. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems);
  10930. }
  10931. /* inherits documentation from base class */
  10932. QRect QCPAbstractLegendItem::clipRect() const
  10933. {
  10934. return mOuterRect;
  10935. }
  10936. /* inherits documentation from base class */
  10937. void QCPAbstractLegendItem::selectEvent(QMouseEvent* event, bool additive, const QVariant& details,
  10938. bool* selectionStateChanged)
  10939. {
  10940. Q_UNUSED(event)
  10941. Q_UNUSED(details)
  10942. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) {
  10943. bool selBefore = mSelected;
  10944. setSelected(additive ? !mSelected : true);
  10945. if (selectionStateChanged)
  10946. *selectionStateChanged = mSelected != selBefore;
  10947. }
  10948. }
  10949. /* inherits documentation from base class */
  10950. void QCPAbstractLegendItem::deselectEvent(bool* selectionStateChanged)
  10951. {
  10952. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) {
  10953. bool selBefore = mSelected;
  10954. setSelected(false);
  10955. if (selectionStateChanged)
  10956. *selectionStateChanged = mSelected != selBefore;
  10957. }
  10958. }
  10959. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10960. //////////////////// QCPPlottableLegendItem
  10961. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10962. /*! \class QCPPlottableLegendItem
  10963. \brief A legend item representing a plottable with an icon and the plottable name.
  10964. This is the standard legend item for plottables. It displays an icon of the plottable next to the
  10965. plottable name. The icon is drawn by the respective plottable itself (\ref
  10966. QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable.
  10967. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the
  10968. middle.
  10969. Legend items of this type are always associated with one plottable (retrievable via the
  10970. plottable() function and settable with the constructor). You may change the font of the plottable
  10971. name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref
  10972. QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding.
  10973. The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend
  10974. creates/removes legend items of this type in the default implementation. However, these functions
  10975. may be reimplemented such that a different kind of legend item (e.g a direct subclass of
  10976. QCPAbstractLegendItem) is used for that plottable.
  10977. Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of
  10978. QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout
  10979. interface, QCPLegend has specialized functions for handling legend items conveniently, see the
  10980. documentation of \ref QCPLegend.
  10981. */
  10982. /*!
  10983. Creates a new legend item associated with \a plottable.
  10984. Once it's created, it can be added to the legend via \ref QCPLegend::addItem.
  10985. A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref
  10986. QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend.
  10987. */
  10988. QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend* parent, QCPAbstractPlottable* plottable)
  10989. : QCPAbstractLegendItem(parent), mPlottable(plottable)
  10990. {}
  10991. /*! \internal
  10992. Returns the pen that shall be used to draw the icon border, taking into account the selection
  10993. state of this item.
  10994. */
  10995. QPen QCPPlottableLegendItem::getIconBorderPen() const
  10996. {
  10997. return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
  10998. }
  10999. /*! \internal
  11000. Returns the text color that shall be used to draw text, taking into account the selection state
  11001. of this item.
  11002. */
  11003. QColor QCPPlottableLegendItem::getTextColor() const
  11004. {
  11005. return mSelected ? mSelectedTextColor : mTextColor;
  11006. }
  11007. /*! \internal
  11008. Returns the font that shall be used to draw text, taking into account the selection state of this
  11009. item.
  11010. */
  11011. QFont QCPPlottableLegendItem::getFont() const
  11012. {
  11013. return mSelected ? mSelectedFont : mFont;
  11014. }
  11015. /*! \internal
  11016. Draws the item with \a painter. The size and position of the drawn legend item is defined by the
  11017. parent layout (typically a \ref QCPLegend) and the \ref minimumSizeHint and \ref maximumSizeHint
  11018. of this legend item.
  11019. */
  11020. void QCPPlottableLegendItem::draw(QCPPainter* painter)
  11021. {
  11022. if (!mPlottable)
  11023. return;
  11024. painter->setFont(getFont());
  11025. painter->setPen(QPen(getTextColor()));
  11026. QSizeF iconSize = mParentLegend->iconSize();
  11027. QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(),
  11028. Qt::TextDontClip, mPlottable->name());
  11029. QRectF iconRect(mRect.topLeft(), iconSize);
  11030. int textHeight = qMax(textRect.height(),
  11031. iconSize.height()); // if text has smaller height than icon, center text
  11032. // vertically in icon height, else align tops
  11033. painter->drawText(mRect.x() + iconSize.width() + mParentLegend->iconTextPadding(), mRect.y(),
  11034. textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name());
  11035. // draw icon:
  11036. painter->save();
  11037. painter->setClipRect(iconRect, Qt::IntersectClip);
  11038. mPlottable->drawLegendIcon(painter, iconRect);
  11039. painter->restore();
  11040. // draw icon border:
  11041. if (getIconBorderPen().style() != Qt::NoPen) {
  11042. painter->setPen(getIconBorderPen());
  11043. painter->setBrush(Qt::NoBrush);
  11044. painter->drawRect(iconRect);
  11045. }
  11046. }
  11047. /*! \internal
  11048. Calculates and returns the size of this item. This includes the icon, the text and the padding in
  11049. between.
  11050. */
  11051. QSize QCPPlottableLegendItem::minimumSizeHint() const
  11052. {
  11053. if (!mPlottable)
  11054. return QSize();
  11055. QSize result(0, 0);
  11056. QRect textRect;
  11057. QFontMetrics fontMetrics(getFont());
  11058. QSize iconSize = mParentLegend->iconSize();
  11059. textRect =
  11060. fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  11061. result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width()
  11062. + mMargins.left() + mMargins.right());
  11063. result.setHeight(qMax(textRect.height(), iconSize.height()) + mMargins.top()
  11064. + mMargins.bottom());
  11065. return result;
  11066. }
  11067. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11068. //////////////////// QCPLegend
  11069. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11070. /*! \class QCPLegend
  11071. \brief Manages a legend inside a QCustomPlot.
  11072. A legend is a small box somewhere in the plot which lists plottables with their name and icon.
  11073. Normally, the legend is populated by calling \ref QCPAbstractPlottable::addToLegend. The
  11074. respective legend item can be removed with \ref QCPAbstractPlottable::removeFromLegend. However,
  11075. QCPLegend also offers an interface to add and manipulate legend items directly: \ref item, \ref
  11076. itemWithPlottable, \ref itemCount, \ref addItem, \ref removeItem, etc.
  11077. The QCPLegend derives from QCPLayoutGrid and as such can be placed in any position a
  11078. QCPLayoutElement may be positioned. The legend items are themselves QCPLayoutElements which are
  11079. placed in the grid layout of the legend. QCPLegend only adds an interface specialized for
  11080. handling child elements of type QCPAbstractLegendItem, as mentioned above. In principle, any
  11081. other layout elements may also be added to a legend via the normal \ref QCPLayoutGrid interface.
  11082. However, the QCPAbstractLegendItem-Interface will ignore those elements (e.g. \ref itemCount will
  11083. only return the number of items with QCPAbstractLegendItems type).
  11084. By default, every QCustomPlot has one legend (QCustomPlot::legend) which is placed in the inset
  11085. layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
  11086. position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend
  11087. outside of the axis rect, place it anywhere else with the QCPLayout/QCPLayoutElement interface.
  11088. */
  11089. /* start of documentation of signals */
  11090. /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection);
  11091. This signal is emitted when the selection state of this legend has changed.
  11092. \see setSelectedParts, setSelectableParts
  11093. */
  11094. /* end of documentation of signals */
  11095. /*!
  11096. Constructs a new QCPLegend instance with \a parentPlot as the containing plot and default values.
  11097. Note that by default, QCustomPlot already contains a legend ready to be used as
  11098. QCustomPlot::legend
  11099. */
  11100. QCPLegend::QCPLegend()
  11101. {
  11102. setRowSpacing(0);
  11103. setColumnSpacing(10);
  11104. setMargins(QMargins(2, 3, 2, 2));
  11105. setAntialiased(false);
  11106. setIconSize(32, 18);
  11107. setIconTextPadding(7);
  11108. setSelectableParts(spLegendBox | spItems);
  11109. setSelectedParts(spNone);
  11110. setBorderPen(QPen(Qt::black));
  11111. setSelectedBorderPen(QPen(Qt::blue, 2));
  11112. setIconBorderPen(Qt::NoPen);
  11113. setSelectedIconBorderPen(QPen(Qt::blue, 2));
  11114. setBrush(Qt::white);
  11115. setSelectedBrush(Qt::white);
  11116. setTextColor(Qt::black);
  11117. setSelectedTextColor(Qt::blue);
  11118. }
  11119. QCPLegend::~QCPLegend()
  11120. {
  11121. clearItems();
  11122. if (qobject_cast<QCustomPlot*>(
  11123. mParentPlot)) // make sure this isn't called from QObject dtor when QCustomPlot is
  11124. // already destructed (happens when the legend is not in any layout and
  11125. // thus QObject-child of QCustomPlot)
  11126. mParentPlot->legendRemoved(this);
  11127. }
  11128. /* no doc for getter, see setSelectedParts */
  11129. QCPLegend::SelectableParts QCPLegend::selectedParts() const
  11130. {
  11131. // check whether any legend elements selected, if yes, add spItems to return value
  11132. bool hasSelectedItems = false;
  11133. for (int i = 0; i < itemCount(); ++i) {
  11134. if (item(i) && item(i)->selected()) {
  11135. hasSelectedItems = true;
  11136. break;
  11137. }
  11138. }
  11139. if (hasSelectedItems)
  11140. return mSelectedParts | spItems;
  11141. else
  11142. return mSelectedParts & ~spItems;
  11143. }
  11144. /*!
  11145. Sets the pen, the border of the entire legend is drawn with.
  11146. */
  11147. void QCPLegend::setBorderPen(const QPen& pen)
  11148. {
  11149. mBorderPen = pen;
  11150. }
  11151. /*!
  11152. Sets the brush of the legend background.
  11153. */
  11154. void QCPLegend::setBrush(const QBrush& brush)
  11155. {
  11156. mBrush = brush;
  11157. }
  11158. /*!
  11159. Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will
  11160. use this font by default. However, a different font can be specified on a per-item-basis by
  11161. accessing the specific legend item.
  11162. This function will also set \a font on all already existing legend items.
  11163. \see QCPAbstractLegendItem::setFont
  11164. */
  11165. void QCPLegend::setFont(const QFont& font)
  11166. {
  11167. mFont = font;
  11168. for (int i = 0; i < itemCount(); ++i) {
  11169. if (item(i))
  11170. item(i)->setFont(mFont);
  11171. }
  11172. }
  11173. /*!
  11174. Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph)
  11175. will use this color by default. However, a different colors can be specified on a per-item-basis
  11176. by accessing the specific legend item.
  11177. This function will also set \a color on all already existing legend items.
  11178. \see QCPAbstractLegendItem::setTextColor
  11179. */
  11180. void QCPLegend::setTextColor(const QColor& color)
  11181. {
  11182. mTextColor = color;
  11183. for (int i = 0; i < itemCount(); ++i) {
  11184. if (item(i))
  11185. item(i)->setTextColor(color);
  11186. }
  11187. }
  11188. /*!
  11189. Sets the size of legend icons. Legend items that draw an icon (e.g. a visual
  11190. representation of the graph) will use this size by default.
  11191. */
  11192. void QCPLegend::setIconSize(const QSize& size)
  11193. {
  11194. mIconSize = size;
  11195. }
  11196. /*! \overload
  11197. */
  11198. void QCPLegend::setIconSize(int width, int height)
  11199. {
  11200. mIconSize.setWidth(width);
  11201. mIconSize.setHeight(height);
  11202. }
  11203. /*!
  11204. Sets the horizontal space in pixels between the legend icon and the text next to it.
  11205. Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the
  11206. name of the graph) will use this space by default.
  11207. */
  11208. void QCPLegend::setIconTextPadding(int padding)
  11209. {
  11210. mIconTextPadding = padding;
  11211. }
  11212. /*!
  11213. Sets the pen used to draw a border around each legend icon. Legend items that draw an
  11214. icon (e.g. a visual representation of the graph) will use this pen by default.
  11215. If no border is wanted, set this to \a Qt::NoPen.
  11216. */
  11217. void QCPLegend::setIconBorderPen(const QPen& pen)
  11218. {
  11219. mIconBorderPen = pen;
  11220. }
  11221. /*!
  11222. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot
  11223. surface. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.)
  11224. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  11225. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  11226. directly.
  11227. \see SelectablePart, setSelectedParts
  11228. */
  11229. void QCPLegend::setSelectableParts(const SelectableParts& selectable)
  11230. {
  11231. if (mSelectableParts != selectable) {
  11232. mSelectableParts = selectable;
  11233. emit selectableChanged(mSelectableParts);
  11234. }
  11235. }
  11236. /*!
  11237. Sets the selected state of the respective legend parts described by \ref SelectablePart. When a
  11238. part is selected, it uses a different pen/font and brush. If some legend items are selected and \a
  11239. selected doesn't contain \ref spItems, those items become deselected.
  11240. The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions
  11241. contains iSelectLegend. You only need to call this function when you wish to change the selection
  11242. state manually.
  11243. This function can change the selection state of a part even when \ref setSelectableParts was set
  11244. to a value that actually excludes the part.
  11245. emits the \ref selectionChanged signal when \a selected is different from the previous selection
  11246. state.
  11247. Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set
  11248. before, because there's no way to specify which exact items to newly select. Do this by calling
  11249. \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select.
  11250. \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen,
  11251. setSelectedIconBorderPen, setSelectedBrush, setSelectedFont
  11252. */
  11253. void QCPLegend::setSelectedParts(const SelectableParts& selected)
  11254. {
  11255. SelectableParts newSelected = selected;
  11256. mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed
  11257. if (mSelectedParts != newSelected) {
  11258. if (!mSelectedParts.testFlag(spItems)
  11259. && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that)
  11260. {
  11261. qDebug() << Q_FUNC_INFO
  11262. << "spItems flag can not be set, it can only be unset with this function";
  11263. newSelected &= ~spItems;
  11264. }
  11265. if (mSelectedParts.testFlag(spItems)
  11266. && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection
  11267. {
  11268. for (int i = 0; i < itemCount(); ++i) {
  11269. if (item(i))
  11270. item(i)->setSelected(false);
  11271. }
  11272. }
  11273. mSelectedParts = newSelected;
  11274. emit selectionChanged(mSelectedParts);
  11275. }
  11276. }
  11277. /*!
  11278. When the legend box is selected, this pen is used to draw the border instead of the normal pen
  11279. set via \ref setBorderPen.
  11280. \see setSelectedParts, setSelectableParts, setSelectedBrush
  11281. */
  11282. void QCPLegend::setSelectedBorderPen(const QPen& pen)
  11283. {
  11284. mSelectedBorderPen = pen;
  11285. }
  11286. /*!
  11287. Sets the pen legend items will use to draw their icon borders, when they are selected.
  11288. \see setSelectedParts, setSelectableParts, setSelectedFont
  11289. */
  11290. void QCPLegend::setSelectedIconBorderPen(const QPen& pen)
  11291. {
  11292. mSelectedIconBorderPen = pen;
  11293. }
  11294. /*!
  11295. When the legend box is selected, this brush is used to draw the legend background instead of the
  11296. normal brush set via \ref setBrush.
  11297. \see setSelectedParts, setSelectableParts, setSelectedBorderPen
  11298. */
  11299. void QCPLegend::setSelectedBrush(const QBrush& brush)
  11300. {
  11301. mSelectedBrush = brush;
  11302. }
  11303. /*!
  11304. Sets the default font that is used by legend items when they are selected.
  11305. This function will also set \a font on all already existing legend items.
  11306. \see setFont, QCPAbstractLegendItem::setSelectedFont
  11307. */
  11308. void QCPLegend::setSelectedFont(const QFont& font)
  11309. {
  11310. mSelectedFont = font;
  11311. for (int i = 0; i < itemCount(); ++i) {
  11312. if (item(i))
  11313. item(i)->setSelectedFont(font);
  11314. }
  11315. }
  11316. /*!
  11317. Sets the default text color that is used by legend items when they are selected.
  11318. This function will also set \a color on all already existing legend items.
  11319. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor
  11320. */
  11321. void QCPLegend::setSelectedTextColor(const QColor& color)
  11322. {
  11323. mSelectedTextColor = color;
  11324. for (int i = 0; i < itemCount(); ++i) {
  11325. if (item(i))
  11326. item(i)->setSelectedTextColor(color);
  11327. }
  11328. }
  11329. /*!
  11330. Returns the item with index \a i.
  11331. \see itemCount
  11332. */
  11333. QCPAbstractLegendItem* QCPLegend::item(int index) const
  11334. {
  11335. return qobject_cast<QCPAbstractLegendItem*>(elementAt(index));
  11336. }
  11337. /*!
  11338. Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  11339. If such an item isn't in the legend, returns 0.
  11340. \see hasItemWithPlottable
  11341. */
  11342. QCPPlottableLegendItem* QCPLegend::itemWithPlottable(const QCPAbstractPlottable* plottable) const
  11343. {
  11344. for (int i = 0; i < itemCount(); ++i) {
  11345. if (QCPPlottableLegendItem* pli = qobject_cast<QCPPlottableLegendItem*>(item(i))) {
  11346. if (pli->plottable() == plottable)
  11347. return pli;
  11348. }
  11349. }
  11350. return 0;
  11351. }
  11352. /*!
  11353. Returns the number of items currently in the legend.
  11354. \see item
  11355. */
  11356. int QCPLegend::itemCount() const
  11357. {
  11358. return elementCount();
  11359. }
  11360. /*!
  11361. Returns whether the legend contains \a itm.
  11362. */
  11363. bool QCPLegend::hasItem(QCPAbstractLegendItem* item) const
  11364. {
  11365. for (int i = 0; i < itemCount(); ++i) {
  11366. if (item == this->item(i))
  11367. return true;
  11368. }
  11369. return false;
  11370. }
  11371. /*!
  11372. Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable
  11373. (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns false.
  11374. \see itemWithPlottable
  11375. */
  11376. bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable* plottable) const
  11377. {
  11378. return itemWithPlottable(plottable);
  11379. }
  11380. /*!
  11381. Adds \a item to the legend, if it's not present already.
  11382. Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly
  11383. added.
  11384. The legend takes ownership of the item.
  11385. */
  11386. bool QCPLegend::addItem(QCPAbstractLegendItem* item)
  11387. {
  11388. if (!hasItem(item)) {
  11389. return addElement(rowCount(), 0, item);
  11390. } else
  11391. return false;
  11392. }
  11393. /*!
  11394. Removes the item with index \a index from the legend.
  11395. Returns true, if successful.
  11396. \see itemCount, clearItems
  11397. */
  11398. bool QCPLegend::removeItem(int index)
  11399. {
  11400. if (QCPAbstractLegendItem* ali = item(index)) {
  11401. bool success = remove(ali);
  11402. simplify();
  11403. return success;
  11404. } else
  11405. return false;
  11406. }
  11407. /*! \overload
  11408. Removes \a item from the legend.
  11409. Returns true, if successful.
  11410. \see clearItems
  11411. */
  11412. bool QCPLegend::removeItem(QCPAbstractLegendItem* item)
  11413. {
  11414. bool success = remove(item);
  11415. simplify();
  11416. return success;
  11417. }
  11418. /*!
  11419. Removes all items from the legend.
  11420. */
  11421. void QCPLegend::clearItems()
  11422. {
  11423. for (int i = itemCount() - 1; i >= 0; --i)
  11424. removeItem(i);
  11425. }
  11426. /*!
  11427. Returns the legend items that are currently selected. If no items are selected,
  11428. the list is empty.
  11429. \see QCPAbstractLegendItem::setSelected, setSelectable
  11430. */
  11431. QList<QCPAbstractLegendItem*> QCPLegend::selectedItems() const
  11432. {
  11433. QList<QCPAbstractLegendItem*> result;
  11434. for (int i = 0; i < itemCount(); ++i) {
  11435. if (QCPAbstractLegendItem* ali = item(i)) {
  11436. if (ali->selected())
  11437. result.append(ali);
  11438. }
  11439. }
  11440. return result;
  11441. }
  11442. /*! \internal
  11443. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  11444. before drawing main legend elements.
  11445. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  11446. This function takes into account the local setting of the antialiasing flag as well as the
  11447. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  11448. QCustomPlot::setNotAntialiasedElements.
  11449. \see setAntialiased
  11450. */
  11451. void QCPLegend::applyDefaultAntialiasingHint(QCPPainter* painter) const
  11452. {
  11453. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend);
  11454. }
  11455. /*! \internal
  11456. Returns the pen used to paint the border of the legend, taking into account the selection state
  11457. of the legend box.
  11458. */
  11459. QPen QCPLegend::getBorderPen() const
  11460. {
  11461. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen;
  11462. }
  11463. /*! \internal
  11464. Returns the brush used to paint the background of the legend, taking into account the selection
  11465. state of the legend box.
  11466. */
  11467. QBrush QCPLegend::getBrush() const
  11468. {
  11469. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush;
  11470. }
  11471. /*! \internal
  11472. Draws the legend box with the provided \a painter. The individual legend items are layerables
  11473. themselves, thus are drawn independently.
  11474. */
  11475. void QCPLegend::draw(QCPPainter* painter)
  11476. {
  11477. // draw background rect:
  11478. painter->setBrush(getBrush());
  11479. painter->setPen(getBorderPen());
  11480. painter->drawRect(mOuterRect);
  11481. }
  11482. /* inherits documentation from base class */
  11483. double QCPLegend::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  11484. {
  11485. if (!mParentPlot)
  11486. return -1;
  11487. if (onlySelectable && !mSelectableParts.testFlag(spLegendBox))
  11488. return -1;
  11489. if (mOuterRect.contains(pos.toPoint())) {
  11490. if (details)
  11491. details->setValue(spLegendBox);
  11492. return mParentPlot->selectionTolerance() * 0.99;
  11493. }
  11494. return -1;
  11495. }
  11496. /* inherits documentation from base class */
  11497. void QCPLegend::selectEvent(QMouseEvent* event, bool additive, const QVariant& details,
  11498. bool* selectionStateChanged)
  11499. {
  11500. Q_UNUSED(event)
  11501. mSelectedParts = selectedParts(); // in case item selection has changed
  11502. if (details.value<SelectablePart>() == spLegendBox && mSelectableParts.testFlag(spLegendBox)) {
  11503. SelectableParts selBefore = mSelectedParts;
  11504. setSelectedParts(
  11505. additive ? mSelectedParts ^ spLegendBox
  11506. : mSelectedParts
  11507. | spLegendBox); // no need to unset spItems in !additive case, because
  11508. // they will be deselected by QCustomPlot (they're normal
  11509. // QCPLayerables with own deselectEvent)
  11510. if (selectionStateChanged)
  11511. *selectionStateChanged = mSelectedParts != selBefore;
  11512. }
  11513. }
  11514. /* inherits documentation from base class */
  11515. void QCPLegend::deselectEvent(bool* selectionStateChanged)
  11516. {
  11517. mSelectedParts = selectedParts(); // in case item selection has changed
  11518. if (mSelectableParts.testFlag(spLegendBox)) {
  11519. SelectableParts selBefore = mSelectedParts;
  11520. setSelectedParts(selectedParts() & ~spLegendBox);
  11521. if (selectionStateChanged)
  11522. *selectionStateChanged = mSelectedParts != selBefore;
  11523. }
  11524. }
  11525. /* inherits documentation from base class */
  11526. QCP::Interaction QCPLegend::selectionCategory() const
  11527. {
  11528. return QCP::iSelectLegend;
  11529. }
  11530. /* inherits documentation from base class */
  11531. QCP::Interaction QCPAbstractLegendItem::selectionCategory() const
  11532. {
  11533. return QCP::iSelectLegend;
  11534. }
  11535. /* inherits documentation from base class */
  11536. void QCPLegend::parentPlotInitialized(QCustomPlot* parentPlot)
  11537. {
  11538. Q_UNUSED(parentPlot)
  11539. }
  11540. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11541. //////////////////// QCPPlotTitle
  11542. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11543. /*! \class QCPPlotTitle
  11544. \brief A layout element displaying a plot title text
  11545. The text may be specified with \ref setText, theformatting can be controlled with \ref setFont
  11546. and \ref setTextColor.
  11547. A plot title can be added as follows:
  11548. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpplottitle-creation
  11549. Since a plot title is a common requirement, QCustomPlot offers specialized selection signals for
  11550. easy interaction with QCPPlotTitle. If a layout element of type QCPPlotTitle is clicked, the
  11551. signal \ref QCustomPlot::titleClick is emitted. A double click emits the \ref
  11552. QCustomPlot::titleDoubleClick signal.
  11553. */
  11554. /* start documentation of signals */
  11555. /*! \fn void QCPPlotTitle::selectionChanged(bool selected)
  11556. This signal is emitted when the selection state has changed to \a selected, either by user
  11557. interaction or by a direct call to \ref setSelected.
  11558. \see setSelected, setSelectable
  11559. */
  11560. /* end documentation of signals */
  11561. /*!
  11562. Creates a new QCPPlotTitle instance and sets default values. The initial text is empty (\ref
  11563. setText).
  11564. To set the title text in the constructor, rather use \ref QCPPlotTitle(QCustomPlot *parentPlot,
  11565. const QString &text).
  11566. */
  11567. QCPPlotTitle::QCPPlotTitle(QCustomPlot* parentPlot)
  11568. : QCPLayoutElement(parentPlot)
  11569. , mFont(QFont(QLatin1String("sans serif"), 13 * 1.5, QFont::Bold))
  11570. , mTextColor(Qt::black)
  11571. , mSelectedFont(QFont(QLatin1String("sans serif"), 13 * 1.6, QFont::Bold))
  11572. , mSelectedTextColor(Qt::blue)
  11573. , mSelectable(false)
  11574. , mSelected(false)
  11575. {
  11576. if (parentPlot) {
  11577. setLayer(parentPlot->currentLayer());
  11578. mFont =
  11579. QFont(parentPlot->font().family(), parentPlot->font().pointSize() * 1.5, QFont::Bold);
  11580. mSelectedFont =
  11581. QFont(parentPlot->font().family(), parentPlot->font().pointSize() * 1.6, QFont::Bold);
  11582. }
  11583. setMargins(QMargins(5, 5, 5, 0));
  11584. }
  11585. /*! \overload
  11586. Creates a new QCPPlotTitle instance and sets default values. The initial text is set to \a text.
  11587. */
  11588. QCPPlotTitle::QCPPlotTitle(QCustomPlot* parentPlot, const QString& text)
  11589. : QCPLayoutElement(parentPlot)
  11590. , mText(text)
  11591. , mFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize() * 1.5, QFont::Bold))
  11592. , mTextColor(Qt::black)
  11593. , mSelectedFont(
  11594. QFont(parentPlot->font().family(), parentPlot->font().pointSize() * 1.6, QFont::Bold))
  11595. , mSelectedTextColor(Qt::blue)
  11596. , mSelectable(false)
  11597. , mSelected(false)
  11598. {
  11599. setLayer(QLatin1String("axes"));
  11600. setMargins(QMargins(5, 5, 5, 0));
  11601. }
  11602. /*!
  11603. Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of
  11604. "\n".
  11605. \see setFont, setTextColor
  11606. */
  11607. void QCPPlotTitle::setText(const QString& text)
  11608. {
  11609. mText = text;
  11610. }
  11611. /*!
  11612. Sets the \a font of the title text.
  11613. \see setTextColor, setSelectedFont
  11614. */
  11615. void QCPPlotTitle::setFont(const QFont& font)
  11616. {
  11617. mFont = font;
  11618. }
  11619. /*!
  11620. Sets the \a color of the title text.
  11621. \see setFont, setSelectedTextColor
  11622. */
  11623. void QCPPlotTitle::setTextColor(const QColor& color)
  11624. {
  11625. mTextColor = color;
  11626. }
  11627. /*!
  11628. Sets the \a font of the title text that will be used if the plot title is selected (\ref
  11629. setSelected).
  11630. \see setFont
  11631. */
  11632. void QCPPlotTitle::setSelectedFont(const QFont& font)
  11633. {
  11634. mSelectedFont = font;
  11635. }
  11636. /*!
  11637. Sets the \a color of the title text that will be used if the plot title is selected (\ref
  11638. setSelected).
  11639. \see setTextColor
  11640. */
  11641. void QCPPlotTitle::setSelectedTextColor(const QColor& color)
  11642. {
  11643. mSelectedTextColor = color;
  11644. }
  11645. /*!
  11646. Sets whether the user may select this plot title to \a selectable.
  11647. Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed
  11648. programmatically via \ref setSelected.
  11649. */
  11650. void QCPPlotTitle::setSelectable(bool selectable)
  11651. {
  11652. if (mSelectable != selectable) {
  11653. mSelectable = selectable;
  11654. emit selectableChanged(mSelectable);
  11655. }
  11656. }
  11657. /*!
  11658. Sets the selection state of this plot title to \a selected. If the selection has changed, \ref
  11659. selectionChanged is emitted.
  11660. Note that this function can change the selection state independently of the current \ref
  11661. setSelectable state.
  11662. */
  11663. void QCPPlotTitle::setSelected(bool selected)
  11664. {
  11665. if (mSelected != selected) {
  11666. mSelected = selected;
  11667. emit selectionChanged(mSelected);
  11668. }
  11669. }
  11670. /* inherits documentation from base class */
  11671. void QCPPlotTitle::applyDefaultAntialiasingHint(QCPPainter* painter) const
  11672. {
  11673. applyAntialiasingHint(painter, mAntialiased, QCP::aeNone);
  11674. }
  11675. /* inherits documentation from base class */
  11676. void QCPPlotTitle::draw(QCPPainter* painter)
  11677. {
  11678. painter->setFont(mainFont());
  11679. painter->setPen(QPen(mainTextColor()));
  11680. painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect);
  11681. }
  11682. /* inherits documentation from base class */
  11683. QSize QCPPlotTitle::minimumSizeHint() const
  11684. {
  11685. QFontMetrics metrics(mFont);
  11686. QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size();
  11687. result.rwidth() += mMargins.left() + mMargins.right();
  11688. result.rheight() += mMargins.top() + mMargins.bottom();
  11689. return result;
  11690. }
  11691. /* inherits documentation from base class */
  11692. QSize QCPPlotTitle::maximumSizeHint() const
  11693. {
  11694. QFontMetrics metrics(mFont);
  11695. QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size();
  11696. result.rheight() += mMargins.top() + mMargins.bottom();
  11697. result.setWidth(QWIDGETSIZE_MAX);
  11698. return result;
  11699. }
  11700. /* inherits documentation from base class */
  11701. void QCPPlotTitle::selectEvent(QMouseEvent* event, bool additive, const QVariant& details,
  11702. bool* selectionStateChanged)
  11703. {
  11704. Q_UNUSED(event)
  11705. Q_UNUSED(details)
  11706. if (mSelectable) {
  11707. bool selBefore = mSelected;
  11708. setSelected(additive ? !mSelected : true);
  11709. if (selectionStateChanged)
  11710. *selectionStateChanged = mSelected != selBefore;
  11711. }
  11712. }
  11713. /* inherits documentation from base class */
  11714. void QCPPlotTitle::deselectEvent(bool* selectionStateChanged)
  11715. {
  11716. if (mSelectable) {
  11717. bool selBefore = mSelected;
  11718. setSelected(false);
  11719. if (selectionStateChanged)
  11720. *selectionStateChanged = mSelected != selBefore;
  11721. }
  11722. }
  11723. /* inherits documentation from base class */
  11724. double QCPPlotTitle::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  11725. {
  11726. Q_UNUSED(details)
  11727. if (onlySelectable && !mSelectable)
  11728. return -1;
  11729. if (mTextBoundingRect.contains(pos.toPoint()))
  11730. return mParentPlot->selectionTolerance() * 0.99;
  11731. else
  11732. return -1;
  11733. }
  11734. /*! \internal
  11735. Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to
  11736. <tt>true</tt>, else mFont is returned.
  11737. */
  11738. QFont QCPPlotTitle::mainFont() const
  11739. {
  11740. return mSelected ? mSelectedFont : mFont;
  11741. }
  11742. /*! \internal
  11743. Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to
  11744. <tt>true</tt>, else mTextColor is returned.
  11745. */
  11746. QColor QCPPlotTitle::mainTextColor() const
  11747. {
  11748. return mSelected ? mSelectedTextColor : mTextColor;
  11749. }
  11750. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11751. //////////////////// QCPColorScale
  11752. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11753. /*! \class QCPColorScale
  11754. \brief A color scale for use with color coding data such as QCPColorMap
  11755. This layout element can be placed on the plot to correlate a color gradient with data values. It
  11756. is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps".
  11757. \image html QCPColorScale.png
  11758. The color scale can be either horizontal or vertical, as shown in the image above. The
  11759. orientation and the side where the numbers appear is controlled with \ref setType.
  11760. Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are
  11761. connected, they share their gradient, data range and data scale type (\ref setGradient, \ref
  11762. setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color
  11763. scale, to make them all synchronize these properties.
  11764. To have finer control over the number display and axis behaviour, you can directly access the
  11765. \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if
  11766. you want to change the number of automatically generated ticks, call
  11767. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-autotickcount
  11768. Placing a color scale next to the main axis rect works like with any other layout element:
  11769. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation
  11770. In this case we have placed it to the right of the default axis rect, so it wasn't necessary to
  11771. call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color
  11772. scale can be set with \ref setLabel.
  11773. For optimum appearance (like in the image above), it may be desirable to line up the axis rect and
  11774. the borders of the color scale. Use a \ref QCPMarginGroup to achieve this:
  11775. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup
  11776. Color scales are initialized with a non-zero minimum top and bottom margin (\ref
  11777. setMinimumMargins), because vertical color scales are most common and the minimum top/bottom
  11778. margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a
  11779. horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop,
  11780. you might want to also change the minimum margins accordingly, e.g.
  11781. <tt>setMinimumMargins(QMargins(6, 0, 6, 0))</tt>.
  11782. */
  11783. /* start documentation of inline functions */
  11784. /*! \fn QCPAxis *QCPColorScale::axis() const
  11785. Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the
  11786. appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its
  11787. interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref
  11788. setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref
  11789. QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on
  11790. the QCPColorScale or on its QCPAxis.
  11791. If the type of the color scale is changed with \ref setType, the axis returned by this method
  11792. will change, too, to either the left, right, bottom or top axis, depending on which type was set.
  11793. */
  11794. /* end documentation of signals */
  11795. /* start documentation of signals */
  11796. /*! \fn void QCPColorScale::dataRangeChanged(QCPRange newRange);
  11797. This signal is emitted when the data range changes.
  11798. \see setDataRange
  11799. */
  11800. /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  11801. This signal is emitted when the data scale type changes.
  11802. \see setDataScaleType
  11803. */
  11804. /*! \fn void QCPColorScale::gradientChanged(QCPColorGradient newGradient);
  11805. This signal is emitted when the gradient changes.
  11806. \see setGradient
  11807. */
  11808. /* end documentation of signals */
  11809. /*!
  11810. Constructs a new QCPColorScale.
  11811. */
  11812. QCPColorScale::QCPColorScale(QCustomPlot* parentPlot)
  11813. : QCPLayoutElement(parentPlot)
  11814. , mType(QCPAxis::atTop)
  11815. , // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks
  11816. // it's already atRight
  11817. mDataScaleType(QCPAxis::stLinear)
  11818. , mBarWidth(20)
  11819. , mAxisRect(new QCPColorScaleAxisRectPrivate(this))
  11820. {
  11821. setMinimumMargins(
  11822. QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and
  11823. // top (important if no margin group is used)
  11824. setType(QCPAxis::atRight);
  11825. setDataRange(QCPRange(0, 6));
  11826. }
  11827. QCPColorScale::~QCPColorScale()
  11828. {
  11829. delete mAxisRect;
  11830. }
  11831. /* undocumented getter */
  11832. QString QCPColorScale::label() const
  11833. {
  11834. if (!mColorAxis) {
  11835. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  11836. return QString();
  11837. }
  11838. return mColorAxis.data()->label();
  11839. }
  11840. /* undocumented getter */
  11841. bool QCPColorScale::rangeDrag() const
  11842. {
  11843. if (!mAxisRect) {
  11844. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11845. return false;
  11846. }
  11847. return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType))
  11848. && mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))
  11849. && mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation()
  11850. == QCPAxis::orientation(mType);
  11851. }
  11852. /* undocumented getter */
  11853. bool QCPColorScale::rangeZoom() const
  11854. {
  11855. if (!mAxisRect) {
  11856. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11857. return false;
  11858. }
  11859. return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType))
  11860. && mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))
  11861. && mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation()
  11862. == QCPAxis::orientation(mType);
  11863. }
  11864. /*!
  11865. Sets at which side of the color scale the axis is placed, and thus also its orientation.
  11866. Note that after setting \a type to a different value, the axis returned by \ref axis() will
  11867. be a different one. The new axis will adopt the following properties from the previous axis: The
  11868. range, scale type, log base and label.
  11869. */
  11870. void QCPColorScale::setType(QCPAxis::AxisType type)
  11871. {
  11872. if (!mAxisRect) {
  11873. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11874. return;
  11875. }
  11876. if (mType != type) {
  11877. mType = type;
  11878. QCPRange rangeTransfer(0, 6);
  11879. double logBaseTransfer = 10;
  11880. QString labelTransfer;
  11881. // revert some settings on old axis:
  11882. if (mColorAxis) {
  11883. rangeTransfer = mColorAxis.data()->range();
  11884. labelTransfer = mColorAxis.data()->label();
  11885. logBaseTransfer = mColorAxis.data()->scaleLogBase();
  11886. mColorAxis.data()->setLabel(QString());
  11887. disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this,
  11888. SLOT(setDataRange(QCPRange)));
  11889. disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this,
  11890. SLOT(setDataScaleType(QCPAxis::ScaleType)));
  11891. }
  11892. QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>()
  11893. << QCPAxis::atLeft << QCPAxis::atRight
  11894. << QCPAxis::atBottom << QCPAxis::atTop;
  11895. foreach (QCPAxis::AxisType atype, allAxisTypes) {
  11896. mAxisRect.data()->axis(atype)->setTicks(atype == mType);
  11897. mAxisRect.data()->axis(atype)->setTickLabels(atype == mType);
  11898. }
  11899. // set new mColorAxis pointer:
  11900. mColorAxis = mAxisRect.data()->axis(mType);
  11901. // transfer settings to new axis:
  11902. mColorAxis.data()->setRange(
  11903. rangeTransfer); // transfer range of old axis to new one (necessary if axis changes from
  11904. // vertical to horizontal or vice versa)
  11905. mColorAxis.data()->setLabel(labelTransfer);
  11906. mColorAxis.data()->setScaleLogBase(
  11907. logBaseTransfer); // scaleType is synchronized among axes in realtime via signals
  11908. // (connected in QCPColorScale ctor), so we only need to take care of
  11909. // log base here
  11910. connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this,
  11911. SLOT(setDataRange(QCPRange)));
  11912. connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this,
  11913. SLOT(setDataScaleType(QCPAxis::ScaleType)));
  11914. mAxisRect.data()->setRangeDragAxes(
  11915. QCPAxis::orientation(mType) == Qt::Horizontal ? mColorAxis.data() : 0,
  11916. QCPAxis::orientation(mType) == Qt::Vertical ? mColorAxis.data() : 0);
  11917. }
  11918. }
  11919. /*!
  11920. Sets the range spanned by the color gradient and that is shown by the axis in the color scale.
  11921. It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is
  11922. also equivalent to directly accessing the \ref axis and setting its range with \ref
  11923. QCPAxis::setRange.
  11924. \see setDataScaleType, setGradient, rescaleDataRange
  11925. */
  11926. void QCPColorScale::setDataRange(const QCPRange& dataRange)
  11927. {
  11928. if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) {
  11929. mDataRange = dataRange;
  11930. if (mColorAxis)
  11931. mColorAxis.data()->setRange(mDataRange);
  11932. emit dataRangeChanged(mDataRange);
  11933. }
  11934. }
  11935. /*!
  11936. Sets the scale type of the color scale, i.e. whether values are linearly associated with colors
  11937. or logarithmically.
  11938. It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It
  11939. is also equivalent to directly accessing the \ref axis and setting its scale type with \ref
  11940. QCPAxis::setScaleType.
  11941. \see setDataRange, setGradient
  11942. */
  11943. void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType)
  11944. {
  11945. if (mDataScaleType != scaleType) {
  11946. mDataScaleType = scaleType;
  11947. if (mColorAxis)
  11948. mColorAxis.data()->setScaleType(mDataScaleType);
  11949. if (mDataScaleType == QCPAxis::stLogarithmic)
  11950. setDataRange(mDataRange.sanitizedForLogScale());
  11951. emit dataScaleTypeChanged(mDataScaleType);
  11952. }
  11953. }
  11954. /*!
  11955. Sets the color gradient that will be used to represent data values.
  11956. It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps.
  11957. \see setDataRange, setDataScaleType
  11958. */
  11959. void QCPColorScale::setGradient(const QCPColorGradient& gradient)
  11960. {
  11961. if (mGradient != gradient) {
  11962. mGradient = gradient;
  11963. if (mAxisRect)
  11964. mAxisRect.data()->mGradientImageInvalidated = true;
  11965. emit gradientChanged(mGradient);
  11966. }
  11967. }
  11968. /*!
  11969. Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on
  11970. the internal \ref axis.
  11971. */
  11972. void QCPColorScale::setLabel(const QString& str)
  11973. {
  11974. if (!mColorAxis) {
  11975. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  11976. return;
  11977. }
  11978. mColorAxis.data()->setLabel(str);
  11979. }
  11980. /*!
  11981. Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed
  11982. will have.
  11983. */
  11984. void QCPColorScale::setBarWidth(int width)
  11985. {
  11986. mBarWidth = width;
  11987. }
  11988. /*!
  11989. Sets whether the user can drag the data range (\ref setDataRange).
  11990. Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref
  11991. QCustomPlot::setInteractions) to allow range dragging.
  11992. */
  11993. void QCPColorScale::setRangeDrag(bool enabled)
  11994. {
  11995. if (!mAxisRect) {
  11996. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  11997. return;
  11998. }
  11999. if (enabled)
  12000. mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType));
  12001. else
  12002. mAxisRect.data()->setRangeDrag(0);
  12003. }
  12004. /*!
  12005. Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel.
  12006. Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref
  12007. QCustomPlot::setInteractions) to allow range dragging.
  12008. */
  12009. void QCPColorScale::setRangeZoom(bool enabled)
  12010. {
  12011. if (!mAxisRect) {
  12012. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  12013. return;
  12014. }
  12015. if (enabled)
  12016. mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType));
  12017. else
  12018. mAxisRect.data()->setRangeZoom(0);
  12019. }
  12020. /*!
  12021. Returns a list of all the color maps associated with this color scale.
  12022. */
  12023. QList<QCPColorMap*> QCPColorScale::colorMaps() const
  12024. {
  12025. QList<QCPColorMap*> result;
  12026. for (int i = 0; i < mParentPlot->plottableCount(); ++i) {
  12027. if (QCPColorMap* cm = qobject_cast<QCPColorMap*>(mParentPlot->plottable(i)))
  12028. if (cm->colorScale() == this)
  12029. result.append(cm);
  12030. }
  12031. return result;
  12032. }
  12033. /*!
  12034. Changes the data range such that all color maps associated with this color scale are fully mapped
  12035. to the gradient in the data dimension.
  12036. \see setDataRange
  12037. */
  12038. void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps)
  12039. {
  12040. QList<QCPColorMap*> maps = colorMaps();
  12041. QCPRange newRange;
  12042. bool haveRange = false;
  12043. int sign = 0; // TODO: should change this to QCPAbstractPlottable::SignDomain later (currently
  12044. // is protected, maybe move to QCP namespace)
  12045. if (mDataScaleType == QCPAxis::stLogarithmic)
  12046. sign = (mDataRange.upper < 0 ? -1 : 1);
  12047. for (int i = 0; i < maps.size(); ++i) {
  12048. if (!maps.at(i)->realVisibility() && onlyVisibleMaps)
  12049. continue;
  12050. QCPRange mapRange;
  12051. if (maps.at(i)->colorScale() == this) {
  12052. bool currentFoundRange = true;
  12053. mapRange = maps.at(i)->data()->dataBounds();
  12054. if (sign == 1) {
  12055. if (mapRange.lower <= 0 && mapRange.upper > 0)
  12056. mapRange.lower = mapRange.upper * 1e-3;
  12057. else if (mapRange.lower <= 0 && mapRange.upper <= 0)
  12058. currentFoundRange = false;
  12059. } else if (sign == -1) {
  12060. if (mapRange.upper >= 0 && mapRange.lower < 0)
  12061. mapRange.upper = mapRange.lower * 1e-3;
  12062. else if (mapRange.upper >= 0 && mapRange.lower >= 0)
  12063. currentFoundRange = false;
  12064. }
  12065. if (currentFoundRange) {
  12066. if (!haveRange)
  12067. newRange = mapRange;
  12068. else
  12069. newRange.expand(mapRange);
  12070. haveRange = true;
  12071. }
  12072. }
  12073. }
  12074. if (haveRange) {
  12075. if (!QCPRange::validRange(
  12076. newRange)) // likely due to range being zero (plottable has only constant data in
  12077. // this dimension), shift current range to at least center the data
  12078. {
  12079. double center = (newRange.lower + newRange.upper)
  12080. * 0.5; // upper and lower should be equal anyway, but just to make sure,
  12081. // incase validRange returned false for other reason
  12082. if (mDataScaleType == QCPAxis::stLinear) {
  12083. newRange.lower = center - mDataRange.size() / 2.0;
  12084. newRange.upper = center + mDataRange.size() / 2.0;
  12085. } else // mScaleType == stLogarithmic
  12086. {
  12087. newRange.lower = center / qSqrt(mDataRange.upper / mDataRange.lower);
  12088. newRange.upper = center * qSqrt(mDataRange.upper / mDataRange.lower);
  12089. }
  12090. }
  12091. setDataRange(newRange);
  12092. }
  12093. }
  12094. /* inherits documentation from base class */
  12095. void QCPColorScale::update(UpdatePhase phase)
  12096. {
  12097. QCPLayoutElement::update(phase);
  12098. if (!mAxisRect) {
  12099. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  12100. return;
  12101. }
  12102. mAxisRect.data()->update(phase);
  12103. switch (phase) {
  12104. case upMargins: {
  12105. if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) {
  12106. setMaximumSize(QWIDGETSIZE_MAX, mBarWidth + mAxisRect.data()->margins().top()
  12107. + mAxisRect.data()->margins().bottom()
  12108. + margins().top() + margins().bottom());
  12109. setMinimumSize(0, mBarWidth + mAxisRect.data()->margins().top()
  12110. + mAxisRect.data()->margins().bottom() + margins().top()
  12111. + margins().bottom());
  12112. } else {
  12113. setMaximumSize(mBarWidth + mAxisRect.data()->margins().left()
  12114. + mAxisRect.data()->margins().right() + margins().left()
  12115. + margins().right(),
  12116. QWIDGETSIZE_MAX);
  12117. setMinimumSize(mBarWidth + mAxisRect.data()->margins().left()
  12118. + mAxisRect.data()->margins().right() + margins().left()
  12119. + margins().right(),
  12120. 0);
  12121. }
  12122. break;
  12123. }
  12124. case upLayout: {
  12125. mAxisRect.data()->setOuterRect(rect());
  12126. break;
  12127. }
  12128. default:
  12129. break;
  12130. }
  12131. }
  12132. /* inherits documentation from base class */
  12133. void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter* painter) const
  12134. {
  12135. painter->setAntialiasing(false);
  12136. }
  12137. /* inherits documentation from base class */
  12138. void QCPColorScale::mousePressEvent(QMouseEvent* event)
  12139. {
  12140. if (!mAxisRect) {
  12141. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  12142. return;
  12143. }
  12144. mAxisRect.data()->mousePressEvent(event);
  12145. }
  12146. /* inherits documentation from base class */
  12147. void QCPColorScale::mouseMoveEvent(QMouseEvent* event)
  12148. {
  12149. if (!mAxisRect) {
  12150. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  12151. return;
  12152. }
  12153. mAxisRect.data()->mouseMoveEvent(event);
  12154. }
  12155. /* inherits documentation from base class */
  12156. void QCPColorScale::mouseReleaseEvent(QMouseEvent* event)
  12157. {
  12158. if (!mAxisRect) {
  12159. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  12160. return;
  12161. }
  12162. mAxisRect.data()->mouseReleaseEvent(event);
  12163. }
  12164. /* inherits documentation from base class */
  12165. void QCPColorScale::wheelEvent(QWheelEvent* event)
  12166. {
  12167. if (!mAxisRect) {
  12168. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  12169. return;
  12170. }
  12171. mAxisRect.data()->wheelEvent(event);
  12172. }
  12173. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12174. //////////////////// QCPColorScaleAxisRectPrivate
  12175. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12176. /*! \class QCPColorScaleAxisRectPrivate
  12177. \internal
  12178. \brief An axis rect subclass for use in a QCPColorScale
  12179. This is a private class and not part of the public QCustomPlot interface.
  12180. It provides the axis rect functionality for the QCPColorScale class.
  12181. */
  12182. /*!
  12183. Creates a new instance, as a child of \a parentColorScale.
  12184. */
  12185. QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale* parentColorScale)
  12186. : QCPAxisRect(parentColorScale->parentPlot(), true)
  12187. , mParentColorScale(parentColorScale)
  12188. , mGradientImageInvalidated(true)
  12189. {
  12190. setParentLayerable(parentColorScale);
  12191. setMinimumMargins(QMargins(0, 0, 0, 0));
  12192. QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>()
  12193. << QCPAxis::atBottom << QCPAxis::atTop
  12194. << QCPAxis::atLeft << QCPAxis::atRight;
  12195. foreach (QCPAxis::AxisType type, allAxisTypes) {
  12196. axis(type)->setVisible(true);
  12197. axis(type)->grid()->setVisible(false);
  12198. axis(type)->setPadding(0);
  12199. connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this,
  12200. SLOT(axisSelectionChanged(QCPAxis::SelectableParts)));
  12201. connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this,
  12202. SLOT(axisSelectableChanged(QCPAxis::SelectableParts)));
  12203. }
  12204. connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight),
  12205. SLOT(setRange(QCPRange)));
  12206. connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft),
  12207. SLOT(setRange(QCPRange)));
  12208. connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop),
  12209. SLOT(setRange(QCPRange)));
  12210. connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom),
  12211. SLOT(setRange(QCPRange)));
  12212. connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)),
  12213. axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType)));
  12214. connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)),
  12215. axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType)));
  12216. connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)),
  12217. axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType)));
  12218. connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)),
  12219. axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType)));
  12220. // make layer transfers of color scale transfer to axis rect and axes
  12221. // the axes must be set after axis rect, such that they appear above color gradient drawn by
  12222. // axis rect:
  12223. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*)));
  12224. foreach (QCPAxis::AxisType type, allAxisTypes)
  12225. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type),
  12226. SLOT(setLayer(QCPLayer*)));
  12227. }
  12228. /*! \internal
  12229. Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws
  12230. it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation.
  12231. */
  12232. void QCPColorScaleAxisRectPrivate::draw(QCPPainter* painter)
  12233. {
  12234. if (mGradientImageInvalidated)
  12235. updateGradientImage();
  12236. bool mirrorHorz = false;
  12237. bool mirrorVert = false;
  12238. if (mParentColorScale->mColorAxis) {
  12239. mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed()
  12240. && (mParentColorScale->type() == QCPAxis::atBottom
  12241. || mParentColorScale->type() == QCPAxis::atTop);
  12242. mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed()
  12243. && (mParentColorScale->type() == QCPAxis::atLeft
  12244. || mParentColorScale->type() == QCPAxis::atRight);
  12245. }
  12246. painter->drawImage(rect().adjusted(0, -1, 0, -1),
  12247. mGradientImage.mirrored(mirrorHorz, mirrorVert));
  12248. QCPAxisRect::draw(painter);
  12249. }
  12250. /*! \internal
  12251. Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to
  12252. generate a gradient image. This gradient image will be used in the \ref draw method.
  12253. */
  12254. void QCPColorScaleAxisRectPrivate::updateGradientImage()
  12255. {
  12256. if (rect().isEmpty())
  12257. return;
  12258. int n = mParentColorScale->mGradient.levelCount();
  12259. int w, h;
  12260. QVector<double> data(n);
  12261. for (int i = 0; i < n; ++i)
  12262. data[i] = i;
  12263. if (mParentColorScale->mType == QCPAxis::atBottom
  12264. || mParentColorScale->mType == QCPAxis::atTop) {
  12265. w = n;
  12266. h = rect().height();
  12267. mGradientImage = QImage(w, h, QImage::Format_RGB32);
  12268. QVector<QRgb*> pixels;
  12269. for (int y = 0; y < h; ++y)
  12270. pixels.append(reinterpret_cast<QRgb*>(mGradientImage.scanLine(y)));
  12271. mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n - 1), pixels.first(),
  12272. n);
  12273. for (int y = 1; y < h; ++y)
  12274. memcpy(pixels.at(y), pixels.first(), n * sizeof(QRgb));
  12275. } else {
  12276. w = rect().width();
  12277. h = n;
  12278. mGradientImage = QImage(w, h, QImage::Format_RGB32);
  12279. for (int y = 0; y < h; ++y) {
  12280. QRgb* pixels = reinterpret_cast<QRgb*>(mGradientImage.scanLine(y));
  12281. const QRgb lineColor =
  12282. mParentColorScale->mGradient.color(data[h - 1 - y], QCPRange(0, n - 1));
  12283. for (int x = 0; x < w; ++x)
  12284. pixels[x] = lineColor;
  12285. }
  12286. }
  12287. mGradientImageInvalidated = false;
  12288. }
  12289. /*! \internal
  12290. This slot is connected to the selectionChanged signals of the four axes in the constructor. It
  12291. synchronizes the selection state of the axes.
  12292. */
  12293. void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts)
  12294. {
  12295. // axis bases of four axes shall always (de-)selected synchronously:
  12296. QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>()
  12297. << QCPAxis::atBottom << QCPAxis::atTop
  12298. << QCPAxis::atLeft << QCPAxis::atRight;
  12299. foreach (QCPAxis::AxisType type, allAxisTypes) {
  12300. if (QCPAxis* senderAxis = qobject_cast<QCPAxis*>(sender()))
  12301. if (senderAxis->axisType() == type)
  12302. continue;
  12303. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) {
  12304. if (selectedParts.testFlag(QCPAxis::spAxis))
  12305. axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis);
  12306. else
  12307. axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis);
  12308. }
  12309. }
  12310. }
  12311. /*! \internal
  12312. This slot is connected to the selectableChanged signals of the four axes in the constructor. It
  12313. synchronizes the selectability of the axes.
  12314. */
  12315. void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts)
  12316. {
  12317. // synchronize axis base selectability:
  12318. QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>()
  12319. << QCPAxis::atBottom << QCPAxis::atTop
  12320. << QCPAxis::atLeft << QCPAxis::atRight;
  12321. foreach (QCPAxis::AxisType type, allAxisTypes) {
  12322. if (QCPAxis* senderAxis = qobject_cast<QCPAxis*>(sender()))
  12323. if (senderAxis->axisType() == type)
  12324. continue;
  12325. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) {
  12326. if (selectableParts.testFlag(QCPAxis::spAxis))
  12327. axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis);
  12328. else
  12329. axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis);
  12330. }
  12331. }
  12332. }
  12333. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12334. //////////////////// QCPData
  12335. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12336. /*! \class QCPData
  12337. \brief Holds the data of one single data point for QCPGraph.
  12338. The container for storing multiple data points is \ref QCPDataMap.
  12339. The stored data is:
  12340. \li \a key: coordinate on the key axis of this data point
  12341. \li \a value: coordinate on the value axis of this data point
  12342. \li \a keyErrorMinus: negative error in the key dimension (for error bars)
  12343. \li \a keyErrorPlus: positive error in the key dimension (for error bars)
  12344. \li \a valueErrorMinus: negative error in the value dimension (for error bars)
  12345. \li \a valueErrorPlus: positive error in the value dimension (for error bars)
  12346. \see QCPDataMap
  12347. */
  12348. /*!
  12349. Constructs a data point with key, value and all errors set to zero.
  12350. */
  12351. QCPData::QCPData()
  12352. : key(0), value(0), keyErrorPlus(0), keyErrorMinus(0), valueErrorPlus(0), valueErrorMinus(0)
  12353. {}
  12354. /*!
  12355. Constructs a data point with the specified \a key and \a value. All errors are set to zero.
  12356. */
  12357. QCPData::QCPData(double key, double value)
  12358. : key(key)
  12359. , value(value)
  12360. , keyErrorPlus(0)
  12361. , keyErrorMinus(0)
  12362. , valueErrorPlus(0)
  12363. , valueErrorMinus(0)
  12364. {}
  12365. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12366. //////////////////// QCPGraph
  12367. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12368. /*! \class QCPGraph
  12369. \brief A plottable representing a graph in a plot.
  12370. \image html QCPGraph.png
  12371. Usually you create new graphs by calling QCustomPlot::addGraph. The resulting instance can be
  12372. accessed via QCustomPlot::graph.
  12373. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  12374. also access and modify the graph's data via the \ref data method, which returns a pointer to the
  12375. internal \ref QCPDataMap.
  12376. Graphs are used to display single-valued data. Single-valued means that there should only be one
  12377. data point per unique key coordinate. In other words, the graph can't have \a loops. If you do
  12378. want to plot non-single-valued curves, rather use the QCPCurve plottable.
  12379. Gaps in the graph line can be created by adding data points with NaN as value
  12380. (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data
  12381. points that shall be separated.
  12382. \section appearance Changing the appearance
  12383. The appearance of the graph is mainly determined by the line style, scatter style, brush and pen
  12384. of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen).
  12385. \subsection filling Filling under or between graphs
  12386. QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to
  12387. the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill,
  12388. just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent.
  12389. By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill
  12390. between this graph and another one, call \ref setChannelFillGraph with the other graph as
  12391. parameter.
  12392. \see QCustomPlot::addGraph, QCustomPlot::graph
  12393. */
  12394. /* start of documentation of inline functions */
  12395. /*! \fn QCPDataMap *QCPGraph::data() const
  12396. Returns a pointer to the internal data storage of type \ref QCPDataMap. You may use it to
  12397. directly manipulate the data, which may be more convenient and faster than using the regular \ref
  12398. setData or \ref addData methods, in certain situations.
  12399. */
  12400. /* end of documentation of inline functions */
  12401. /*!
  12402. Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  12403. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  12404. the same orientation. If either of these restrictions is violated, a corresponding message is
  12405. printed to the debug output (qDebug), the construction is not aborted, though.
  12406. The constructed QCPGraph can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
  12407. then takes ownership of the graph.
  12408. To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph
  12409. function.
  12410. */
  12411. QCPGraph::QCPGraph(QCPAxis* keyAxis, QCPAxis* valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis)
  12412. {
  12413. mData = new QCPDataMap;
  12414. setPen(QPen(Qt::blue, 0));
  12415. setErrorPen(QPen(Qt::black));
  12416. setBrush(Qt::NoBrush);
  12417. setSelectedPen(QPen(QColor(80, 80, 255), 2.5));
  12418. setSelectedBrush(Qt::NoBrush);
  12419. setLineStyle(lsLine);
  12420. setErrorType(etNone);
  12421. setErrorBarSize(6);
  12422. setErrorBarSkipSymbol(true);
  12423. setChannelFillGraph(0);
  12424. setAdaptiveSampling(true);
  12425. }
  12426. QCPGraph::~QCPGraph()
  12427. {
  12428. delete mData;
  12429. }
  12430. /*!
  12431. Replaces the current data with the provided \a data.
  12432. If \a copy is set to true, data points in \a data will only be copied. if false, the graph
  12433. takes ownership of the passed data and replaces the internal data pointer with it. This is
  12434. significantly faster than copying for large datasets.
  12435. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12436. returns a pointer to the internal \ref QCPDataMap.
  12437. */
  12438. void QCPGraph::setData(QCPDataMap* data, bool copy)
  12439. {
  12440. if (mData == data) {
  12441. qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable"
  12442. << reinterpret_cast<quintptr>(data);
  12443. return;
  12444. }
  12445. if (copy) {
  12446. *mData = *data;
  12447. } else {
  12448. delete mData;
  12449. mData = data;
  12450. }
  12451. }
  12452. /*! \overload
  12453. Replaces the current data with the provided points in \a key and \a value pairs. The provided
  12454. vectors should have equal length. Else, the number of added points will be the size of the
  12455. smallest vector.
  12456. */
  12457. void QCPGraph::setData(const QVector<double>& key, const QVector<double>& value)
  12458. {
  12459. mData->clear();
  12460. int n = key.size();
  12461. n = qMin(n, value.size());
  12462. QCPData newData;
  12463. for (int i = 0; i < n; ++i) {
  12464. newData.key = key[i];
  12465. newData.value = value[i];
  12466. mData->insertMulti(newData.key, newData);
  12467. }
  12468. }
  12469. /*!
  12470. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12471. symmetrical value error of the data points are set to the values in \a valueError.
  12472. For error bars to show appropriately, see \ref setErrorType.
  12473. The provided vectors should have equal length. Else, the number of added points will be the size
  12474. of the smallest vector.
  12475. For asymmetrical errors (plus different from minus), see the overloaded version of this function.
  12476. */
  12477. void QCPGraph::setDataValueError(const QVector<double>& key, const QVector<double>& value,
  12478. const QVector<double>& valueError)
  12479. {
  12480. mData->clear();
  12481. int n = key.size();
  12482. n = qMin(n, value.size());
  12483. n = qMin(n, valueError.size());
  12484. QCPData newData;
  12485. for (int i = 0; i < n; ++i) {
  12486. newData.key = key[i];
  12487. newData.value = value[i];
  12488. newData.valueErrorMinus = valueError[i];
  12489. newData.valueErrorPlus = valueError[i];
  12490. mData->insertMulti(key[i], newData);
  12491. }
  12492. }
  12493. /*!
  12494. \overload
  12495. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12496. negative value error of the data points are set to the values in \a valueErrorMinus, the positive
  12497. value error to \a valueErrorPlus.
  12498. For error bars to show appropriately, see \ref setErrorType.
  12499. The provided vectors should have equal length. Else, the number of added points will be the size
  12500. of the smallest vector.
  12501. */
  12502. void QCPGraph::setDataValueError(const QVector<double>& key, const QVector<double>& value,
  12503. const QVector<double>& valueErrorMinus,
  12504. const QVector<double>& valueErrorPlus)
  12505. {
  12506. mData->clear();
  12507. int n = key.size();
  12508. n = qMin(n, value.size());
  12509. n = qMin(n, valueErrorMinus.size());
  12510. n = qMin(n, valueErrorPlus.size());
  12511. QCPData newData;
  12512. for (int i = 0; i < n; ++i) {
  12513. newData.key = key[i];
  12514. newData.value = value[i];
  12515. newData.valueErrorMinus = valueErrorMinus[i];
  12516. newData.valueErrorPlus = valueErrorPlus[i];
  12517. mData->insertMulti(key[i], newData);
  12518. }
  12519. }
  12520. /*!
  12521. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12522. symmetrical key error of the data points are set to the values in \a keyError.
  12523. For error bars to show appropriately, see \ref setErrorType.
  12524. The provided vectors should have equal length. Else, the number of added points will be the size
  12525. of the smallest vector.
  12526. For asymmetrical errors (plus different from minus), see the overloaded version of this function.
  12527. */
  12528. void QCPGraph::setDataKeyError(const QVector<double>& key, const QVector<double>& value,
  12529. const QVector<double>& keyError)
  12530. {
  12531. mData->clear();
  12532. int n = key.size();
  12533. n = qMin(n, value.size());
  12534. n = qMin(n, keyError.size());
  12535. QCPData newData;
  12536. for (int i = 0; i < n; ++i) {
  12537. newData.key = key[i];
  12538. newData.value = value[i];
  12539. newData.keyErrorMinus = keyError[i];
  12540. newData.keyErrorPlus = keyError[i];
  12541. mData->insertMulti(key[i], newData);
  12542. }
  12543. }
  12544. /*!
  12545. \overload
  12546. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12547. negative key error of the data points are set to the values in \a keyErrorMinus, the positive
  12548. key error to \a keyErrorPlus.
  12549. For error bars to show appropriately, see \ref setErrorType.
  12550. The provided vectors should have equal length. Else, the number of added points will be the size
  12551. of the smallest vector.
  12552. */
  12553. void QCPGraph::setDataKeyError(const QVector<double>& key, const QVector<double>& value,
  12554. const QVector<double>& keyErrorMinus,
  12555. const QVector<double>& keyErrorPlus)
  12556. {
  12557. mData->clear();
  12558. int n = key.size();
  12559. n = qMin(n, value.size());
  12560. n = qMin(n, keyErrorMinus.size());
  12561. n = qMin(n, keyErrorPlus.size());
  12562. QCPData newData;
  12563. for (int i = 0; i < n; ++i) {
  12564. newData.key = key[i];
  12565. newData.value = value[i];
  12566. newData.keyErrorMinus = keyErrorMinus[i];
  12567. newData.keyErrorPlus = keyErrorPlus[i];
  12568. mData->insertMulti(key[i], newData);
  12569. }
  12570. }
  12571. /*!
  12572. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12573. symmetrical key and value errors of the data points are set to the values in \a keyError and \a
  12574. valueError. For error bars to show appropriately, see \ref setErrorType. The provided vectors
  12575. should have equal length. Else, the number of added points will be the size of the smallest
  12576. vector.
  12577. For asymmetrical errors (plus different from minus), see the overloaded version of this function.
  12578. */
  12579. void QCPGraph::setDataBothError(const QVector<double>& key, const QVector<double>& value,
  12580. const QVector<double>& keyError, const QVector<double>& valueError)
  12581. {
  12582. mData->clear();
  12583. int n = key.size();
  12584. n = qMin(n, value.size());
  12585. n = qMin(n, valueError.size());
  12586. n = qMin(n, keyError.size());
  12587. QCPData newData;
  12588. for (int i = 0; i < n; ++i) {
  12589. newData.key = key[i];
  12590. newData.value = value[i];
  12591. newData.keyErrorMinus = keyError[i];
  12592. newData.keyErrorPlus = keyError[i];
  12593. newData.valueErrorMinus = valueError[i];
  12594. newData.valueErrorPlus = valueError[i];
  12595. mData->insertMulti(key[i], newData);
  12596. }
  12597. }
  12598. /*!
  12599. \overload
  12600. Replaces the current data with the provided points in \a key and \a value pairs. Additionally the
  12601. negative key and value errors of the data points are set to the values in \a keyErrorMinus and \a
  12602. valueErrorMinus. The positive key and value errors are set to the values in \a keyErrorPlus \a
  12603. valueErrorPlus. For error bars to show appropriately, see \ref setErrorType. The provided vectors
  12604. should have equal length. Else, the number of added points will be the size of the smallest
  12605. vector.
  12606. */
  12607. void QCPGraph::setDataBothError(const QVector<double>& key, const QVector<double>& value,
  12608. const QVector<double>& keyErrorMinus,
  12609. const QVector<double>& keyErrorPlus,
  12610. const QVector<double>& valueErrorMinus,
  12611. const QVector<double>& valueErrorPlus)
  12612. {
  12613. mData->clear();
  12614. int n = key.size();
  12615. n = qMin(n, value.size());
  12616. n = qMin(n, valueErrorMinus.size());
  12617. n = qMin(n, valueErrorPlus.size());
  12618. n = qMin(n, keyErrorMinus.size());
  12619. n = qMin(n, keyErrorPlus.size());
  12620. QCPData newData;
  12621. for (int i = 0; i < n; ++i) {
  12622. newData.key = key[i];
  12623. newData.value = value[i];
  12624. newData.keyErrorMinus = keyErrorMinus[i];
  12625. newData.keyErrorPlus = keyErrorPlus[i];
  12626. newData.valueErrorMinus = valueErrorMinus[i];
  12627. newData.valueErrorPlus = valueErrorPlus[i];
  12628. mData->insertMulti(key[i], newData);
  12629. }
  12630. }
  12631. /*!
  12632. Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
  12633. \ref lsNone and \ref setScatterStyle to the desired scatter style.
  12634. \see setScatterStyle
  12635. */
  12636. void QCPGraph::setLineStyle(LineStyle ls)
  12637. {
  12638. mLineStyle = ls;
  12639. }
  12640. /*!
  12641. Sets the visual appearance of single data points in the plot. If set to \ref
  12642. QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only-plots with appropriate
  12643. line style).
  12644. \see QCPScatterStyle, setLineStyle
  12645. */
  12646. void QCPGraph::setScatterStyle(const QCPScatterStyle& style)
  12647. {
  12648. mScatterStyle = style;
  12649. }
  12650. /*!
  12651. Sets which kind of error bars (Key Error, Value Error or both) should be drawn on each data
  12652. point. If you set \a errorType to something other than \ref etNone, make sure to actually pass
  12653. error data via the specific setData functions along with the data points (e.g. \ref
  12654. setDataValueError, \ref setDataKeyError, \ref setDataBothError).
  12655. \see ErrorType
  12656. */
  12657. void QCPGraph::setErrorType(ErrorType errorType)
  12658. {
  12659. mErrorType = errorType;
  12660. }
  12661. /*!
  12662. Sets the pen with which the error bars will be drawn.
  12663. \see setErrorBarSize, setErrorType
  12664. */
  12665. void QCPGraph::setErrorPen(const QPen& pen)
  12666. {
  12667. mErrorPen = pen;
  12668. }
  12669. /*!
  12670. Sets the width of the handles at both ends of an error bar in pixels.
  12671. */
  12672. void QCPGraph::setErrorBarSize(double size)
  12673. {
  12674. mErrorBarSize = size;
  12675. }
  12676. /*!
  12677. If \a enabled is set to true, the error bar will not be drawn as a solid line under the scatter
  12678. symbol but leave some free space around the symbol.
  12679. This feature uses the current scatter size (\ref QCPScatterStyle::setSize) to determine the size
  12680. of the area to leave blank. So when drawing Pixmaps as scatter points (\ref
  12681. QCPScatterStyle::ssPixmap), the scatter size must be set manually to a value corresponding to the
  12682. size of the Pixmap, if the error bars should leave gaps to its boundaries.
  12683. \ref setErrorType, setErrorBarSize, setScatterStyle
  12684. */
  12685. void QCPGraph::setErrorBarSkipSymbol(bool enabled)
  12686. {
  12687. mErrorBarSkipSymbol = enabled;
  12688. }
  12689. /*!
  12690. Sets the target graph for filling the area between this graph and \a targetGraph with the current
  12691. brush (\ref setBrush).
  12692. When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To
  12693. disable any filling, set the brush to Qt::NoBrush.
  12694. \see setBrush
  12695. */
  12696. void QCPGraph::setChannelFillGraph(QCPGraph* targetGraph)
  12697. {
  12698. // prevent setting channel target to this graph itself:
  12699. if (targetGraph == this) {
  12700. qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself";
  12701. mChannelFillGraph = 0;
  12702. return;
  12703. }
  12704. // prevent setting channel target to a graph not in the plot:
  12705. if (targetGraph && targetGraph->mParentPlot != mParentPlot) {
  12706. qDebug() << Q_FUNC_INFO << "targetGraph not in same plot";
  12707. mChannelFillGraph = 0;
  12708. return;
  12709. }
  12710. mChannelFillGraph = targetGraph;
  12711. }
  12712. /*!
  12713. Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive
  12714. sampling technique can drastically improve the replot performance for graphs with a larger number
  12715. of points (e.g. above 10,000), without notably changing the appearance of the graph.
  12716. By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive
  12717. sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no
  12718. disadvantage in almost all cases.
  12719. \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive
  12720. sampling"
  12721. As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are
  12722. reproduced reliably, as well as the overall shape of the data set. The replot time reduces
  12723. dramatically though. This allows QCustomPlot to display large amounts of data in realtime.
  12724. \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with
  12725. adaptive sampling"
  12726. Care must be taken when using high-density scatter plots in combination with adaptive sampling.
  12727. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still
  12728. gives a significant reduction of replot times, but not quite as much as for line plots. This is
  12729. because scatter plots inherently need more data points to be preserved in order to still resemble
  12730. the original, non-adaptive-sampling plot. As shown above, the results still aren't quite
  12731. identical, as banding occurs for the outer data points. This is in fact intentional, such that
  12732. the boundaries of the data cloud stay visible to the viewer. How strong the banding appears,
  12733. depends on the point density, i.e. the number of points in the plot.
  12734. For some situations with scatter plots it might thus be desirable to manually turn adaptive
  12735. sampling off. For example, when saving the plot to disk. This can be achieved by setting \a
  12736. enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled
  12737. back to true afterwards.
  12738. */
  12739. void QCPGraph::setAdaptiveSampling(bool enabled)
  12740. {
  12741. mAdaptiveSampling = enabled;
  12742. }
  12743. /*!
  12744. Adds the provided data points in \a dataMap to the current data.
  12745. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12746. returns a pointer to the internal \ref QCPDataMap.
  12747. \see removeData
  12748. */
  12749. void QCPGraph::addData(const QCPDataMap& dataMap)
  12750. {
  12751. mData->unite(dataMap);
  12752. }
  12753. /*! \overload
  12754. Adds the provided single data point in \a data to the current data.
  12755. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12756. returns a pointer to the internal \ref QCPDataMap.
  12757. \see removeData
  12758. */
  12759. void QCPGraph::addData(const QCPData& data)
  12760. {
  12761. mData->insertMulti(data.key, data);
  12762. }
  12763. /*! \overload
  12764. Adds the provided single data point as \a key and \a value pair to the current data.
  12765. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12766. returns a pointer to the internal \ref QCPDataMap.
  12767. \see removeData
  12768. */
  12769. void QCPGraph::addData(double key, double value)
  12770. {
  12771. QCPData newData;
  12772. newData.key = key;
  12773. newData.value = value;
  12774. mData->insertMulti(newData.key, newData);
  12775. }
  12776. /*! \overload
  12777. Adds the provided data points as \a key and \a value pairs to the current data.
  12778. Alternatively, you can also access and modify the graph's data via the \ref data method, which
  12779. returns a pointer to the internal \ref QCPDataMap.
  12780. \see removeData
  12781. */
  12782. void QCPGraph::addData(const QVector<double>& keys, const QVector<double>& values)
  12783. {
  12784. int n = qMin(keys.size(), values.size());
  12785. QCPData newData;
  12786. for (int i = 0; i < n; ++i) {
  12787. newData.key = keys[i];
  12788. newData.value = values[i];
  12789. mData->insertMulti(newData.key, newData);
  12790. }
  12791. }
  12792. /*!
  12793. Removes all data points with keys smaller than \a key.
  12794. \see addData, clearData
  12795. */
  12796. void QCPGraph::removeDataBefore(double key)
  12797. {
  12798. QCPDataMap::iterator it = mData->begin();
  12799. while (it != mData->end() && it.key() < key)
  12800. it = mData->erase(it);
  12801. }
  12802. /*!
  12803. Removes all data points with keys greater than \a key.
  12804. \see addData, clearData
  12805. */
  12806. void QCPGraph::removeDataAfter(double key)
  12807. {
  12808. if (mData->isEmpty())
  12809. return;
  12810. QCPDataMap::iterator it = mData->upperBound(key);
  12811. while (it != mData->end())
  12812. it = mData->erase(it);
  12813. }
  12814. /*!
  12815. Removes all data points with keys between \a fromKey and \a toKey.
  12816. if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove
  12817. a single data point with known key, use \ref removeData(double key).
  12818. \see addData, clearData
  12819. */
  12820. void QCPGraph::removeData(double fromKey, double toKey)
  12821. {
  12822. if (fromKey >= toKey || mData->isEmpty())
  12823. return;
  12824. QCPDataMap::iterator it = mData->upperBound(fromKey);
  12825. QCPDataMap::iterator itEnd = mData->upperBound(toKey);
  12826. while (it != itEnd)
  12827. it = mData->erase(it);
  12828. }
  12829. /*! \overload
  12830. Removes a single data point at \a key. If the position is not known with absolute precision,
  12831. consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval
  12832. around the suspected position, depeding on the precision with which the key is known.
  12833. \see addData, clearData
  12834. */
  12835. void QCPGraph::removeData(double key)
  12836. {
  12837. mData->remove(key);
  12838. }
  12839. /*!
  12840. Removes all data points.
  12841. \see removeData, removeDataAfter, removeDataBefore
  12842. */
  12843. void QCPGraph::clearData()
  12844. {
  12845. mData->clear();
  12846. }
  12847. /* inherits documentation from base class */
  12848. double QCPGraph::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  12849. {
  12850. Q_UNUSED(details)
  12851. if ((onlySelectable && !mSelectable) || mData->isEmpty())
  12852. return -1;
  12853. if (!mKeyAxis || !mValueAxis) {
  12854. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  12855. return -1;
  12856. }
  12857. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  12858. return pointDistance(pos);
  12859. else
  12860. return -1;
  12861. }
  12862. /*! \overload
  12863. Allows to define whether error bars are taken into consideration when determining the new axis
  12864. range.
  12865. \see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  12866. */
  12867. void QCPGraph::rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const
  12868. {
  12869. rescaleKeyAxis(onlyEnlarge, includeErrorBars);
  12870. rescaleValueAxis(onlyEnlarge, includeErrorBars);
  12871. }
  12872. /*! \overload
  12873. Allows to define whether error bars (of kind \ref QCPGraph::etKey) are taken into consideration
  12874. when determining the new axis range.
  12875. \see rescaleAxes, QCPAbstractPlottable::rescaleKeyAxis
  12876. */
  12877. void QCPGraph::rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const
  12878. {
  12879. // this code is a copy of QCPAbstractPlottable::rescaleKeyAxis with the only change
  12880. // that getKeyRange is passed the includeErrorBars value.
  12881. if (mData->isEmpty())
  12882. return;
  12883. QCPAxis* keyAxis = mKeyAxis.data();
  12884. if (!keyAxis) {
  12885. qDebug() << Q_FUNC_INFO << "invalid key axis";
  12886. return;
  12887. }
  12888. SignDomain signDomain = sdBoth;
  12889. if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
  12890. signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive);
  12891. bool foundRange;
  12892. QCPRange newRange = getKeyRange(foundRange, signDomain, includeErrorBars);
  12893. if (foundRange) {
  12894. if (onlyEnlarge) {
  12895. if (keyAxis->range().lower < newRange.lower)
  12896. newRange.lower = keyAxis->range().lower;
  12897. if (keyAxis->range().upper > newRange.upper)
  12898. newRange.upper = keyAxis->range().upper;
  12899. }
  12900. keyAxis->setRange(newRange);
  12901. }
  12902. }
  12903. /*! \overload
  12904. Allows to define whether error bars (of kind \ref QCPGraph::etValue) are taken into consideration
  12905. when determining the new axis range.
  12906. \see rescaleAxes, QCPAbstractPlottable::rescaleValueAxis
  12907. */
  12908. void QCPGraph::rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const
  12909. {
  12910. // this code is a copy of QCPAbstractPlottable::rescaleValueAxis with the only change
  12911. // is that getValueRange is passed the includeErrorBars value.
  12912. if (mData->isEmpty())
  12913. return;
  12914. QCPAxis* valueAxis = mValueAxis.data();
  12915. if (!valueAxis) {
  12916. qDebug() << Q_FUNC_INFO << "invalid value axis";
  12917. return;
  12918. }
  12919. SignDomain signDomain = sdBoth;
  12920. if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
  12921. signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive);
  12922. bool foundRange;
  12923. QCPRange newRange = getValueRange(foundRange, signDomain, includeErrorBars);
  12924. if (foundRange) {
  12925. if (onlyEnlarge) {
  12926. if (valueAxis->range().lower < newRange.lower)
  12927. newRange.lower = valueAxis->range().lower;
  12928. if (valueAxis->range().upper > newRange.upper)
  12929. newRange.upper = valueAxis->range().upper;
  12930. }
  12931. valueAxis->setRange(newRange);
  12932. }
  12933. }
  12934. /* inherits documentation from base class */
  12935. void QCPGraph::draw(QCPPainter* painter)
  12936. {
  12937. if (!mKeyAxis || !mValueAxis) {
  12938. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  12939. return;
  12940. }
  12941. if (mKeyAxis.data()->range().size() <= 0 || mData->isEmpty())
  12942. return;
  12943. if (mLineStyle == lsNone && mScatterStyle.isNone())
  12944. return;
  12945. // allocate line and (if necessary) point vectors:
  12946. QVector<QPointF>* lineData = new QVector<QPointF>;
  12947. QVector<QCPData>* scatterData = 0;
  12948. if (!mScatterStyle.isNone())
  12949. scatterData = new QVector<QCPData>;
  12950. // fill vectors with data appropriate to plot style:
  12951. getPlotData(lineData, scatterData);
  12952. // check data validity if flag set:
  12953. #ifdef QCUSTOMPLOT_CHECK_DATA
  12954. QCPDataMap::const_iterator it;
  12955. for (it = mData->constBegin(); it != mData->constEnd(); ++it) {
  12956. if (QCP::isInvalidData(it.value().key, it.value().value)
  12957. || QCP::isInvalidData(it.value().keyErrorPlus, it.value().keyErrorMinus)
  12958. || QCP::isInvalidData(it.value().valueErrorPlus, it.value().valueErrorPlus))
  12959. qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid."
  12960. << "Plottable name:" << name();
  12961. }
  12962. #endif
  12963. // draw fill of graph:
  12964. if (mLineStyle != lsNone)
  12965. drawFill(painter, lineData);
  12966. // draw line:
  12967. if (mLineStyle == lsImpulse)
  12968. drawImpulsePlot(painter, lineData);
  12969. else if (mLineStyle != lsNone)
  12970. drawLinePlot(painter, lineData); // also step plots can be drawn as a line plot
  12971. // draw scatters:
  12972. if (scatterData)
  12973. drawScatterPlot(painter, scatterData);
  12974. // free allocated line and point vectors:
  12975. delete lineData;
  12976. if (scatterData)
  12977. delete scatterData;
  12978. }
  12979. /* inherits documentation from base class */
  12980. void QCPGraph::drawLegendIcon(QCPPainter* painter, const QRectF& rect) const
  12981. {
  12982. // draw fill:
  12983. if (mBrush.style() != Qt::NoBrush) {
  12984. applyFillAntialiasingHint(painter);
  12985. painter->fillRect(QRectF(rect.left(), rect.top() + rect.height() / 2.0, rect.width(),
  12986. rect.height() / 3.0),
  12987. mBrush);
  12988. }
  12989. // draw line vertically centered:
  12990. if (mLineStyle != lsNone) {
  12991. applyDefaultAntialiasingHint(painter);
  12992. painter->setPen(mPen);
  12993. painter->drawLine(QLineF(
  12994. rect.left(), rect.top() + rect.height() / 2.0, rect.right() + 5,
  12995. rect.top()
  12996. + rect.height()
  12997. / 2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
  12998. }
  12999. // draw scatter symbol:
  13000. if (!mScatterStyle.isNone()) {
  13001. applyScattersAntialiasingHint(painter);
  13002. // scale scatter pixmap if it's too large to fit in legend icon rect:
  13003. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap
  13004. && (mScatterStyle.pixmap().size().width() > rect.width()
  13005. || mScatterStyle.pixmap().size().height() > rect.height())) {
  13006. QCPScatterStyle scaledStyle(mScatterStyle);
  13007. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(
  13008. rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  13009. scaledStyle.applyTo(painter, mPen);
  13010. scaledStyle.drawShape(painter, QRectF(rect).center());
  13011. } else {
  13012. mScatterStyle.applyTo(painter, mPen);
  13013. mScatterStyle.drawShape(painter, QRectF(rect).center());
  13014. }
  13015. }
  13016. }
  13017. /*! \internal
  13018. This function branches out to the line style specific "get(...)PlotData" functions, according to
  13019. the line style of the graph.
  13020. \a lineData will be filled with raw points that will be drawn with the according draw functions,
  13021. e.g. \ref drawLinePlot and \ref drawImpulsePlot. These aren't necessarily the original data
  13022. points, since for step plots for example, additional points are needed for drawing lines that
  13023. make up steps. If the line style of the graph is \ref lsNone, the \a lineData vector will be left
  13024. untouched.
  13025. \a scatterData will be filled with the original data points so \ref drawScatterPlot can draw the
  13026. scatter symbols accordingly. If no scatters need to be drawn, i.e. the scatter style's shape is
  13027. \ref QCPScatterStyle::ssNone, pass 0 as \a scatterData, and this step will be skipped.
  13028. \see getScatterPlotData, getLinePlotData, getStepLeftPlotData, getStepRightPlotData,
  13029. getStepCenterPlotData, getImpulsePlotData
  13030. */
  13031. void QCPGraph::getPlotData(QVector<QPointF>* lineData, QVector<QCPData>* scatterData) const
  13032. {
  13033. switch (mLineStyle) {
  13034. case lsNone:
  13035. getScatterPlotData(scatterData);
  13036. break;
  13037. case lsLine:
  13038. getLinePlotData(lineData, scatterData);
  13039. break;
  13040. case lsStepLeft:
  13041. getStepLeftPlotData(lineData, scatterData);
  13042. break;
  13043. case lsStepRight:
  13044. getStepRightPlotData(lineData, scatterData);
  13045. break;
  13046. case lsStepCenter:
  13047. getStepCenterPlotData(lineData, scatterData);
  13048. break;
  13049. case lsImpulse:
  13050. getImpulsePlotData(lineData, scatterData);
  13051. break;
  13052. }
  13053. }
  13054. /*! \internal
  13055. If line style is \ref lsNone and the scatter style's shape is not \ref QCPScatterStyle::ssNone,
  13056. this function serves at providing the visible data points in \a scatterData, so the \ref
  13057. drawScatterPlot function can draw the scatter points accordingly.
  13058. If line style is not \ref lsNone, this function is not called and the data for the scatter points
  13059. are (if needed) calculated inside the corresponding other "get(...)PlotData" functions.
  13060. \see drawScatterPlot
  13061. */
  13062. void QCPGraph::getScatterPlotData(QVector<QCPData>* scatterData) const
  13063. {
  13064. getPreparedData(0, scatterData);
  13065. }
  13066. /*! \internal
  13067. Places the raw data points needed for a normal linearly connected graph in \a linePixelData.
  13068. As for all plot data retrieval functions, \a scatterData just contains all unaltered data
  13069. (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter
  13070. points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  13071. scatterData, and the function will skip filling the vector.
  13072. \see drawLinePlot
  13073. */
  13074. void QCPGraph::getLinePlotData(QVector<QPointF>* linePixelData, QVector<QCPData>* scatterData) const
  13075. {
  13076. QCPAxis* keyAxis = mKeyAxis.data();
  13077. QCPAxis* valueAxis = mValueAxis.data();
  13078. if (!keyAxis || !valueAxis) {
  13079. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  13080. return;
  13081. }
  13082. if (!linePixelData) {
  13083. qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData";
  13084. return;
  13085. }
  13086. QVector<QCPData> lineData;
  13087. getPreparedData(&lineData, scatterData);
  13088. linePixelData->reserve(lineData.size() + 2); // added 2 to reserve memory for lower/upper fill
  13089. // base points that might be needed for fill
  13090. linePixelData->resize(lineData.size());
  13091. // transform lineData points to pixels:
  13092. if (keyAxis->orientation() == Qt::Vertical) {
  13093. for (int i = 0; i < lineData.size(); ++i) {
  13094. (*linePixelData)[i].setX(valueAxis->coordToPixel(lineData.at(i).value));
  13095. (*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key));
  13096. }
  13097. } else // key axis is horizontal
  13098. {
  13099. for (int i = 0; i < lineData.size(); ++i) {
  13100. (*linePixelData)[i].setX(keyAxis->coordToPixel(lineData.at(i).key));
  13101. (*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value));
  13102. }
  13103. }
  13104. }
  13105. /*!
  13106. \internal
  13107. Places the raw data points needed for a step plot with left oriented steps in \a lineData.
  13108. As for all plot data retrieval functions, \a scatterData just contains all unaltered data
  13109. (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter
  13110. points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  13111. scatterData, and the function will skip filling the vector.
  13112. \see drawLinePlot
  13113. */
  13114. void QCPGraph::getStepLeftPlotData(QVector<QPointF>* linePixelData,
  13115. QVector<QCPData>* scatterData) const
  13116. {
  13117. QCPAxis* keyAxis = mKeyAxis.data();
  13118. QCPAxis* valueAxis = mValueAxis.data();
  13119. if (!keyAxis || !valueAxis) {
  13120. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  13121. return;
  13122. }
  13123. if (!linePixelData) {
  13124. qDebug() << Q_FUNC_INFO << "null pointer passed as lineData";
  13125. return;
  13126. }
  13127. QVector<QCPData> lineData;
  13128. getPreparedData(&lineData, scatterData);
  13129. linePixelData->reserve(lineData.size() * 2
  13130. + 2); // added 2 to reserve memory for lower/upper fill base points that
  13131. // might be needed for fill
  13132. linePixelData->resize(lineData.size() * 2);
  13133. // calculate steps from lineData and transform to pixel coordinates:
  13134. if (keyAxis->orientation() == Qt::Vertical) {
  13135. double lastValue = valueAxis->coordToPixel(lineData.first().value);
  13136. double key;
  13137. for (int i = 0; i < lineData.size(); ++i) {
  13138. key = keyAxis->coordToPixel(lineData.at(i).key);
  13139. (*linePixelData)[i * 2 + 0].setX(lastValue);
  13140. (*linePixelData)[i * 2 + 0].setY(key);
  13141. lastValue = valueAxis->coordToPixel(lineData.at(i).value);
  13142. (*linePixelData)[i * 2 + 1].setX(lastValue);
  13143. (*linePixelData)[i * 2 + 1].setY(key);
  13144. }
  13145. } else // key axis is horizontal
  13146. {
  13147. double lastValue = valueAxis->coordToPixel(lineData.first().value);
  13148. double key;
  13149. for (int i = 0; i < lineData.size(); ++i) {
  13150. key = keyAxis->coordToPixel(lineData.at(i).key);
  13151. (*linePixelData)[i * 2 + 0].setX(key);
  13152. (*linePixelData)[i * 2 + 0].setY(lastValue);
  13153. lastValue = valueAxis->coordToPixel(lineData.at(i).value);
  13154. (*linePixelData)[i * 2 + 1].setX(key);
  13155. (*linePixelData)[i * 2 + 1].setY(lastValue);
  13156. }
  13157. }
  13158. }
  13159. /*!
  13160. \internal
  13161. Places the raw data points needed for a step plot with right oriented steps in \a lineData.
  13162. As for all plot data retrieval functions, \a scatterData just contains all unaltered data
  13163. (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter
  13164. points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  13165. scatterData, and the function will skip filling the vector.
  13166. \see drawLinePlot
  13167. */
  13168. void QCPGraph::getStepRightPlotData(QVector<QPointF>* linePixelData,
  13169. QVector<QCPData>* scatterData) const
  13170. {
  13171. QCPAxis* keyAxis = mKeyAxis.data();
  13172. QCPAxis* valueAxis = mValueAxis.data();
  13173. if (!keyAxis || !valueAxis) {
  13174. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  13175. return;
  13176. }
  13177. if (!linePixelData) {
  13178. qDebug() << Q_FUNC_INFO << "null pointer passed as lineData";
  13179. return;
  13180. }
  13181. QVector<QCPData> lineData;
  13182. getPreparedData(&lineData, scatterData);
  13183. linePixelData->reserve(lineData.size() * 2
  13184. + 2); // added 2 to reserve memory for lower/upper fill base points that
  13185. // might be needed for fill
  13186. linePixelData->resize(lineData.size() * 2);
  13187. // calculate steps from lineData and transform to pixel coordinates:
  13188. if (keyAxis->orientation() == Qt::Vertical) {
  13189. double lastKey = keyAxis->coordToPixel(lineData.first().key);
  13190. double value;
  13191. for (int i = 0; i < lineData.size(); ++i) {
  13192. value = valueAxis->coordToPixel(lineData.at(i).value);
  13193. (*linePixelData)[i * 2 + 0].setX(value);
  13194. (*linePixelData)[i * 2 + 0].setY(lastKey);
  13195. lastKey = keyAxis->coordToPixel(lineData.at(i).key);
  13196. (*linePixelData)[i * 2 + 1].setX(value);
  13197. (*linePixelData)[i * 2 + 1].setY(lastKey);
  13198. }
  13199. } else // key axis is horizontal
  13200. {
  13201. double lastKey = keyAxis->coordToPixel(lineData.first().key);
  13202. double value;
  13203. for (int i = 0; i < lineData.size(); ++i) {
  13204. value = valueAxis->coordToPixel(lineData.at(i).value);
  13205. (*linePixelData)[i * 2 + 0].setX(lastKey);
  13206. (*linePixelData)[i * 2 + 0].setY(value);
  13207. lastKey = keyAxis->coordToPixel(lineData.at(i).key);
  13208. (*linePixelData)[i * 2 + 1].setX(lastKey);
  13209. (*linePixelData)[i * 2 + 1].setY(value);
  13210. }
  13211. }
  13212. }
  13213. /*!
  13214. \internal
  13215. Places the raw data points needed for a step plot with centered steps in \a lineData.
  13216. As for all plot data retrieval functions, \a scatterData just contains all unaltered data
  13217. (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter
  13218. points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  13219. scatterData, and the function will skip filling the vector.
  13220. \see drawLinePlot
  13221. */
  13222. void QCPGraph::getStepCenterPlotData(QVector<QPointF>* linePixelData,
  13223. QVector<QCPData>* scatterData) const
  13224. {
  13225. QCPAxis* keyAxis = mKeyAxis.data();
  13226. QCPAxis* valueAxis = mValueAxis.data();
  13227. if (!keyAxis || !valueAxis) {
  13228. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  13229. return;
  13230. }
  13231. if (!linePixelData) {
  13232. qDebug() << Q_FUNC_INFO << "null pointer passed as lineData";
  13233. return;
  13234. }
  13235. QVector<QCPData> lineData;
  13236. getPreparedData(&lineData, scatterData);
  13237. linePixelData->reserve(lineData.size() * 2
  13238. + 2); // added 2 to reserve memory for lower/upper fill base points that
  13239. // might be needed for fill
  13240. linePixelData->resize(lineData.size() * 2);
  13241. // calculate steps from lineData and transform to pixel coordinates:
  13242. if (keyAxis->orientation() == Qt::Vertical) {
  13243. double lastKey = keyAxis->coordToPixel(lineData.first().key);
  13244. double lastValue = valueAxis->coordToPixel(lineData.first().value);
  13245. double key;
  13246. (*linePixelData)[0].setX(lastValue);
  13247. (*linePixelData)[0].setY(lastKey);
  13248. for (int i = 1; i < lineData.size(); ++i) {
  13249. key = (keyAxis->coordToPixel(lineData.at(i).key) + lastKey) * 0.5;
  13250. (*linePixelData)[i * 2 - 1].setX(lastValue);
  13251. (*linePixelData)[i * 2 - 1].setY(key);
  13252. lastValue = valueAxis->coordToPixel(lineData.at(i).value);
  13253. lastKey = keyAxis->coordToPixel(lineData.at(i).key);
  13254. (*linePixelData)[i * 2 + 0].setX(lastValue);
  13255. (*linePixelData)[i * 2 + 0].setY(key);
  13256. }
  13257. (*linePixelData)[lineData.size() * 2 - 1].setX(lastValue);
  13258. (*linePixelData)[lineData.size() * 2 - 1].setY(lastKey);
  13259. } else // key axis is horizontal
  13260. {
  13261. double lastKey = keyAxis->coordToPixel(lineData.first().key);
  13262. double lastValue = valueAxis->coordToPixel(lineData.first().value);
  13263. double key;
  13264. (*linePixelData)[0].setX(lastKey);
  13265. (*linePixelData)[0].setY(lastValue);
  13266. for (int i = 1; i < lineData.size(); ++i) {
  13267. key = (keyAxis->coordToPixel(lineData.at(i).key) + lastKey) * 0.5;
  13268. (*linePixelData)[i * 2 - 1].setX(key);
  13269. (*linePixelData)[i * 2 - 1].setY(lastValue);
  13270. lastValue = valueAxis->coordToPixel(lineData.at(i).value);
  13271. lastKey = keyAxis->coordToPixel(lineData.at(i).key);
  13272. (*linePixelData)[i * 2 + 0].setX(key);
  13273. (*linePixelData)[i * 2 + 0].setY(lastValue);
  13274. }
  13275. (*linePixelData)[lineData.size() * 2 - 1].setX(lastKey);
  13276. (*linePixelData)[lineData.size() * 2 - 1].setY(lastValue);
  13277. }
  13278. }
  13279. /*!
  13280. \internal
  13281. Places the raw data points needed for an impulse plot in \a lineData.
  13282. As for all plot data retrieval functions, \a scatterData just contains all unaltered data
  13283. (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter
  13284. points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a
  13285. scatterData, and the function will skip filling the vector.
  13286. \see drawImpulsePlot
  13287. */
  13288. void QCPGraph::getImpulsePlotData(QVector<QPointF>* linePixelData,
  13289. QVector<QCPData>* scatterData) const
  13290. {
  13291. QCPAxis* keyAxis = mKeyAxis.data();
  13292. QCPAxis* valueAxis = mValueAxis.data();
  13293. if (!keyAxis || !valueAxis) {
  13294. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  13295. return;
  13296. }
  13297. if (!linePixelData) {
  13298. qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData";
  13299. return;
  13300. }
  13301. QVector<QCPData> lineData;
  13302. getPreparedData(&lineData, scatterData);
  13303. linePixelData->resize(
  13304. lineData.size() * 2); // no need to reserve 2 extra points because impulse plot has no fill
  13305. // transform lineData points to pixels:
  13306. if (keyAxis->orientation() == Qt::Vertical) {
  13307. double zeroPointX = valueAxis->coordToPixel(0);
  13308. double key;
  13309. for (int i = 0; i < lineData.size(); ++i) {
  13310. key = keyAxis->coordToPixel(lineData.at(i).key);
  13311. (*linePixelData)[i * 2 + 0].setX(zeroPointX);
  13312. (*linePixelData)[i * 2 + 0].setY(key);
  13313. (*linePixelData)[i * 2 + 1].setX(valueAxis->coordToPixel(lineData.at(i).value));
  13314. (*linePixelData)[i * 2 + 1].setY(key);
  13315. }
  13316. } else // key axis is horizontal
  13317. {
  13318. double zeroPointY = valueAxis->coordToPixel(0);
  13319. double key;
  13320. for (int i = 0; i < lineData.size(); ++i) {
  13321. key = keyAxis->coordToPixel(lineData.at(i).key);
  13322. (*linePixelData)[i * 2 + 0].setX(key);
  13323. (*linePixelData)[i * 2 + 0].setY(zeroPointY);
  13324. (*linePixelData)[i * 2 + 1].setX(key);
  13325. (*linePixelData)[i * 2 + 1].setY(valueAxis->coordToPixel(lineData.at(i).value));
  13326. }
  13327. }
  13328. }
  13329. /*! \internal
  13330. Draws the fill of the graph with the specified brush.
  13331. If the fill is a normal fill towards the zero-value-line, only the \a lineData is required (and
  13332. two extra points at the zero-value-line, which are added by \ref addFillBasePoints and removed by
  13333. \ref removeFillBasePoints after the fill drawing is done).
  13334. If the fill is a channel fill between this QCPGraph and another QCPGraph (mChannelFillGraph), the
  13335. more complex polygon is calculated with the \ref getChannelFillPolygon function.
  13336. \see drawLinePlot
  13337. */
  13338. void QCPGraph::drawFill(QCPPainter* painter, QVector<QPointF>* lineData) const
  13339. {
  13340. if (mLineStyle == lsImpulse)
  13341. return; // fill doesn't make sense for impulse plot
  13342. if (mainBrush().style() == Qt::NoBrush || mainBrush().color().alpha() == 0)
  13343. return;
  13344. applyFillAntialiasingHint(painter);
  13345. if (!mChannelFillGraph) {
  13346. // draw base fill under graph, fill goes all the way to the zero-value-line:
  13347. addFillBasePoints(lineData);
  13348. painter->setPen(Qt::NoPen);
  13349. painter->setBrush(mainBrush());
  13350. painter->drawPolygon(QPolygonF(*lineData));
  13351. removeFillBasePoints(lineData);
  13352. } else {
  13353. // draw channel fill between this graph and mChannelFillGraph:
  13354. painter->setPen(Qt::NoPen);
  13355. painter->setBrush(mainBrush());
  13356. painter->drawPolygon(getChannelFillPolygon(lineData));
  13357. }
  13358. }
  13359. /*! \internal
  13360. Draws scatter symbols at every data point passed in \a scatterData. scatter symbols are
  13361. independent of the line style and are always drawn if the scatter style's shape is not \ref
  13362. QCPScatterStyle::ssNone. Hence, the \a scatterData vector is outputted by all "get(...)PlotData"
  13363. functions, together with the (line style dependent) line data.
  13364. \see drawLinePlot, drawImpulsePlot
  13365. */
  13366. void QCPGraph::drawScatterPlot(QCPPainter* painter, QVector<QCPData>* scatterData) const
  13367. {
  13368. QCPAxis* keyAxis = mKeyAxis.data();
  13369. QCPAxis* valueAxis = mValueAxis.data();
  13370. if (!keyAxis || !valueAxis) {
  13371. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  13372. return;
  13373. }
  13374. // draw error bars:
  13375. if (mErrorType != etNone) {
  13376. applyErrorBarsAntialiasingHint(painter);
  13377. painter->setPen(mErrorPen);
  13378. if (keyAxis->orientation() == Qt::Vertical) {
  13379. for (int i = 0; i < scatterData->size(); ++i)
  13380. drawError(painter, valueAxis->coordToPixel(scatterData->at(i).value),
  13381. keyAxis->coordToPixel(scatterData->at(i).key), scatterData->at(i));
  13382. } else {
  13383. for (int i = 0; i < scatterData->size(); ++i)
  13384. drawError(painter, keyAxis->coordToPixel(scatterData->at(i).key),
  13385. valueAxis->coordToPixel(scatterData->at(i).value), scatterData->at(i));
  13386. }
  13387. }
  13388. // draw scatter point symbols:
  13389. applyScattersAntialiasingHint(painter);
  13390. mScatterStyle.applyTo(painter, mPen);
  13391. if (keyAxis->orientation() == Qt::Vertical) {
  13392. for (int i = 0; i < scatterData->size(); ++i)
  13393. if (!qIsNaN(scatterData->at(i).value))
  13394. mScatterStyle.drawShape(painter, valueAxis->coordToPixel(scatterData->at(i).value),
  13395. keyAxis->coordToPixel(scatterData->at(i).key));
  13396. } else {
  13397. for (int i = 0; i < scatterData->size(); ++i)
  13398. if (!qIsNaN(scatterData->at(i).value))
  13399. mScatterStyle.drawShape(painter, keyAxis->coordToPixel(scatterData->at(i).key),
  13400. valueAxis->coordToPixel(scatterData->at(i).value));
  13401. }
  13402. }
  13403. /*! \internal
  13404. Draws line graphs from the provided data. It connects all points in \a lineData, which was
  13405. created by one of the "get(...)PlotData" functions for line styles that require simple line
  13406. connections between the point vector they create. These are for example \ref getLinePlotData,
  13407. \ref getStepLeftPlotData, \ref getStepRightPlotData and \ref getStepCenterPlotData.
  13408. \see drawScatterPlot, drawImpulsePlot
  13409. */
  13410. void QCPGraph::drawLinePlot(QCPPainter* painter, QVector<QPointF>* lineData) const
  13411. {
  13412. // draw line of graph:
  13413. if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) {
  13414. applyDefaultAntialiasingHint(painter);
  13415. painter->setPen(mainPen());
  13416. painter->setBrush(Qt::NoBrush);
  13417. /* Draws polyline in batches, currently not used:
  13418. int p = 0;
  13419. while (p < lineData->size())
  13420. {
  13421. int batch = qMin(25, lineData->size()-p);
  13422. if (p != 0)
  13423. {
  13424. ++batch;
  13425. --p; // to draw the connection lines between two batches
  13426. }
  13427. painter->drawPolyline(lineData->constData()+p, batch);
  13428. p += batch;
  13429. }
  13430. */
  13431. // if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
  13432. if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines)
  13433. && painter->pen().style() == Qt::SolidLine
  13434. && !painter->modes().testFlag(QCPPainter::pmVectorized)
  13435. && !painter->modes().testFlag(QCPPainter::pmNoCaching)) {
  13436. int i = 0;
  13437. bool lastIsNan = false;
  13438. const int lineDataSize = lineData->size();
  13439. while (i < lineDataSize
  13440. && (qIsNaN(lineData->at(i).y())
  13441. || qIsNaN(lineData->at(i).x()))) // make sure first point is not NaN
  13442. ++i;
  13443. ++i; // because drawing works in 1 point retrospect
  13444. while (i < lineDataSize) {
  13445. if (!qIsNaN(lineData->at(i).y())
  13446. && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line
  13447. {
  13448. if (!lastIsNan)
  13449. painter->drawLine(lineData->at(i - 1), lineData->at(i));
  13450. else
  13451. lastIsNan = false;
  13452. } else
  13453. lastIsNan = true;
  13454. ++i;
  13455. }
  13456. } else {
  13457. int segmentStart = 0;
  13458. int i = 0;
  13459. const int lineDataSize = lineData->size();
  13460. while (i < lineDataSize) {
  13461. if (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x())
  13462. || qIsInf(lineData->at(i).y())) // NaNs create a gap in the line. Also filter
  13463. // Infs which make drawPolyline block
  13464. {
  13465. painter->drawPolyline(lineData->constData() + segmentStart,
  13466. i - segmentStart); // i, because we don't want to include
  13467. // the current NaN point
  13468. segmentStart = i + 1;
  13469. }
  13470. ++i;
  13471. }
  13472. // draw last segment:
  13473. painter->drawPolyline(lineData->constData() + segmentStart,
  13474. lineDataSize - segmentStart);
  13475. }
  13476. }
  13477. }
  13478. /*! \internal
  13479. Draws impulses from the provided data, i.e. it connects all line pairs in \a lineData, which was
  13480. created by \ref getImpulsePlotData.
  13481. \see drawScatterPlot, drawLinePlot
  13482. */
  13483. void QCPGraph::drawImpulsePlot(QCPPainter* painter, QVector<QPointF>* lineData) const
  13484. {
  13485. // draw impulses:
  13486. if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) {
  13487. applyDefaultAntialiasingHint(painter);
  13488. QPen pen = mainPen();
  13489. pen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
  13490. painter->setPen(pen);
  13491. painter->setBrush(Qt::NoBrush);
  13492. painter->drawLines(*lineData);
  13493. }
  13494. }
  13495. /*! \internal
  13496. Returns the \a lineData and \a scatterData that need to be plotted for this graph taking into
  13497. consideration the current axis ranges and, if \ref setAdaptiveSampling is enabled, local point
  13498. densities.
  13499. 0 may be passed as \a lineData or \a scatterData to indicate that the respective dataset isn't
  13500. needed. For example, if the scatter style (\ref setScatterStyle) is \ref QCPScatterStyle::ssNone,
  13501. \a scatterData should be 0 to prevent unnecessary calculations.
  13502. This method is used by the various "get(...)PlotData" methods to get the basic working set of
  13503. data.
  13504. */
  13505. void QCPGraph::getPreparedData(QVector<QCPData>* lineData, QVector<QCPData>* scatterData) const
  13506. {
  13507. QCPAxis* keyAxis = mKeyAxis.data();
  13508. QCPAxis* valueAxis = mValueAxis.data();
  13509. if (!keyAxis || !valueAxis) {
  13510. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  13511. return;
  13512. }
  13513. // get visible data range:
  13514. QCPDataMap::const_iterator lower,
  13515. upper; // note that upper is the actual upper point, and not 1 step after the upper point
  13516. getVisibleDataBounds(lower, upper);
  13517. if (lower == mData->constEnd() || upper == mData->constEnd())
  13518. return;
  13519. // count points in visible range, taking into account that we only need to count to the limit
  13520. // maxCount if using adaptive sampling:
  13521. int maxCount = std::numeric_limits<int>::max();
  13522. if (mAdaptiveSampling) {
  13523. int keyPixelSpan =
  13524. qAbs(keyAxis->coordToPixel(lower.key()) - keyAxis->coordToPixel(upper.key()));
  13525. maxCount = 2 * keyPixelSpan + 2;
  13526. }
  13527. int dataCount = countDataInBounds(lower, upper, maxCount);
  13528. if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at
  13529. // least two points per pixel on average
  13530. {
  13531. if (lineData) {
  13532. QCPDataMap::const_iterator it = lower;
  13533. QCPDataMap::const_iterator upperEnd = upper + 1;
  13534. double minValue = it.value().value;
  13535. double maxValue = it.value().value;
  13536. QCPDataMap::const_iterator currentIntervalFirstPoint = it;
  13537. int reversedFactor =
  13538. keyAxis->rangeReversed() != (keyAxis->orientation() == Qt::Vertical)
  13539. ? -1
  13540. : 1; // is used to calculate keyEpsilon pixel into the correct direction
  13541. int reversedRound = keyAxis->rangeReversed() != (keyAxis->orientation() == Qt::Vertical)
  13542. ? 1
  13543. : 0; // is used to switch between floor (normal) and ceil
  13544. // (reversed) rounding of currentIntervalStartKey
  13545. double currentIntervalStartKey =
  13546. keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key()) + reversedRound));
  13547. double lastIntervalEndKey = currentIntervalStartKey;
  13548. double keyEpsilon =
  13549. qAbs(currentIntervalStartKey
  13550. - keyAxis->pixelToCoord(
  13551. keyAxis->coordToPixel(currentIntervalStartKey)
  13552. + 1.0 * reversedFactor)); // interval of one pixel on screen when mapped to
  13553. // plot key coordinates
  13554. bool keyEpsilonVariable =
  13555. keyAxis->scaleType()
  13556. == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after
  13557. // every interval (for log axes)
  13558. int intervalDataCount = 1;
  13559. ++it; // advance iterator to second data point because adaptive sampling works in 1
  13560. // point retrospect
  13561. while (it != upperEnd) {
  13562. if (it.key()
  13563. < currentIntervalStartKey
  13564. + keyEpsilon) // data point is still within same pixel, so skip it and
  13565. // expand value span of this cluster if necessary
  13566. {
  13567. if (it.value().value < minValue)
  13568. minValue = it.value().value;
  13569. else if (it.value().value > maxValue)
  13570. maxValue = it.value().value;
  13571. ++intervalDataCount;
  13572. } else // new pixel interval started
  13573. {
  13574. if (intervalDataCount
  13575. >= 2) // last pixel had multiple data points, consolidate them to a cluster
  13576. {
  13577. if (lastIntervalEndKey
  13578. < currentIntervalStartKey
  13579. - keyEpsilon) // last point is further away, so first point of
  13580. // this cluster must be at a real data point
  13581. lineData->append(QCPData(currentIntervalStartKey + keyEpsilon * 0.2,
  13582. currentIntervalFirstPoint.value().value));
  13583. lineData->append(
  13584. QCPData(currentIntervalStartKey + keyEpsilon * 0.25, minValue));
  13585. lineData->append(
  13586. QCPData(currentIntervalStartKey + keyEpsilon * 0.75, maxValue));
  13587. if (it.key()
  13588. > currentIntervalStartKey
  13589. + keyEpsilon * 2) // new pixel started further away from previous
  13590. // cluster, so make sure the last point of the
  13591. // cluster is at a real data point
  13592. lineData->append(QCPData(currentIntervalStartKey + keyEpsilon * 0.8,
  13593. (it - 1).value().value));
  13594. } else
  13595. lineData->append(QCPData(currentIntervalFirstPoint.key(),
  13596. currentIntervalFirstPoint.value().value));
  13597. lastIntervalEndKey = (it - 1).value().key;
  13598. minValue = it.value().value;
  13599. maxValue = it.value().value;
  13600. currentIntervalFirstPoint = it;
  13601. currentIntervalStartKey = keyAxis->pixelToCoord(
  13602. (int)(keyAxis->coordToPixel(it.key()) + reversedRound));
  13603. if (keyEpsilonVariable)
  13604. keyEpsilon = qAbs(
  13605. currentIntervalStartKey
  13606. - keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)
  13607. + 1.0 * reversedFactor));
  13608. intervalDataCount = 1;
  13609. }
  13610. ++it;
  13611. }
  13612. // handle last interval:
  13613. if (intervalDataCount
  13614. >= 2) // last pixel had multiple data points, consolidate them to a cluster
  13615. {
  13616. if (lastIntervalEndKey
  13617. < currentIntervalStartKey
  13618. - keyEpsilon) // last point wasn't a cluster, so first point of this
  13619. // cluster must be at a real data point
  13620. lineData->append(QCPData(currentIntervalStartKey + keyEpsilon * 0.2,
  13621. currentIntervalFirstPoint.value().value));
  13622. lineData->append(QCPData(currentIntervalStartKey + keyEpsilon * 0.25, minValue));
  13623. lineData->append(QCPData(currentIntervalStartKey + keyEpsilon * 0.75, maxValue));
  13624. } else
  13625. lineData->append(QCPData(currentIntervalFirstPoint.key(),
  13626. currentIntervalFirstPoint.value().value));
  13627. }
  13628. if (scatterData) {
  13629. double valueMaxRange = valueAxis->range().upper;
  13630. double valueMinRange = valueAxis->range().lower;
  13631. QCPDataMap::const_iterator it = lower;
  13632. QCPDataMap::const_iterator upperEnd = upper + 1;
  13633. double minValue = it.value().value;
  13634. double maxValue = it.value().value;
  13635. QCPDataMap::const_iterator minValueIt = it;
  13636. QCPDataMap::const_iterator maxValueIt = it;
  13637. QCPDataMap::const_iterator currentIntervalStart = it;
  13638. int reversedFactor =
  13639. keyAxis->rangeReversed()
  13640. ? -1
  13641. : 1; // is used to calculate keyEpsilon pixel into the correct direction
  13642. int reversedRound = keyAxis->rangeReversed()
  13643. ? 1
  13644. : 0; // is used to switch between floor (normal) and ceil
  13645. // (reversed) rounding of currentIntervalStartKey
  13646. double currentIntervalStartKey =
  13647. keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key()) + reversedRound));
  13648. double keyEpsilon =
  13649. qAbs(currentIntervalStartKey
  13650. - keyAxis->pixelToCoord(
  13651. keyAxis->coordToPixel(currentIntervalStartKey)
  13652. + 1.0 * reversedFactor)); // interval of one pixel on screen when mapped to
  13653. // plot key coordinates
  13654. bool keyEpsilonVariable =
  13655. keyAxis->scaleType()
  13656. == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after
  13657. // every interval (for log axes)
  13658. int intervalDataCount = 1;
  13659. ++it; // advance iterator to second data point because adaptive sampling works in 1
  13660. // point retrospect
  13661. while (it != upperEnd) {
  13662. if (it.key()
  13663. < currentIntervalStartKey
  13664. + keyEpsilon) // data point is still within same pixel, so skip it and
  13665. // expand value span of this pixel if necessary
  13666. {
  13667. if (it.value().value < minValue && it.value().value > valueMinRange
  13668. && it.value().value < valueMaxRange) {
  13669. minValue = it.value().value;
  13670. minValueIt = it;
  13671. } else if (it.value().value > maxValue && it.value().value > valueMinRange
  13672. && it.value().value < valueMaxRange) {
  13673. maxValue = it.value().value;
  13674. maxValueIt = it;
  13675. }
  13676. ++intervalDataCount;
  13677. } else // new pixel started
  13678. {
  13679. if (intervalDataCount
  13680. >= 2) // last pixel had multiple data points, consolidate them
  13681. {
  13682. // determine value pixel span and add as many points in interval to maintain
  13683. // certain vertical data density (this is specific to scatter plot):
  13684. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)
  13685. - valueAxis->coordToPixel(maxValue));
  13686. int dataModulo = qMax(
  13687. 1,
  13688. qRound(intervalDataCount
  13689. / (valuePixelSpan / 4.0))); // approximately every 4 value pixels
  13690. // one data point on average
  13691. QCPDataMap::const_iterator intervalIt = currentIntervalStart;
  13692. int c = 0;
  13693. while (intervalIt != it) {
  13694. if ((c % dataModulo == 0 || intervalIt == minValueIt
  13695. || intervalIt == maxValueIt)
  13696. && intervalIt.value().value > valueMinRange
  13697. && intervalIt.value().value < valueMaxRange)
  13698. scatterData->append(intervalIt.value());
  13699. ++c;
  13700. ++intervalIt;
  13701. }
  13702. } else if (currentIntervalStart.value().value > valueMinRange
  13703. && currentIntervalStart.value().value < valueMaxRange)
  13704. scatterData->append(currentIntervalStart.value());
  13705. minValue = it.value().value;
  13706. maxValue = it.value().value;
  13707. currentIntervalStart = it;
  13708. currentIntervalStartKey = keyAxis->pixelToCoord(
  13709. (int)(keyAxis->coordToPixel(it.key()) + reversedRound));
  13710. if (keyEpsilonVariable)
  13711. keyEpsilon = qAbs(
  13712. currentIntervalStartKey
  13713. - keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)
  13714. + 1.0 * reversedFactor));
  13715. intervalDataCount = 1;
  13716. }
  13717. ++it;
  13718. }
  13719. // handle last interval:
  13720. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  13721. {
  13722. // determine value pixel span and add as many points in interval to maintain certain
  13723. // vertical data density (this is specific to scatter plot):
  13724. double valuePixelSpan =
  13725. qAbs(valueAxis->coordToPixel(minValue) - valueAxis->coordToPixel(maxValue));
  13726. int dataModulo = qMax(
  13727. 1,
  13728. qRound(
  13729. intervalDataCount
  13730. / (valuePixelSpan
  13731. / 4.0))); // approximately every 4 value pixels one data point on average
  13732. QCPDataMap::const_iterator intervalIt = currentIntervalStart;
  13733. int c = 0;
  13734. while (intervalIt != it) {
  13735. if ((c % dataModulo == 0 || intervalIt == minValueIt
  13736. || intervalIt == maxValueIt)
  13737. && intervalIt.value().value > valueMinRange
  13738. && intervalIt.value().value < valueMaxRange)
  13739. scatterData->append(intervalIt.value());
  13740. ++c;
  13741. ++intervalIt;
  13742. }
  13743. } else if (currentIntervalStart.value().value > valueMinRange
  13744. && currentIntervalStart.value().value < valueMaxRange)
  13745. scatterData->append(currentIntervalStart.value());
  13746. }
  13747. } else // don't use adaptive sampling algorithm, transfer points one-to-one from the map into
  13748. // the output parameters
  13749. {
  13750. QVector<QCPData>* dataVector = 0;
  13751. if (lineData)
  13752. dataVector = lineData;
  13753. else if (scatterData)
  13754. dataVector = scatterData;
  13755. if (dataVector) {
  13756. QCPDataMap::const_iterator it = lower;
  13757. QCPDataMap::const_iterator upperEnd = upper + 1;
  13758. dataVector->reserve(dataCount + 2); // +2 for possible fill end points
  13759. while (it != upperEnd) {
  13760. dataVector->append(it.value());
  13761. ++it;
  13762. }
  13763. }
  13764. if (lineData && scatterData)
  13765. *scatterData = *dataVector;
  13766. }
  13767. }
  13768. /*! \internal
  13769. called by the scatter drawing function (\ref drawScatterPlot) to draw the error bars on one data
  13770. point. \a x and \a y pixel positions of the data point are passed since they are already known in
  13771. pixel coordinates in the drawing function, so we save some extra coordToPixel transforms here. \a
  13772. data is therefore only used for the errors, not key and value.
  13773. */
  13774. void QCPGraph::drawError(QCPPainter* painter, double x, double y, const QCPData& data) const
  13775. {
  13776. if (qIsNaN(data.value))
  13777. return;
  13778. QCPAxis* keyAxis = mKeyAxis.data();
  13779. QCPAxis* valueAxis = mValueAxis.data();
  13780. if (!keyAxis || !valueAxis) {
  13781. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  13782. return;
  13783. }
  13784. double a, b; // positions of error bar bounds in pixels
  13785. double barWidthHalf = mErrorBarSize * 0.5;
  13786. double skipSymbolMargin =
  13787. mScatterStyle.size(); // pixels left blank per side, when mErrorBarSkipSymbol is true
  13788. if (keyAxis->orientation() == Qt::Vertical) {
  13789. // draw key error vertically and value error horizontally
  13790. if (mErrorType == etKey || mErrorType == etBoth) {
  13791. a = keyAxis->coordToPixel(data.key - data.keyErrorMinus);
  13792. b = keyAxis->coordToPixel(data.key + data.keyErrorPlus);
  13793. if (keyAxis->rangeReversed())
  13794. qSwap(a, b);
  13795. // draw spine:
  13796. if (mErrorBarSkipSymbol) {
  13797. if (a - y > skipSymbolMargin) // don't draw spine if error is so small it's within
  13798. // skipSymbolmargin
  13799. painter->drawLine(QLineF(x, a, x, y + skipSymbolMargin));
  13800. if (y - b > skipSymbolMargin)
  13801. painter->drawLine(QLineF(x, y - skipSymbolMargin, x, b));
  13802. } else
  13803. painter->drawLine(QLineF(x, a, x, b));
  13804. // draw handles:
  13805. painter->drawLine(QLineF(x - barWidthHalf, a, x + barWidthHalf, a));
  13806. painter->drawLine(QLineF(x - barWidthHalf, b, x + barWidthHalf, b));
  13807. }
  13808. if (mErrorType == etValue || mErrorType == etBoth) {
  13809. a = valueAxis->coordToPixel(data.value - data.valueErrorMinus);
  13810. b = valueAxis->coordToPixel(data.value + data.valueErrorPlus);
  13811. if (valueAxis->rangeReversed())
  13812. qSwap(a, b);
  13813. // draw spine:
  13814. if (mErrorBarSkipSymbol) {
  13815. if (x - a > skipSymbolMargin) // don't draw spine if error is so small it's within
  13816. // skipSymbolmargin
  13817. painter->drawLine(QLineF(a, y, x - skipSymbolMargin, y));
  13818. if (b - x > skipSymbolMargin)
  13819. painter->drawLine(QLineF(x + skipSymbolMargin, y, b, y));
  13820. } else
  13821. painter->drawLine(QLineF(a, y, b, y));
  13822. // draw handles:
  13823. painter->drawLine(QLineF(a, y - barWidthHalf, a, y + barWidthHalf));
  13824. painter->drawLine(QLineF(b, y - barWidthHalf, b, y + barWidthHalf));
  13825. }
  13826. } else // mKeyAxis->orientation() is Qt::Horizontal
  13827. {
  13828. // draw value error vertically and key error horizontally
  13829. if (mErrorType == etKey || mErrorType == etBoth) {
  13830. a = keyAxis->coordToPixel(data.key - data.keyErrorMinus);
  13831. b = keyAxis->coordToPixel(data.key + data.keyErrorPlus);
  13832. if (keyAxis->rangeReversed())
  13833. qSwap(a, b);
  13834. // draw spine:
  13835. if (mErrorBarSkipSymbol) {
  13836. if (x - a > skipSymbolMargin) // don't draw spine if error is so small it's within
  13837. // skipSymbolmargin
  13838. painter->drawLine(QLineF(a, y, x - skipSymbolMargin, y));
  13839. if (b - x > skipSymbolMargin)
  13840. painter->drawLine(QLineF(x + skipSymbolMargin, y, b, y));
  13841. } else
  13842. painter->drawLine(QLineF(a, y, b, y));
  13843. // draw handles:
  13844. painter->drawLine(QLineF(a, y - barWidthHalf, a, y + barWidthHalf));
  13845. painter->drawLine(QLineF(b, y - barWidthHalf, b, y + barWidthHalf));
  13846. }
  13847. if (mErrorType == etValue || mErrorType == etBoth) {
  13848. a = valueAxis->coordToPixel(data.value - data.valueErrorMinus);
  13849. b = valueAxis->coordToPixel(data.value + data.valueErrorPlus);
  13850. if (valueAxis->rangeReversed())
  13851. qSwap(a, b);
  13852. // draw spine:
  13853. if (mErrorBarSkipSymbol) {
  13854. if (a - y > skipSymbolMargin) // don't draw spine if error is so small it's within
  13855. // skipSymbolmargin
  13856. painter->drawLine(QLineF(x, a, x, y + skipSymbolMargin));
  13857. if (y - b > skipSymbolMargin)
  13858. painter->drawLine(QLineF(x, y - skipSymbolMargin, x, b));
  13859. } else
  13860. painter->drawLine(QLineF(x, a, x, b));
  13861. // draw handles:
  13862. painter->drawLine(QLineF(x - barWidthHalf, a, x + barWidthHalf, a));
  13863. painter->drawLine(QLineF(x - barWidthHalf, b, x + barWidthHalf, b));
  13864. }
  13865. }
  13866. }
  13867. /*! \internal
  13868. called by \ref getPreparedData to determine which data (key) range is visible at the current key
  13869. axis range setting, so only that needs to be processed.
  13870. \a lower returns an iterator to the lowest data point that needs to be taken into account when
  13871. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  13872. lower may still be just outside the visible range.
  13873. \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie
  13874. just outside of the visible range.
  13875. if the graph contains no data, both \a lower and \a upper point to constEnd.
  13876. */
  13877. void QCPGraph::getVisibleDataBounds(QCPDataMap::const_iterator& lower,
  13878. QCPDataMap::const_iterator& upper) const
  13879. {
  13880. if (!mKeyAxis) {
  13881. qDebug() << Q_FUNC_INFO << "invalid key axis";
  13882. return;
  13883. }
  13884. if (mData->isEmpty()) {
  13885. lower = mData->constEnd();
  13886. upper = mData->constEnd();
  13887. return;
  13888. }
  13889. // get visible data range as QMap iterators
  13890. QCPDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower);
  13891. QCPDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper);
  13892. bool lowoutlier =
  13893. lbound != mData->constBegin(); // indicates whether there exist points below axis range
  13894. bool highoutlier =
  13895. ubound != mData->constEnd(); // indicates whether there exist points above axis range
  13896. lower = (lowoutlier ? lbound - 1 : lbound); // data point range that will be actually drawn
  13897. upper = (highoutlier ? ubound : ubound - 1); // data point range that will be actually drawn
  13898. }
  13899. /*! \internal
  13900. Counts the number of data points between \a lower and \a upper (including them), up to a maximum
  13901. of \a maxCount.
  13902. This function is used by \ref getPreparedData to determine whether adaptive sampling shall be
  13903. used (if enabled via \ref setAdaptiveSampling) or not. This is also why counting of data points
  13904. only needs to be done until \a maxCount is reached, which should be set to the number of data
  13905. points at which adaptive sampling sets in.
  13906. */
  13907. int QCPGraph::countDataInBounds(const QCPDataMap::const_iterator& lower,
  13908. const QCPDataMap::const_iterator& upper, int maxCount) const
  13909. {
  13910. if (upper == mData->constEnd() && lower == mData->constEnd())
  13911. return 0;
  13912. QCPDataMap::const_iterator it = lower;
  13913. int count = 1;
  13914. while (it != upper && count < maxCount) {
  13915. ++it;
  13916. ++count;
  13917. }
  13918. return count;
  13919. }
  13920. /*! \internal
  13921. The line data vector generated by e.g. getLinePlotData contains only the line that connects the
  13922. data points. If the graph needs to be filled, two additional points need to be added at the
  13923. value-zero-line in the lower and upper key positions of the graph. This function calculates these
  13924. points and adds them to the end of \a lineData. Since the fill is typically drawn before the line
  13925. stroke, these added points need to be removed again after the fill is done, with the
  13926. removeFillBasePoints function.
  13927. The expanding of \a lineData by two points will not cause unnecessary memory reallocations,
  13928. because the data vector generation functions (getLinePlotData etc.) reserve two extra points when
  13929. they allocate memory for \a lineData.
  13930. \see removeFillBasePoints, lowerFillBasePoint, upperFillBasePoint
  13931. */
  13932. void QCPGraph::addFillBasePoints(QVector<QPointF>* lineData) const
  13933. {
  13934. if (!mKeyAxis) {
  13935. qDebug() << Q_FUNC_INFO << "invalid key axis";
  13936. return;
  13937. }
  13938. if (!lineData) {
  13939. qDebug() << Q_FUNC_INFO << "passed null as lineData";
  13940. return;
  13941. }
  13942. if (lineData->isEmpty())
  13943. return;
  13944. // append points that close the polygon fill at the key axis:
  13945. if (mKeyAxis.data()->orientation() == Qt::Vertical) {
  13946. *lineData << upperFillBasePoint(lineData->last().y());
  13947. *lineData << lowerFillBasePoint(lineData->first().y());
  13948. } else {
  13949. *lineData << upperFillBasePoint(lineData->last().x());
  13950. *lineData << lowerFillBasePoint(lineData->first().x());
  13951. }
  13952. }
  13953. /*! \internal
  13954. removes the two points from \a lineData that were added by \ref addFillBasePoints.
  13955. \see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint
  13956. */
  13957. void QCPGraph::removeFillBasePoints(QVector<QPointF>* lineData) const
  13958. {
  13959. if (!lineData) {
  13960. qDebug() << Q_FUNC_INFO << "passed null as lineData";
  13961. return;
  13962. }
  13963. if (lineData->isEmpty())
  13964. return;
  13965. lineData->remove(lineData->size() - 2, 2);
  13966. }
  13967. /*! \internal
  13968. called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon
  13969. on the lower side of the zero-value-line parallel to the key axis. The logarithmic axis scale
  13970. case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative
  13971. infinity. So this case is handled separately by just closing the fill polygon on the axis which
  13972. lies in the direction towards the zero value.
  13973. \a lowerKey will be the the key (in pixels) of the returned point. Depending on whether the key
  13974. axis is horizontal or vertical, \a lowerKey will end up as the x or y value of the returned
  13975. point, respectively.
  13976. \see upperFillBasePoint, addFillBasePoints
  13977. */
  13978. QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const
  13979. {
  13980. QCPAxis* keyAxis = mKeyAxis.data();
  13981. QCPAxis* valueAxis = mValueAxis.data();
  13982. if (!keyAxis || !valueAxis) {
  13983. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  13984. return QPointF();
  13985. }
  13986. QPointF point;
  13987. if (valueAxis->scaleType() == QCPAxis::stLinear) {
  13988. if (keyAxis->axisType() == QCPAxis::atLeft) {
  13989. point.setX(valueAxis->coordToPixel(0));
  13990. point.setY(lowerKey);
  13991. } else if (keyAxis->axisType() == QCPAxis::atRight) {
  13992. point.setX(valueAxis->coordToPixel(0));
  13993. point.setY(lowerKey);
  13994. } else if (keyAxis->axisType() == QCPAxis::atTop) {
  13995. point.setX(lowerKey);
  13996. point.setY(valueAxis->coordToPixel(0));
  13997. } else if (keyAxis->axisType() == QCPAxis::atBottom) {
  13998. point.setX(lowerKey);
  13999. point.setY(valueAxis->coordToPixel(0));
  14000. }
  14001. } else // valueAxis->mScaleType == QCPAxis::stLogarithmic
  14002. {
  14003. // In logarithmic scaling we can't just draw to value zero so we just fill all the way
  14004. // to the axis which is in the direction towards zero
  14005. if (keyAxis->orientation() == Qt::Vertical) {
  14006. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed())
  14007. || (valueAxis->range().upper > 0
  14008. && valueAxis->rangeReversed())) // if range is negative, zero is on opposite
  14009. // side of key axis
  14010. point.setX(keyAxis->axisRect()->right());
  14011. else
  14012. point.setX(keyAxis->axisRect()->left());
  14013. point.setY(lowerKey);
  14014. } else if (keyAxis->axisType() == QCPAxis::atTop
  14015. || keyAxis->axisType() == QCPAxis::atBottom) {
  14016. point.setX(lowerKey);
  14017. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed())
  14018. || (valueAxis->range().upper > 0
  14019. && valueAxis->rangeReversed())) // if range is negative, zero is on opposite
  14020. // side of key axis
  14021. point.setY(keyAxis->axisRect()->top());
  14022. else
  14023. point.setY(keyAxis->axisRect()->bottom());
  14024. }
  14025. }
  14026. return point;
  14027. }
  14028. /*! \internal
  14029. called by \ref addFillBasePoints to conveniently assign the point which closes the fill
  14030. polygon on the upper side of the zero-value-line parallel to the key axis. The logarithmic axis
  14031. scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or
  14032. negative infinity. So this case is handled separately by just closing the fill polygon on the
  14033. axis which lies in the direction towards the zero value.
  14034. \a upperKey will be the the key (in pixels) of the returned point. Depending on whether the key
  14035. axis is horizontal or vertical, \a upperKey will end up as the x or y value of the returned
  14036. point, respectively.
  14037. \see lowerFillBasePoint, addFillBasePoints
  14038. */
  14039. QPointF QCPGraph::upperFillBasePoint(double upperKey) const
  14040. {
  14041. QCPAxis* keyAxis = mKeyAxis.data();
  14042. QCPAxis* valueAxis = mValueAxis.data();
  14043. if (!keyAxis || !valueAxis) {
  14044. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  14045. return QPointF();
  14046. }
  14047. QPointF point;
  14048. if (valueAxis->scaleType() == QCPAxis::stLinear) {
  14049. if (keyAxis->axisType() == QCPAxis::atLeft) {
  14050. point.setX(valueAxis->coordToPixel(0));
  14051. point.setY(upperKey);
  14052. } else if (keyAxis->axisType() == QCPAxis::atRight) {
  14053. point.setX(valueAxis->coordToPixel(0));
  14054. point.setY(upperKey);
  14055. } else if (keyAxis->axisType() == QCPAxis::atTop) {
  14056. point.setX(upperKey);
  14057. point.setY(valueAxis->coordToPixel(0));
  14058. } else if (keyAxis->axisType() == QCPAxis::atBottom) {
  14059. point.setX(upperKey);
  14060. point.setY(valueAxis->coordToPixel(0));
  14061. }
  14062. } else // valueAxis->mScaleType == QCPAxis::stLogarithmic
  14063. {
  14064. // In logarithmic scaling we can't just draw to value 0 so we just fill all the way
  14065. // to the axis which is in the direction towards 0
  14066. if (keyAxis->orientation() == Qt::Vertical) {
  14067. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed())
  14068. || (valueAxis->range().upper > 0
  14069. && valueAxis->rangeReversed())) // if range is negative, zero is on opposite
  14070. // side of key axis
  14071. point.setX(keyAxis->axisRect()->right());
  14072. else
  14073. point.setX(keyAxis->axisRect()->left());
  14074. point.setY(upperKey);
  14075. } else if (keyAxis->axisType() == QCPAxis::atTop
  14076. || keyAxis->axisType() == QCPAxis::atBottom) {
  14077. point.setX(upperKey);
  14078. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed())
  14079. || (valueAxis->range().upper > 0
  14080. && valueAxis->rangeReversed())) // if range is negative, zero is on opposite
  14081. // side of key axis
  14082. point.setY(keyAxis->axisRect()->top());
  14083. else
  14084. point.setY(keyAxis->axisRect()->bottom());
  14085. }
  14086. }
  14087. return point;
  14088. }
  14089. /*! \internal
  14090. Generates the polygon needed for drawing channel fills between this graph (data passed via \a
  14091. lineData) and the graph specified by mChannelFillGraph (data generated by calling its \ref
  14092. getPlotData function). May return an empty polygon if the key ranges have no overlap or fill
  14093. target graph and this graph don't have same orientation (i.e. both key axes horizontal or both
  14094. key axes vertical). For increased performance (due to implicit sharing), keep the returned
  14095. QPolygonF const.
  14096. */
  14097. const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF>* lineData) const
  14098. {
  14099. if (!mChannelFillGraph)
  14100. return QPolygonF();
  14101. QCPAxis* keyAxis = mKeyAxis.data();
  14102. QCPAxis* valueAxis = mValueAxis.data();
  14103. if (!keyAxis || !valueAxis) {
  14104. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  14105. return QPolygonF();
  14106. }
  14107. if (!mChannelFillGraph.data()->mKeyAxis) {
  14108. qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid";
  14109. return QPolygonF();
  14110. }
  14111. if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation())
  14112. return QPolygonF(); // don't have same axis orientation, can't fill that (Note: if keyAxis
  14113. // fits, valueAxis will fit too, because it's always orthogonal to
  14114. // keyAxis)
  14115. if (lineData->isEmpty())
  14116. return QPolygonF();
  14117. QVector<QPointF> otherData;
  14118. mChannelFillGraph.data()->getPlotData(&otherData, 0);
  14119. if (otherData.isEmpty())
  14120. return QPolygonF();
  14121. QVector<QPointF> thisData;
  14122. thisData.reserve(
  14123. lineData->size()
  14124. + otherData.size()); // because we will join both vectors at end of this function
  14125. for (int i = 0; i < lineData->size();
  14126. ++i) // don't use the vector<<(vector), it squeezes internally, which ruins the
  14127. // performance tuning with reserve()
  14128. thisData << lineData->at(i);
  14129. // pointers to be able to swap them, depending which data range needs cropping:
  14130. QVector<QPointF>* staticData = &thisData;
  14131. QVector<QPointF>* croppedData = &otherData;
  14132. // crop both vectors to ranges in which the keys overlap (which coord is key, depends on
  14133. // axisType):
  14134. if (keyAxis->orientation() == Qt::Horizontal) {
  14135. // x is key
  14136. // if an axis range is reversed, the data point keys will be descending. Reverse them, since
  14137. // following algorithm assumes ascending keys:
  14138. if (staticData->first().x() > staticData->last().x()) {
  14139. int size = staticData->size();
  14140. for (int i = 0; i < size / 2; ++i)
  14141. qSwap((*staticData)[i], (*staticData)[size - 1 - i]);
  14142. }
  14143. if (croppedData->first().x() > croppedData->last().x()) {
  14144. int size = croppedData->size();
  14145. for (int i = 0; i < size / 2; ++i)
  14146. qSwap((*croppedData)[i], (*croppedData)[size - 1 - i]);
  14147. }
  14148. // crop lower bound:
  14149. if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
  14150. qSwap(staticData, croppedData);
  14151. int lowBound = findIndexBelowX(croppedData, staticData->first().x());
  14152. if (lowBound == -1)
  14153. return QPolygonF(); // key ranges have no overlap
  14154. croppedData->remove(0, lowBound);
  14155. // set lowest point of cropped data to fit exactly key position of first static data
  14156. // point via linear interpolation:
  14157. if (croppedData->size() < 2)
  14158. return QPolygonF(); // need at least two points for interpolation
  14159. double slope;
  14160. if (croppedData->at(1).x() - croppedData->at(0).x() != 0)
  14161. slope = (croppedData->at(1).y() - croppedData->at(0).y())
  14162. / (croppedData->at(1).x() - croppedData->at(0).x());
  14163. else
  14164. slope = 0;
  14165. (*croppedData)[0].setY(croppedData->at(0).y()
  14166. + slope * (staticData->first().x() - croppedData->at(0).x()));
  14167. (*croppedData)[0].setX(staticData->first().x());
  14168. // crop upper bound:
  14169. if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
  14170. qSwap(staticData, croppedData);
  14171. int highBound = findIndexAboveX(croppedData, staticData->last().x());
  14172. if (highBound == -1)
  14173. return QPolygonF(); // key ranges have no overlap
  14174. croppedData->remove(highBound + 1, croppedData->size() - (highBound + 1));
  14175. // set highest point of cropped data to fit exactly key position of last static data
  14176. // point via linear interpolation:
  14177. if (croppedData->size() < 2)
  14178. return QPolygonF(); // need at least two points for interpolation
  14179. int li = croppedData->size() - 1; // last index
  14180. if (croppedData->at(li).x() - croppedData->at(li - 1).x() != 0)
  14181. slope = (croppedData->at(li).y() - croppedData->at(li - 1).y())
  14182. / (croppedData->at(li).x() - croppedData->at(li - 1).x());
  14183. else
  14184. slope = 0;
  14185. (*croppedData)[li].setY(croppedData->at(li - 1).y()
  14186. + slope * (staticData->last().x() - croppedData->at(li - 1).x()));
  14187. (*croppedData)[li].setX(staticData->last().x());
  14188. } else // mKeyAxis->orientation() == Qt::Vertical
  14189. {
  14190. // y is key
  14191. // similar to "x is key" but switched x,y. Further, lower/upper meaning is inverted compared
  14192. // to x, because in pixel coordinates, y increases from top to bottom, not bottom to top
  14193. // like data coordinate. if an axis range is reversed, the data point keys will be
  14194. // descending. Reverse them, since following algorithm assumes ascending keys:
  14195. if (staticData->first().y() < staticData->last().y()) {
  14196. int size = staticData->size();
  14197. for (int i = 0; i < size / 2; ++i)
  14198. qSwap((*staticData)[i], (*staticData)[size - 1 - i]);
  14199. }
  14200. if (croppedData->first().y() < croppedData->last().y()) {
  14201. int size = croppedData->size();
  14202. for (int i = 0; i < size / 2; ++i)
  14203. qSwap((*croppedData)[i], (*croppedData)[size - 1 - i]);
  14204. }
  14205. // crop lower bound:
  14206. if (staticData->first().y() > croppedData->first().y()) // other one must be cropped
  14207. qSwap(staticData, croppedData);
  14208. int lowBound = findIndexAboveY(croppedData, staticData->first().y());
  14209. if (lowBound == -1)
  14210. return QPolygonF(); // key ranges have no overlap
  14211. croppedData->remove(0, lowBound);
  14212. // set lowest point of cropped data to fit exactly key position of first static data
  14213. // point via linear interpolation:
  14214. if (croppedData->size() < 2)
  14215. return QPolygonF(); // need at least two points for interpolation
  14216. double slope;
  14217. if (croppedData->at(1).y() - croppedData->at(0).y()
  14218. != 0) // avoid division by zero in step plots
  14219. slope = (croppedData->at(1).x() - croppedData->at(0).x())
  14220. / (croppedData->at(1).y() - croppedData->at(0).y());
  14221. else
  14222. slope = 0;
  14223. (*croppedData)[0].setX(croppedData->at(0).x()
  14224. + slope * (staticData->first().y() - croppedData->at(0).y()));
  14225. (*croppedData)[0].setY(staticData->first().y());
  14226. // crop upper bound:
  14227. if (staticData->last().y() < croppedData->last().y()) // other one must be cropped
  14228. qSwap(staticData, croppedData);
  14229. int highBound = findIndexBelowY(croppedData, staticData->last().y());
  14230. if (highBound == -1)
  14231. return QPolygonF(); // key ranges have no overlap
  14232. croppedData->remove(highBound + 1, croppedData->size() - (highBound + 1));
  14233. // set highest point of cropped data to fit exactly key position of last static data
  14234. // point via linear interpolation:
  14235. if (croppedData->size() < 2)
  14236. return QPolygonF(); // need at least two points for interpolation
  14237. int li = croppedData->size() - 1; // last index
  14238. if (croppedData->at(li).y() - croppedData->at(li - 1).y()
  14239. != 0) // avoid division by zero in step plots
  14240. slope = (croppedData->at(li).x() - croppedData->at(li - 1).x())
  14241. / (croppedData->at(li).y() - croppedData->at(li - 1).y());
  14242. else
  14243. slope = 0;
  14244. (*croppedData)[li].setX(croppedData->at(li - 1).x()
  14245. + slope * (staticData->last().y() - croppedData->at(li - 1).y()));
  14246. (*croppedData)[li].setY(staticData->last().y());
  14247. }
  14248. // return joined:
  14249. for (int i = otherData.size() - 1; i >= 0;
  14250. --i) // insert reversed, otherwise the polygon will be twisted
  14251. thisData << otherData.at(i);
  14252. return QPolygonF(thisData);
  14253. }
  14254. /*! \internal
  14255. Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in
  14256. \a data points are ordered ascending, as is the case when plotting with horizontal key axis.
  14257. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  14258. */
  14259. int QCPGraph::findIndexAboveX(const QVector<QPointF>* data, double x) const
  14260. {
  14261. for (int i = data->size() - 1; i >= 0; --i) {
  14262. if (data->at(i).x() < x) {
  14263. if (i < data->size() - 1)
  14264. return i + 1;
  14265. else
  14266. return data->size() - 1;
  14267. }
  14268. }
  14269. return -1;
  14270. }
  14271. /*! \internal
  14272. Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in
  14273. \a data points are ordered ascending, as is the case when plotting with horizontal key axis.
  14274. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  14275. */
  14276. int QCPGraph::findIndexBelowX(const QVector<QPointF>* data, double x) const
  14277. {
  14278. for (int i = 0; i < data->size(); ++i) {
  14279. if (data->at(i).x() > x) {
  14280. if (i > 0)
  14281. return i - 1;
  14282. else
  14283. return 0;
  14284. }
  14285. }
  14286. return -1;
  14287. }
  14288. /*! \internal
  14289. Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in
  14290. \a data points are ordered descending, as is the case when plotting with vertical key axis.
  14291. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  14292. */
  14293. int QCPGraph::findIndexAboveY(const QVector<QPointF>* data, double y) const
  14294. {
  14295. for (int i = 0; i < data->size(); ++i) {
  14296. if (data->at(i).y() < y) {
  14297. if (i > 0)
  14298. return i - 1;
  14299. else
  14300. return 0;
  14301. }
  14302. }
  14303. return -1;
  14304. }
  14305. /*! \internal
  14306. Calculates the (minimum) distance (in pixels) the graph's representation has from the given \a
  14307. pixelPoint in pixels. This is used to determine whether the graph was clicked or not, e.g. in
  14308. \ref selectTest.
  14309. If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape
  14310. is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns
  14311. -1.0.
  14312. */
  14313. double QCPGraph::pointDistance(const QPointF& pixelPoint) const
  14314. {
  14315. if (mData->isEmpty())
  14316. return -1.0;
  14317. if (mLineStyle == lsNone && mScatterStyle.isNone())
  14318. return -1.0;
  14319. // calculate minimum distances to graph representation:
  14320. if (mLineStyle == lsNone) {
  14321. // no line displayed, only calculate distance to scatter points:
  14322. QVector<QCPData> scatterData;
  14323. getScatterPlotData(&scatterData);
  14324. if (scatterData.size() > 0) {
  14325. double minDistSqr = std::numeric_limits<double>::max();
  14326. for (int i = 0; i < scatterData.size(); ++i) {
  14327. double currentDistSqr =
  14328. QVector2D(coordsToPixels(scatterData.at(i).key, scatterData.at(i).value)
  14329. - pixelPoint)
  14330. .lengthSquared();
  14331. if (currentDistSqr < minDistSqr)
  14332. minDistSqr = currentDistSqr;
  14333. }
  14334. return qSqrt(minDistSqr);
  14335. } else // no data available in view to calculate distance to
  14336. return -1.0;
  14337. } else {
  14338. // line displayed, calculate distance to line segments:
  14339. QVector<QPointF> lineData;
  14340. getPlotData(&lineData, 0); // unlike with getScatterPlotData we get pixel coordinates here
  14341. if (lineData.size() > 1) // at least one line segment, compare distance to line segments
  14342. {
  14343. double minDistSqr = std::numeric_limits<double>::max();
  14344. if (mLineStyle == lsImpulse) {
  14345. // impulse plot differs from other line styles in that the lineData points are only
  14346. // pairwise connected:
  14347. for (int i = 0; i < lineData.size() - 1; i += 2) // iterate pairs
  14348. {
  14349. double currentDistSqr =
  14350. distSqrToLine(lineData.at(i), lineData.at(i + 1), pixelPoint);
  14351. if (currentDistSqr < minDistSqr)
  14352. minDistSqr = currentDistSqr;
  14353. }
  14354. } else {
  14355. // all other line plots (line and step) connect points directly:
  14356. for (int i = 0; i < lineData.size() - 1; ++i) {
  14357. double currentDistSqr =
  14358. distSqrToLine(lineData.at(i), lineData.at(i + 1), pixelPoint);
  14359. if (currentDistSqr < minDistSqr)
  14360. minDistSqr = currentDistSqr;
  14361. }
  14362. }
  14363. return qSqrt(minDistSqr);
  14364. } else if (lineData.size() > 0) // only single data point, calculate distance to that point
  14365. {
  14366. return QVector2D(lineData.at(0) - pixelPoint).length();
  14367. } else // no data available in view to calculate distance to
  14368. return -1.0;
  14369. }
  14370. }
  14371. /*! \internal
  14372. Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in
  14373. \a data points are ordered descending, as is the case when plotting with vertical key axis (since
  14374. keys are ordered ascending).
  14375. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  14376. */
  14377. int QCPGraph::findIndexBelowY(const QVector<QPointF>* data, double y) const
  14378. {
  14379. for (int i = data->size() - 1; i >= 0; --i) {
  14380. if (data->at(i).y() > y) {
  14381. if (i < data->size() - 1)
  14382. return i + 1;
  14383. else
  14384. return data->size() - 1;
  14385. }
  14386. }
  14387. return -1;
  14388. }
  14389. /* inherits documentation from base class */
  14390. QCPRange QCPGraph::getKeyRange(bool& foundRange, SignDomain inSignDomain) const
  14391. {
  14392. // just call the specialized version which takes an additional argument whether error bars
  14393. // should also be taken into consideration for range calculation. We set this to true here.
  14394. return getKeyRange(foundRange, inSignDomain, true);
  14395. }
  14396. /* inherits documentation from base class */
  14397. QCPRange QCPGraph::getValueRange(bool& foundRange, SignDomain inSignDomain) const
  14398. {
  14399. // just call the specialized version which takes an additional argument whether error bars
  14400. // should also be taken into consideration for range calculation. We set this to true here.
  14401. return getValueRange(foundRange, inSignDomain, true);
  14402. }
  14403. /*! \overload
  14404. Allows to specify whether the error bars should be included in the range calculation.
  14405. \see getKeyRange(bool &foundRange, SignDomain inSignDomain)
  14406. */
  14407. QCPRange QCPGraph::getKeyRange(bool& foundRange, SignDomain inSignDomain, bool includeErrors) const
  14408. {
  14409. QCPRange range;
  14410. bool haveLower = false;
  14411. bool haveUpper = false;
  14412. double current, currentErrorMinus, currentErrorPlus;
  14413. if (inSignDomain == sdBoth) // range may be anywhere
  14414. {
  14415. QCPDataMap::const_iterator it = mData->constBegin();
  14416. while (it != mData->constEnd()) {
  14417. if (!qIsNaN(it.value().value)) {
  14418. current = it.value().key;
  14419. currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
  14420. currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
  14421. if (current - currentErrorMinus < range.lower || !haveLower) {
  14422. range.lower = current - currentErrorMinus;
  14423. haveLower = true;
  14424. }
  14425. if (current + currentErrorPlus > range.upper || !haveUpper) {
  14426. range.upper = current + currentErrorPlus;
  14427. haveUpper = true;
  14428. }
  14429. }
  14430. ++it;
  14431. }
  14432. } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain
  14433. {
  14434. QCPDataMap::const_iterator it = mData->constBegin();
  14435. while (it != mData->constEnd()) {
  14436. if (!qIsNaN(it.value().value)) {
  14437. current = it.value().key;
  14438. currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
  14439. currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
  14440. if ((current - currentErrorMinus < range.lower || !haveLower)
  14441. && current - currentErrorMinus < 0) {
  14442. range.lower = current - currentErrorMinus;
  14443. haveLower = true;
  14444. }
  14445. if ((current + currentErrorPlus > range.upper || !haveUpper)
  14446. && current + currentErrorPlus < 0) {
  14447. range.upper = current + currentErrorPlus;
  14448. haveUpper = true;
  14449. }
  14450. if (includeErrors) // in case point is in valid sign domain but errobars stretch
  14451. // beyond it, we still want to geht that point.
  14452. {
  14453. if ((current < range.lower || !haveLower) && current < 0) {
  14454. range.lower = current;
  14455. haveLower = true;
  14456. }
  14457. if ((current > range.upper || !haveUpper) && current < 0) {
  14458. range.upper = current;
  14459. haveUpper = true;
  14460. }
  14461. }
  14462. }
  14463. ++it;
  14464. }
  14465. } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain
  14466. {
  14467. QCPDataMap::const_iterator it = mData->constBegin();
  14468. while (it != mData->constEnd()) {
  14469. if (!qIsNaN(it.value().value)) {
  14470. current = it.value().key;
  14471. currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0);
  14472. currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0);
  14473. if ((current - currentErrorMinus < range.lower || !haveLower)
  14474. && current - currentErrorMinus > 0) {
  14475. range.lower = current - currentErrorMinus;
  14476. haveLower = true;
  14477. }
  14478. if ((current + currentErrorPlus > range.upper || !haveUpper)
  14479. && current + currentErrorPlus > 0) {
  14480. range.upper = current + currentErrorPlus;
  14481. haveUpper = true;
  14482. }
  14483. if (includeErrors) // in case point is in valid sign domain but errobars stretch
  14484. // beyond it, we still want to get that point.
  14485. {
  14486. if ((current < range.lower || !haveLower) && current > 0) {
  14487. range.lower = current;
  14488. haveLower = true;
  14489. }
  14490. if ((current > range.upper || !haveUpper) && current > 0) {
  14491. range.upper = current;
  14492. haveUpper = true;
  14493. }
  14494. }
  14495. }
  14496. ++it;
  14497. }
  14498. }
  14499. foundRange = haveLower && haveUpper;
  14500. return range;
  14501. }
  14502. /*! \overload
  14503. Allows to specify whether the error bars should be included in the range calculation.
  14504. \see getValueRange(bool &foundRange, SignDomain inSignDomain)
  14505. */
  14506. QCPRange QCPGraph::getValueRange(bool& foundRange, SignDomain inSignDomain,
  14507. bool includeErrors) const
  14508. {
  14509. QCPRange range;
  14510. bool haveLower = false;
  14511. bool haveUpper = false;
  14512. double current, currentErrorMinus, currentErrorPlus;
  14513. if (inSignDomain == sdBoth) // range may be anywhere
  14514. {
  14515. QCPDataMap::const_iterator it = mData->constBegin();
  14516. while (it != mData->constEnd()) {
  14517. current = it.value().value;
  14518. if (!qIsNaN(current)) {
  14519. currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
  14520. currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
  14521. if (current - currentErrorMinus < range.lower || !haveLower) {
  14522. range.lower = current - currentErrorMinus;
  14523. haveLower = true;
  14524. }
  14525. if (current + currentErrorPlus > range.upper || !haveUpper) {
  14526. range.upper = current + currentErrorPlus;
  14527. haveUpper = true;
  14528. }
  14529. }
  14530. ++it;
  14531. }
  14532. } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain
  14533. {
  14534. QCPDataMap::const_iterator it = mData->constBegin();
  14535. while (it != mData->constEnd()) {
  14536. current = it.value().value;
  14537. if (!qIsNaN(current)) {
  14538. currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
  14539. currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
  14540. if ((current - currentErrorMinus < range.lower || !haveLower)
  14541. && current - currentErrorMinus < 0) {
  14542. range.lower = current - currentErrorMinus;
  14543. haveLower = true;
  14544. }
  14545. if ((current + currentErrorPlus > range.upper || !haveUpper)
  14546. && current + currentErrorPlus < 0) {
  14547. range.upper = current + currentErrorPlus;
  14548. haveUpper = true;
  14549. }
  14550. if (includeErrors) // in case point is in valid sign domain but errobars stretch
  14551. // beyond it, we still want to get that point.
  14552. {
  14553. if ((current < range.lower || !haveLower) && current < 0) {
  14554. range.lower = current;
  14555. haveLower = true;
  14556. }
  14557. if ((current > range.upper || !haveUpper) && current < 0) {
  14558. range.upper = current;
  14559. haveUpper = true;
  14560. }
  14561. }
  14562. }
  14563. ++it;
  14564. }
  14565. } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain
  14566. {
  14567. QCPDataMap::const_iterator it = mData->constBegin();
  14568. while (it != mData->constEnd()) {
  14569. current = it.value().value;
  14570. if (!qIsNaN(current)) {
  14571. currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0);
  14572. currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0);
  14573. if ((current - currentErrorMinus < range.lower || !haveLower)
  14574. && current - currentErrorMinus > 0) {
  14575. range.lower = current - currentErrorMinus;
  14576. haveLower = true;
  14577. }
  14578. if ((current + currentErrorPlus > range.upper || !haveUpper)
  14579. && current + currentErrorPlus > 0) {
  14580. range.upper = current + currentErrorPlus;
  14581. haveUpper = true;
  14582. }
  14583. if (includeErrors) // in case point is in valid sign domain but errobars stretch
  14584. // beyond it, we still want to geht that point.
  14585. {
  14586. if ((current < range.lower || !haveLower) && current > 0) {
  14587. range.lower = current;
  14588. haveLower = true;
  14589. }
  14590. if ((current > range.upper || !haveUpper) && current > 0) {
  14591. range.upper = current;
  14592. haveUpper = true;
  14593. }
  14594. }
  14595. }
  14596. ++it;
  14597. }
  14598. }
  14599. foundRange = haveLower && haveUpper;
  14600. return range;
  14601. }
  14602. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14603. //////////////////// QCPCurveData
  14604. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14605. /*! \class QCPCurveData
  14606. \brief Holds the data of one single data point for QCPCurve.
  14607. The container for storing multiple data points is \ref QCPCurveDataMap.
  14608. The stored data is:
  14609. \li \a t: the free parameter of the curve at this curve point (cp. the mathematical vector
  14610. <em>(x(t), y(t))</em>) \li \a key: coordinate on the key axis of this curve point \li \a value:
  14611. coordinate on the value axis of this curve point
  14612. \see QCPCurveDataMap
  14613. */
  14614. /*!
  14615. Constructs a curve data point with t, key and value set to zero.
  14616. */
  14617. QCPCurveData::QCPCurveData() : t(0), key(0), value(0)
  14618. {}
  14619. /*!
  14620. Constructs a curve data point with the specified \a t, \a key and \a value.
  14621. */
  14622. QCPCurveData::QCPCurveData(double t, double key, double value) : t(t), key(key), value(value)
  14623. {}
  14624. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14625. //////////////////// QCPCurve
  14626. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14627. /*! \class QCPCurve
  14628. \brief A plottable representing a parametric curve in a plot.
  14629. \image html QCPCurve.png
  14630. Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate,
  14631. so their visual representation can have \a loops. This is realized by introducing a third
  14632. coordinate \a t, which defines the order of the points described by the other two coordinates \a
  14633. x and \a y.
  14634. To plot data, assign it with the \ref setData or \ref addData functions.
  14635. Gaps in the curve can be created by adding data points with NaN as key and value
  14636. (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data
  14637. points that shall be separated.
  14638. \section appearance Changing the appearance
  14639. The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush).
  14640. \section usage Usage
  14641. Like all data representing objects in QCustomPlot, the QCPCurve is a plottable
  14642. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable,
  14643. QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
  14644. Usually, you first create an instance and add it to the customPlot:
  14645. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1
  14646. and then modify the properties of the newly created plottable, e.g.:
  14647. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2
  14648. */
  14649. /*!
  14650. Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  14651. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  14652. the same orientation. If either of these restrictions is violated, a corresponding message is
  14653. printed to the debug output (qDebug), the construction is not aborted, though.
  14654. The constructed QCPCurve can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
  14655. then takes ownership of the graph.
  14656. */
  14657. QCPCurve::QCPCurve(QCPAxis* keyAxis, QCPAxis* valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis)
  14658. {
  14659. mData = new QCPCurveDataMap;
  14660. mPen.setColor(Qt::blue);
  14661. mPen.setStyle(Qt::SolidLine);
  14662. mBrush.setColor(Qt::blue);
  14663. mBrush.setStyle(Qt::NoBrush);
  14664. mSelectedPen = mPen;
  14665. mSelectedPen.setWidthF(2.5);
  14666. mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen
  14667. mSelectedBrush = mBrush;
  14668. setScatterStyle(QCPScatterStyle());
  14669. setLineStyle(lsLine);
  14670. }
  14671. QCPCurve::~QCPCurve()
  14672. {
  14673. delete mData;
  14674. }
  14675. /*!
  14676. Replaces the current data with the provided \a data.
  14677. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable
  14678. takes ownership of the passed data and replaces the internal data pointer with it. This is
  14679. significantly faster than copying for large datasets.
  14680. */
  14681. void QCPCurve::setData(QCPCurveDataMap* data, bool copy)
  14682. {
  14683. if (mData == data) {
  14684. qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable"
  14685. << reinterpret_cast<quintptr>(data);
  14686. return;
  14687. }
  14688. if (copy) {
  14689. *mData = *data;
  14690. } else {
  14691. delete mData;
  14692. mData = data;
  14693. }
  14694. }
  14695. /*! \overload
  14696. Replaces the current data with the provided points in \a t, \a key and \a value tuples. The
  14697. provided vectors should have equal length. Else, the number of added points will be the size of
  14698. the smallest vector.
  14699. */
  14700. void QCPCurve::setData(const QVector<double>& t, const QVector<double>& key,
  14701. const QVector<double>& value)
  14702. {
  14703. mData->clear();
  14704. int n = t.size();
  14705. n = qMin(n, key.size());
  14706. n = qMin(n, value.size());
  14707. QCPCurveData newData;
  14708. for (int i = 0; i < n; ++i) {
  14709. newData.t = t[i];
  14710. newData.key = key[i];
  14711. newData.value = value[i];
  14712. mData->insertMulti(newData.t, newData);
  14713. }
  14714. }
  14715. /*! \overload
  14716. Replaces the current data with the provided \a key and \a value pairs. The t parameter
  14717. of each data point will be set to the integer index of the respective key/value pair.
  14718. */
  14719. void QCPCurve::setData(const QVector<double>& key, const QVector<double>& value)
  14720. {
  14721. mData->clear();
  14722. int n = key.size();
  14723. n = qMin(n, value.size());
  14724. QCPCurveData newData;
  14725. for (int i = 0; i < n; ++i) {
  14726. newData.t = i; // no t vector given, so we assign t the index of the key/value pair
  14727. newData.key = key[i];
  14728. newData.value = value[i];
  14729. mData->insertMulti(newData.t, newData);
  14730. }
  14731. }
  14732. /*!
  14733. Sets the visual appearance of single data points in the plot. If set to \ref
  14734. QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate
  14735. line style).
  14736. \see QCPScatterStyle, setLineStyle
  14737. */
  14738. void QCPCurve::setScatterStyle(const QCPScatterStyle& style)
  14739. {
  14740. mScatterStyle = style;
  14741. }
  14742. /*!
  14743. Sets how the single data points are connected in the plot or how they are represented visually
  14744. apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref
  14745. setScatterStyle to the desired scatter style.
  14746. \see setScatterStyle
  14747. */
  14748. void QCPCurve::setLineStyle(QCPCurve::LineStyle style)
  14749. {
  14750. mLineStyle = style;
  14751. }
  14752. /*!
  14753. Adds the provided data points in \a dataMap to the current data.
  14754. \see removeData
  14755. */
  14756. void QCPCurve::addData(const QCPCurveDataMap& dataMap)
  14757. {
  14758. mData->unite(dataMap);
  14759. }
  14760. /*! \overload
  14761. Adds the provided single data point in \a data to the current data.
  14762. \see removeData
  14763. */
  14764. void QCPCurve::addData(const QCPCurveData& data)
  14765. {
  14766. mData->insertMulti(data.t, data);
  14767. }
  14768. /*! \overload
  14769. Adds the provided single data point as \a t, \a key and \a value tuple to the current data
  14770. \see removeData
  14771. */
  14772. void QCPCurve::addData(double t, double key, double value)
  14773. {
  14774. QCPCurveData newData;
  14775. newData.t = t;
  14776. newData.key = key;
  14777. newData.value = value;
  14778. mData->insertMulti(newData.t, newData);
  14779. }
  14780. /*! \overload
  14781. Adds the provided single data point as \a key and \a value pair to the current data The t
  14782. parameter of the data point is set to the t of the last data point plus 1. If there is no last
  14783. data point, t will be set to 0.
  14784. \see removeData
  14785. */
  14786. void QCPCurve::addData(double key, double value)
  14787. {
  14788. QCPCurveData newData;
  14789. if (!mData->isEmpty())
  14790. newData.t = (mData->constEnd() - 1).key() + 1;
  14791. else
  14792. newData.t = 0;
  14793. newData.key = key;
  14794. newData.value = value;
  14795. mData->insertMulti(newData.t, newData);
  14796. }
  14797. /*! \overload
  14798. Adds the provided data points as \a t, \a key and \a value tuples to the current data.
  14799. \see removeData
  14800. */
  14801. void QCPCurve::addData(const QVector<double>& ts, const QVector<double>& keys,
  14802. const QVector<double>& values)
  14803. {
  14804. int n = ts.size();
  14805. n = qMin(n, keys.size());
  14806. n = qMin(n, values.size());
  14807. QCPCurveData newData;
  14808. for (int i = 0; i < n; ++i) {
  14809. newData.t = ts[i];
  14810. newData.key = keys[i];
  14811. newData.value = values[i];
  14812. mData->insertMulti(newData.t, newData);
  14813. }
  14814. }
  14815. /*!
  14816. Removes all data points with curve parameter t smaller than \a t.
  14817. \see addData, clearData
  14818. */
  14819. void QCPCurve::removeDataBefore(double t)
  14820. {
  14821. QCPCurveDataMap::iterator it = mData->begin();
  14822. while (it != mData->end() && it.key() < t)
  14823. it = mData->erase(it);
  14824. }
  14825. /*!
  14826. Removes all data points with curve parameter t greater than \a t.
  14827. \see addData, clearData
  14828. */
  14829. void QCPCurve::removeDataAfter(double t)
  14830. {
  14831. if (mData->isEmpty())
  14832. return;
  14833. QCPCurveDataMap::iterator it = mData->upperBound(t);
  14834. while (it != mData->end())
  14835. it = mData->erase(it);
  14836. }
  14837. /*!
  14838. Removes all data points with curve parameter t between \a fromt and \a tot. if \a fromt is
  14839. greater or equal to \a tot, the function does nothing. To remove a single data point with known
  14840. t, use \ref removeData(double t).
  14841. \see addData, clearData
  14842. */
  14843. void QCPCurve::removeData(double fromt, double tot)
  14844. {
  14845. if (fromt >= tot || mData->isEmpty())
  14846. return;
  14847. QCPCurveDataMap::iterator it = mData->upperBound(fromt);
  14848. QCPCurveDataMap::iterator itEnd = mData->upperBound(tot);
  14849. while (it != itEnd)
  14850. it = mData->erase(it);
  14851. }
  14852. /*! \overload
  14853. Removes a single data point at curve parameter \a t. If the position is not known with absolute
  14854. precision, consider using \ref removeData(double fromt, double tot) with a small fuzziness
  14855. interval around the suspected position, depeding on the precision with which the curve parameter
  14856. is known.
  14857. \see addData, clearData
  14858. */
  14859. void QCPCurve::removeData(double t)
  14860. {
  14861. mData->remove(t);
  14862. }
  14863. /*!
  14864. Removes all data points.
  14865. \see removeData, removeDataAfter, removeDataBefore
  14866. */
  14867. void QCPCurve::clearData()
  14868. {
  14869. mData->clear();
  14870. }
  14871. /* inherits documentation from base class */
  14872. double QCPCurve::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  14873. {
  14874. Q_UNUSED(details)
  14875. if ((onlySelectable && !mSelectable) || mData->isEmpty())
  14876. return -1;
  14877. if (!mKeyAxis || !mValueAxis) {
  14878. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  14879. return -1;
  14880. }
  14881. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()))
  14882. return pointDistance(pos);
  14883. else
  14884. return -1;
  14885. }
  14886. /* inherits documentation from base class */
  14887. void QCPCurve::draw(QCPPainter* painter)
  14888. {
  14889. if (mData->isEmpty())
  14890. return;
  14891. // allocate line vector:
  14892. QVector<QPointF>* lineData = new QVector<QPointF>;
  14893. // fill with curve data:
  14894. getCurveData(lineData);
  14895. // check data validity if flag set:
  14896. #ifdef QCUSTOMPLOT_CHECK_DATA
  14897. QCPCurveDataMap::const_iterator it;
  14898. for (it = mData->constBegin(); it != mData->constEnd(); ++it) {
  14899. if (QCP::isInvalidData(it.value().t)
  14900. || QCP::isInvalidData(it.value().key, it.value().value))
  14901. qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid."
  14902. << "Plottable name:" << name();
  14903. }
  14904. #endif
  14905. // draw curve fill:
  14906. if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) {
  14907. applyFillAntialiasingHint(painter);
  14908. painter->setPen(Qt::NoPen);
  14909. painter->setBrush(mainBrush());
  14910. painter->drawPolygon(QPolygonF(*lineData));
  14911. }
  14912. // draw curve line:
  14913. if (mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) {
  14914. applyDefaultAntialiasingHint(painter);
  14915. painter->setPen(mainPen());
  14916. painter->setBrush(Qt::NoBrush);
  14917. // if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
  14918. if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines)
  14919. && painter->pen().style() == Qt::SolidLine
  14920. && !painter->modes().testFlag(QCPPainter::pmVectorized)
  14921. && !painter->modes().testFlag(QCPPainter::pmNoCaching)) {
  14922. int i = 0;
  14923. bool lastIsNan = false;
  14924. const int lineDataSize = lineData->size();
  14925. while (i < lineDataSize
  14926. && (qIsNaN(lineData->at(i).y())
  14927. || qIsNaN(lineData->at(i).x()))) // make sure first point is not NaN
  14928. ++i;
  14929. ++i; // because drawing works in 1 point retrospect
  14930. while (i < lineDataSize) {
  14931. if (!qIsNaN(lineData->at(i).y())
  14932. && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line
  14933. {
  14934. if (!lastIsNan)
  14935. painter->drawLine(lineData->at(i - 1), lineData->at(i));
  14936. else
  14937. lastIsNan = false;
  14938. } else
  14939. lastIsNan = true;
  14940. ++i;
  14941. }
  14942. } else {
  14943. int segmentStart = 0;
  14944. int i = 0;
  14945. const int lineDataSize = lineData->size();
  14946. while (i < lineDataSize) {
  14947. if (qIsNaN(lineData->at(i).y())
  14948. || qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line
  14949. {
  14950. painter->drawPolyline(lineData->constData() + segmentStart,
  14951. i - segmentStart); // i, because we don't want to include
  14952. // the current NaN point
  14953. segmentStart = i + 1;
  14954. }
  14955. ++i;
  14956. }
  14957. // draw last segment:
  14958. painter->drawPolyline(lineData->constData() + segmentStart,
  14959. lineDataSize - segmentStart);
  14960. }
  14961. }
  14962. // draw scatters:
  14963. if (!mScatterStyle.isNone())
  14964. drawScatterPlot(painter, lineData);
  14965. // free allocated line data:
  14966. delete lineData;
  14967. }
  14968. /* inherits documentation from base class */
  14969. void QCPCurve::drawLegendIcon(QCPPainter* painter, const QRectF& rect) const
  14970. {
  14971. // draw fill:
  14972. if (mBrush.style() != Qt::NoBrush) {
  14973. applyFillAntialiasingHint(painter);
  14974. painter->fillRect(QRectF(rect.left(), rect.top() + rect.height() / 2.0, rect.width(),
  14975. rect.height() / 3.0),
  14976. mBrush);
  14977. }
  14978. // draw line vertically centered:
  14979. if (mLineStyle != lsNone) {
  14980. applyDefaultAntialiasingHint(painter);
  14981. painter->setPen(mPen);
  14982. painter->drawLine(QLineF(
  14983. rect.left(), rect.top() + rect.height() / 2.0, rect.right() + 5,
  14984. rect.top()
  14985. + rect.height()
  14986. / 2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
  14987. }
  14988. // draw scatter symbol:
  14989. if (!mScatterStyle.isNone()) {
  14990. applyScattersAntialiasingHint(painter);
  14991. // scale scatter pixmap if it's too large to fit in legend icon rect:
  14992. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap
  14993. && (mScatterStyle.pixmap().size().width() > rect.width()
  14994. || mScatterStyle.pixmap().size().height() > rect.height())) {
  14995. QCPScatterStyle scaledStyle(mScatterStyle);
  14996. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(
  14997. rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  14998. scaledStyle.applyTo(painter, mPen);
  14999. scaledStyle.drawShape(painter, QRectF(rect).center());
  15000. } else {
  15001. mScatterStyle.applyTo(painter, mPen);
  15002. mScatterStyle.drawShape(painter, QRectF(rect).center());
  15003. }
  15004. }
  15005. }
  15006. /*! \internal
  15007. Draws scatter symbols at every data point passed in \a pointData. scatter symbols are independent
  15008. of the line style and are always drawn if scatter shape is not \ref QCPScatterStyle::ssNone.
  15009. */
  15010. void QCPCurve::drawScatterPlot(QCPPainter* painter, const QVector<QPointF>* pointData) const
  15011. {
  15012. // draw scatter point symbols:
  15013. applyScattersAntialiasingHint(painter);
  15014. mScatterStyle.applyTo(painter, mPen);
  15015. for (int i = 0; i < pointData->size(); ++i)
  15016. if (!qIsNaN(pointData->at(i).x()) && !qIsNaN(pointData->at(i).y()))
  15017. mScatterStyle.drawShape(painter, pointData->at(i));
  15018. }
  15019. /*! \internal
  15020. called by QCPCurve::draw to generate a point vector (in pixel coordinates) which represents the
  15021. line of the curve.
  15022. Line segments that aren't visible in the current axis rect are handled in an optimized way. They
  15023. are projected onto a rectangle slightly larger than the visible axis rect and simplified
  15024. regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside
  15025. the visible axis rect by generating new temporary points on the outer rect if necessary.
  15026. Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref
  15027. getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints.
  15028. */
  15029. void QCPCurve::getCurveData(QVector<QPointF>* lineData) const
  15030. {
  15031. QCPAxis* keyAxis = mKeyAxis.data();
  15032. QCPAxis* valueAxis = mValueAxis.data();
  15033. if (!keyAxis || !valueAxis) {
  15034. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  15035. return;
  15036. }
  15037. // add margins to rect to compensate for stroke width
  15038. double strokeMargin =
  15039. qMax(qreal(1.0), qreal(mainPen().widthF() * 0.75)); // stroke radius + 50% safety
  15040. if (!mScatterStyle.isNone())
  15041. strokeMargin = qMax(strokeMargin, mScatterStyle.size());
  15042. double rectLeft = keyAxis->pixelToCoord(
  15043. keyAxis->coordToPixel(keyAxis->range().lower)
  15044. - strokeMargin
  15045. * ((keyAxis->orientation() == Qt::Vertical) != keyAxis->rangeReversed() ? -1 : 1));
  15046. double rectRight = keyAxis->pixelToCoord(
  15047. keyAxis->coordToPixel(keyAxis->range().upper)
  15048. + strokeMargin
  15049. * ((keyAxis->orientation() == Qt::Vertical) != keyAxis->rangeReversed() ? -1 : 1));
  15050. double rectBottom = valueAxis->pixelToCoord(
  15051. valueAxis->coordToPixel(valueAxis->range().lower)
  15052. + strokeMargin
  15053. * ((valueAxis->orientation() == Qt::Horizontal) != valueAxis->rangeReversed() ? -1
  15054. : 1));
  15055. double rectTop = valueAxis->pixelToCoord(
  15056. valueAxis->coordToPixel(valueAxis->range().upper)
  15057. - strokeMargin
  15058. * ((valueAxis->orientation() == Qt::Horizontal) != valueAxis->rangeReversed() ? -1
  15059. : 1));
  15060. int currentRegion;
  15061. QCPCurveDataMap::const_iterator it = mData->constBegin();
  15062. QCPCurveDataMap::const_iterator prevIt = mData->constEnd() - 1;
  15063. int prevRegion = getRegion(prevIt.value().key, prevIt.value().value, rectLeft, rectTop,
  15064. rectRight, rectBottom);
  15065. QVector<QPointF> trailingPoints; // points that must be applied after all other points (are
  15066. // generated only when handling first point to get virtual
  15067. // segment between last and first point right)
  15068. while (it != mData->constEnd()) {
  15069. currentRegion =
  15070. getRegion(it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom);
  15071. if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge
  15072. // points or original points if entering R
  15073. {
  15074. if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal
  15075. {
  15076. QPointF crossA, crossB;
  15077. if (prevRegion == 5) // we're coming from R, so add this point optimized
  15078. {
  15079. lineData->append(getOptimizedPoint(
  15080. currentRegion, it.value().key, it.value().value, prevIt.value().key,
  15081. prevIt.value().value, rectLeft, rectTop, rectRight, rectBottom));
  15082. // in the situations 5->1/7/9/3 the segment may leave R and directly cross
  15083. // through two outer regions. In these cases we need to add an additional corner
  15084. // point
  15085. *lineData << getOptimizedCornerPoints(
  15086. prevRegion, currentRegion, prevIt.value().key, prevIt.value().value,
  15087. it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom);
  15088. } else if (mayTraverse(prevRegion, currentRegion)
  15089. && getTraverse(prevIt.value().key, prevIt.value().value, it.value().key,
  15090. it.value().value, rectLeft, rectTop, rectRight,
  15091. rectBottom, crossA, crossB)) {
  15092. // add the two cross points optimized if segment crosses R and if segment isn't
  15093. // virtual zeroth segment between last and first curve point:
  15094. QVector<QPointF> beforeTraverseCornerPoints, afterTraverseCornerPoints;
  15095. getTraverseCornerPoints(prevRegion, currentRegion, rectLeft, rectTop, rectRight,
  15096. rectBottom, beforeTraverseCornerPoints,
  15097. afterTraverseCornerPoints);
  15098. if (it != mData->constBegin()) {
  15099. *lineData << beforeTraverseCornerPoints;
  15100. lineData->append(crossA);
  15101. lineData->append(crossB);
  15102. *lineData << afterTraverseCornerPoints;
  15103. } else {
  15104. lineData->append(crossB);
  15105. *lineData << afterTraverseCornerPoints;
  15106. trailingPoints << beforeTraverseCornerPoints << crossA;
  15107. }
  15108. } else // doesn't cross R, line is just moving around in outside regions, so only
  15109. // need to add optimized point(s) at the boundary corner(s)
  15110. {
  15111. *lineData << getOptimizedCornerPoints(
  15112. prevRegion, currentRegion, prevIt.value().key, prevIt.value().value,
  15113. it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom);
  15114. }
  15115. } else // segment does end in R, so we add previous point optimized and this point at
  15116. // original position
  15117. {
  15118. if (it == mData->constBegin()) // it is first point in curve and prevIt is last one.
  15119. // So save optimized point for adding it to the
  15120. // lineData in the end
  15121. trailingPoints << getOptimizedPoint(
  15122. prevRegion, prevIt.value().key, prevIt.value().value, it.value().key,
  15123. it.value().value, rectLeft, rectTop, rectRight, rectBottom);
  15124. else
  15125. lineData->append(getOptimizedPoint(
  15126. prevRegion, prevIt.value().key, prevIt.value().value, it.value().key,
  15127. it.value().value, rectLeft, rectTop, rectRight, rectBottom));
  15128. lineData->append(coordsToPixels(it.value().key, it.value().value));
  15129. }
  15130. } else // region didn't change
  15131. {
  15132. if (currentRegion == 5) // still in R, keep adding original points
  15133. {
  15134. lineData->append(coordsToPixels(it.value().key, it.value().value));
  15135. } else // still outside R, no need to add anything
  15136. {
  15137. // see how this is not doing anything? That's the main optimization...
  15138. }
  15139. }
  15140. prevIt = it;
  15141. prevRegion = currentRegion;
  15142. ++it;
  15143. }
  15144. *lineData << trailingPoints;
  15145. }
  15146. /*! \internal
  15147. This function is part of the curve optimization algorithm of \ref getCurveData.
  15148. It returns the region of the given point (\a x, \a y) with respect to a rectangle defined by \a
  15149. rectLeft, \a rectTop, \a rectRight, and \a rectBottom.
  15150. The regions are enumerated from top to bottom and left to right:
  15151. <table style="width:10em; text-align:center">
  15152. <tr><td>1</td><td>4</td><td>7</td></tr>
  15153. <tr><td>2</td><td style="border:1px solid black">5</td><td>8</td></tr>
  15154. <tr><td>3</td><td>6</td><td>9</td></tr>
  15155. </table>
  15156. With the rectangle being region 5, and the outer regions extending infinitely outwards. In the
  15157. curve optimization algorithm, region 5 is considered to be the visible portion of the plot.
  15158. */
  15159. int QCPCurve::getRegion(double x, double y, double rectLeft, double rectTop, double rectRight,
  15160. double rectBottom) const
  15161. {
  15162. if (x < rectLeft) // region 123
  15163. {
  15164. if (y > rectTop)
  15165. return 1;
  15166. else if (y < rectBottom)
  15167. return 3;
  15168. else
  15169. return 2;
  15170. } else if (x > rectRight) // region 789
  15171. {
  15172. if (y > rectTop)
  15173. return 7;
  15174. else if (y < rectBottom)
  15175. return 9;
  15176. else
  15177. return 8;
  15178. } else // region 456
  15179. {
  15180. if (y > rectTop)
  15181. return 4;
  15182. else if (y < rectBottom)
  15183. return 6;
  15184. else
  15185. return 5;
  15186. }
  15187. }
  15188. /*! \internal
  15189. This function is part of the curve optimization algorithm of \ref getCurveData.
  15190. This method is used in case the current segment passes from inside the visible rect (region 5,
  15191. see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by
  15192. the line connecting (\a key, \a value) with (\a otherKey, \a otherValue).
  15193. It returns the intersection point of the segment with the border of region 5.
  15194. For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or
  15195. whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or
  15196. leaving it. It is important though that \a otherRegion correctly identifies the other region not
  15197. equal to 5.
  15198. */
  15199. QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key,
  15200. double value, double rectLeft, double rectTop, double rectRight,
  15201. double rectBottom) const
  15202. {
  15203. double intersectKey = rectLeft; // initial value is just fail-safe
  15204. double intersectValue = rectTop; // initial value is just fail-safe
  15205. switch (otherRegion) {
  15206. case 1: // top and left edge
  15207. {
  15208. intersectValue = rectTop;
  15209. intersectKey =
  15210. otherKey + (key - otherKey) / (value - otherValue) * (intersectValue - otherValue);
  15211. if (intersectKey < rectLeft
  15212. || intersectKey > rectRight) // doesn't intersect, so must intersect other:
  15213. {
  15214. intersectKey = rectLeft;
  15215. intersectValue =
  15216. otherValue + (value - otherValue) / (key - otherKey) * (intersectKey - otherKey);
  15217. }
  15218. break;
  15219. }
  15220. case 2: // left edge
  15221. {
  15222. intersectKey = rectLeft;
  15223. intersectValue =
  15224. otherValue + (value - otherValue) / (key - otherKey) * (intersectKey - otherKey);
  15225. break;
  15226. }
  15227. case 3: // bottom and left edge
  15228. {
  15229. intersectValue = rectBottom;
  15230. intersectKey =
  15231. otherKey + (key - otherKey) / (value - otherValue) * (intersectValue - otherValue);
  15232. if (intersectKey < rectLeft
  15233. || intersectKey > rectRight) // doesn't intersect, so must intersect other:
  15234. {
  15235. intersectKey = rectLeft;
  15236. intersectValue =
  15237. otherValue + (value - otherValue) / (key - otherKey) * (intersectKey - otherKey);
  15238. }
  15239. break;
  15240. }
  15241. case 4: // top edge
  15242. {
  15243. intersectValue = rectTop;
  15244. intersectKey =
  15245. otherKey + (key - otherKey) / (value - otherValue) * (intersectValue - otherValue);
  15246. break;
  15247. }
  15248. case 5: {
  15249. break; // case 5 shouldn't happen for this function but we add it anyway to prevent
  15250. // potential discontinuity in branch table
  15251. }
  15252. case 6: // bottom edge
  15253. {
  15254. intersectValue = rectBottom;
  15255. intersectKey =
  15256. otherKey + (key - otherKey) / (value - otherValue) * (intersectValue - otherValue);
  15257. break;
  15258. }
  15259. case 7: // top and right edge
  15260. {
  15261. intersectValue = rectTop;
  15262. intersectKey =
  15263. otherKey + (key - otherKey) / (value - otherValue) * (intersectValue - otherValue);
  15264. if (intersectKey < rectLeft
  15265. || intersectKey > rectRight) // doesn't intersect, so must intersect other:
  15266. {
  15267. intersectKey = rectRight;
  15268. intersectValue =
  15269. otherValue + (value - otherValue) / (key - otherKey) * (intersectKey - otherKey);
  15270. }
  15271. break;
  15272. }
  15273. case 8: // right edge
  15274. {
  15275. intersectKey = rectRight;
  15276. intersectValue =
  15277. otherValue + (value - otherValue) / (key - otherKey) * (intersectKey - otherKey);
  15278. break;
  15279. }
  15280. case 9: // bottom and right edge
  15281. {
  15282. intersectValue = rectBottom;
  15283. intersectKey =
  15284. otherKey + (key - otherKey) / (value - otherValue) * (intersectValue - otherValue);
  15285. if (intersectKey < rectLeft
  15286. || intersectKey > rectRight) // doesn't intersect, so must intersect other:
  15287. {
  15288. intersectKey = rectRight;
  15289. intersectValue =
  15290. otherValue + (value - otherValue) / (key - otherKey) * (intersectKey - otherKey);
  15291. }
  15292. break;
  15293. }
  15294. }
  15295. return coordsToPixels(intersectKey, intersectValue);
  15296. }
  15297. /*! \internal
  15298. This function is part of the curve optimization algorithm of \ref getCurveData.
  15299. In situations where a single segment skips over multiple regions it might become necessary to add
  15300. extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment
  15301. doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts.
  15302. This method provides these points that must be added, assuming the original segment doesn't
  15303. start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by
  15304. \ref getTraverseCornerPoints.)
  15305. For example, consider a segment which directly goes from region 4 to 2 but originally is far out
  15306. to the top left such that it doesn't cross region 5. Naively optimizing these points by
  15307. projecting them on the top and left borders of region 5 will create a segment that surely crosses
  15308. 5, creating a visual artifact in the plot. This method prevents this by providing extra points at
  15309. the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without
  15310. traversing 5.
  15311. */
  15312. QVector<QPointF> QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentRegion,
  15313. double prevKey, double prevValue, double key,
  15314. double value, double rectLeft, double rectTop,
  15315. double rectRight, double rectBottom) const
  15316. {
  15317. QVector<QPointF> result;
  15318. switch (prevRegion) {
  15319. case 1: {
  15320. switch (currentRegion) {
  15321. case 2: {
  15322. result << coordsToPixels(rectLeft, rectTop);
  15323. break;
  15324. }
  15325. case 4: {
  15326. result << coordsToPixels(rectLeft, rectTop);
  15327. break;
  15328. }
  15329. case 3: {
  15330. result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom);
  15331. break;
  15332. }
  15333. case 7: {
  15334. result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop);
  15335. break;
  15336. }
  15337. case 6: {
  15338. result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom);
  15339. result.append(result.last());
  15340. break;
  15341. }
  15342. case 8: {
  15343. result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop);
  15344. result.append(result.last());
  15345. break;
  15346. }
  15347. case 9: { // in this case we need another distinction of cases: segment may pass below or
  15348. // above rect, requiring either bottom right or top left corner points
  15349. if ((value - prevValue) / (key - prevKey) * (rectLeft - key) + value
  15350. < rectBottom) // segment passes below R
  15351. {
  15352. result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom);
  15353. result.append(result.last());
  15354. result << coordsToPixels(rectRight, rectBottom);
  15355. } else {
  15356. result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop);
  15357. result.append(result.last());
  15358. result << coordsToPixels(rectRight, rectBottom);
  15359. }
  15360. break;
  15361. }
  15362. }
  15363. break;
  15364. }
  15365. case 2: {
  15366. switch (currentRegion) {
  15367. case 1: {
  15368. result << coordsToPixels(rectLeft, rectTop);
  15369. break;
  15370. }
  15371. case 3: {
  15372. result << coordsToPixels(rectLeft, rectBottom);
  15373. break;
  15374. }
  15375. case 4: {
  15376. result << coordsToPixels(rectLeft, rectTop);
  15377. result.append(result.last());
  15378. break;
  15379. }
  15380. case 6: {
  15381. result << coordsToPixels(rectLeft, rectBottom);
  15382. result.append(result.last());
  15383. break;
  15384. }
  15385. case 7: {
  15386. result << coordsToPixels(rectLeft, rectTop);
  15387. result.append(result.last());
  15388. result << coordsToPixels(rectRight, rectTop);
  15389. break;
  15390. }
  15391. case 9: {
  15392. result << coordsToPixels(rectLeft, rectBottom);
  15393. result.append(result.last());
  15394. result << coordsToPixels(rectRight, rectBottom);
  15395. break;
  15396. }
  15397. }
  15398. break;
  15399. }
  15400. case 3: {
  15401. switch (currentRegion) {
  15402. case 2: {
  15403. result << coordsToPixels(rectLeft, rectBottom);
  15404. break;
  15405. }
  15406. case 6: {
  15407. result << coordsToPixels(rectLeft, rectBottom);
  15408. break;
  15409. }
  15410. case 1: {
  15411. result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop);
  15412. break;
  15413. }
  15414. case 9: {
  15415. result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom);
  15416. break;
  15417. }
  15418. case 4: {
  15419. result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop);
  15420. result.append(result.last());
  15421. break;
  15422. }
  15423. case 8: {
  15424. result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom);
  15425. result.append(result.last());
  15426. break;
  15427. }
  15428. case 7: { // in this case we need another distinction of cases: segment may pass below or
  15429. // above rect, requiring either bottom right or top left corner points
  15430. if ((value - prevValue) / (key - prevKey) * (rectRight - key) + value
  15431. < rectBottom) // segment passes below R
  15432. {
  15433. result << coordsToPixels(rectLeft, rectBottom)
  15434. << coordsToPixels(rectRight, rectBottom);
  15435. result.append(result.last());
  15436. result << coordsToPixels(rectRight, rectTop);
  15437. } else {
  15438. result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop);
  15439. result.append(result.last());
  15440. result << coordsToPixels(rectRight, rectTop);
  15441. }
  15442. break;
  15443. }
  15444. }
  15445. break;
  15446. }
  15447. case 4: {
  15448. switch (currentRegion) {
  15449. case 1: {
  15450. result << coordsToPixels(rectLeft, rectTop);
  15451. break;
  15452. }
  15453. case 7: {
  15454. result << coordsToPixels(rectRight, rectTop);
  15455. break;
  15456. }
  15457. case 2: {
  15458. result << coordsToPixels(rectLeft, rectTop);
  15459. result.append(result.last());
  15460. break;
  15461. }
  15462. case 8: {
  15463. result << coordsToPixels(rectRight, rectTop);
  15464. result.append(result.last());
  15465. break;
  15466. }
  15467. case 3: {
  15468. result << coordsToPixels(rectLeft, rectTop);
  15469. result.append(result.last());
  15470. result << coordsToPixels(rectLeft, rectBottom);
  15471. break;
  15472. }
  15473. case 9: {
  15474. result << coordsToPixels(rectRight, rectTop);
  15475. result.append(result.last());
  15476. result << coordsToPixels(rectRight, rectBottom);
  15477. break;
  15478. }
  15479. }
  15480. break;
  15481. }
  15482. case 5: {
  15483. switch (currentRegion) {
  15484. case 1: {
  15485. result << coordsToPixels(rectLeft, rectTop);
  15486. break;
  15487. }
  15488. case 7: {
  15489. result << coordsToPixels(rectRight, rectTop);
  15490. break;
  15491. }
  15492. case 9: {
  15493. result << coordsToPixels(rectRight, rectBottom);
  15494. break;
  15495. }
  15496. case 3: {
  15497. result << coordsToPixels(rectLeft, rectBottom);
  15498. break;
  15499. }
  15500. }
  15501. break;
  15502. }
  15503. case 6: {
  15504. switch (currentRegion) {
  15505. case 3: {
  15506. result << coordsToPixels(rectLeft, rectBottom);
  15507. break;
  15508. }
  15509. case 9: {
  15510. result << coordsToPixels(rectRight, rectBottom);
  15511. break;
  15512. }
  15513. case 2: {
  15514. result << coordsToPixels(rectLeft, rectBottom);
  15515. result.append(result.last());
  15516. break;
  15517. }
  15518. case 8: {
  15519. result << coordsToPixels(rectRight, rectBottom);
  15520. result.append(result.last());
  15521. break;
  15522. }
  15523. case 1: {
  15524. result << coordsToPixels(rectLeft, rectBottom);
  15525. result.append(result.last());
  15526. result << coordsToPixels(rectLeft, rectTop);
  15527. break;
  15528. }
  15529. case 7: {
  15530. result << coordsToPixels(rectRight, rectBottom);
  15531. result.append(result.last());
  15532. result << coordsToPixels(rectRight, rectTop);
  15533. break;
  15534. }
  15535. }
  15536. break;
  15537. }
  15538. case 7: {
  15539. switch (currentRegion) {
  15540. case 4: {
  15541. result << coordsToPixels(rectRight, rectTop);
  15542. break;
  15543. }
  15544. case 8: {
  15545. result << coordsToPixels(rectRight, rectTop);
  15546. break;
  15547. }
  15548. case 1: {
  15549. result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop);
  15550. break;
  15551. }
  15552. case 9: {
  15553. result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom);
  15554. break;
  15555. }
  15556. case 2: {
  15557. result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop);
  15558. result.append(result.last());
  15559. break;
  15560. }
  15561. case 6: {
  15562. result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom);
  15563. result.append(result.last());
  15564. break;
  15565. }
  15566. case 3: { // in this case we need another distinction of cases: segment may pass below or
  15567. // above rect, requiring either bottom right or top left corner points
  15568. if ((value - prevValue) / (key - prevKey) * (rectRight - key) + value
  15569. < rectBottom) // segment passes below R
  15570. {
  15571. result << coordsToPixels(rectRight, rectTop)
  15572. << coordsToPixels(rectRight, rectBottom);
  15573. result.append(result.last());
  15574. result << coordsToPixels(rectLeft, rectBottom);
  15575. } else {
  15576. result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop);
  15577. result.append(result.last());
  15578. result << coordsToPixels(rectLeft, rectBottom);
  15579. }
  15580. break;
  15581. }
  15582. }
  15583. break;
  15584. }
  15585. case 8: {
  15586. switch (currentRegion) {
  15587. case 7: {
  15588. result << coordsToPixels(rectRight, rectTop);
  15589. break;
  15590. }
  15591. case 9: {
  15592. result << coordsToPixels(rectRight, rectBottom);
  15593. break;
  15594. }
  15595. case 4: {
  15596. result << coordsToPixels(rectRight, rectTop);
  15597. result.append(result.last());
  15598. break;
  15599. }
  15600. case 6: {
  15601. result << coordsToPixels(rectRight, rectBottom);
  15602. result.append(result.last());
  15603. break;
  15604. }
  15605. case 1: {
  15606. result << coordsToPixels(rectRight, rectTop);
  15607. result.append(result.last());
  15608. result << coordsToPixels(rectLeft, rectTop);
  15609. break;
  15610. }
  15611. case 3: {
  15612. result << coordsToPixels(rectRight, rectBottom);
  15613. result.append(result.last());
  15614. result << coordsToPixels(rectLeft, rectBottom);
  15615. break;
  15616. }
  15617. }
  15618. break;
  15619. }
  15620. case 9: {
  15621. switch (currentRegion) {
  15622. case 6: {
  15623. result << coordsToPixels(rectRight, rectBottom);
  15624. break;
  15625. }
  15626. case 8: {
  15627. result << coordsToPixels(rectRight, rectBottom);
  15628. break;
  15629. }
  15630. case 3: {
  15631. result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom);
  15632. break;
  15633. }
  15634. case 7: {
  15635. result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop);
  15636. break;
  15637. }
  15638. case 2: {
  15639. result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom);
  15640. result.append(result.last());
  15641. break;
  15642. }
  15643. case 4: {
  15644. result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop);
  15645. result.append(result.last());
  15646. break;
  15647. }
  15648. case 1: { // in this case we need another distinction of cases: segment may pass below or
  15649. // above rect, requiring either bottom right or top left corner points
  15650. if ((value - prevValue) / (key - prevKey) * (rectLeft - key) + value
  15651. < rectBottom) // segment passes below R
  15652. {
  15653. result << coordsToPixels(rectRight, rectBottom)
  15654. << coordsToPixels(rectLeft, rectBottom);
  15655. result.append(result.last());
  15656. result << coordsToPixels(rectLeft, rectTop);
  15657. } else {
  15658. result << coordsToPixels(rectRight, rectBottom)
  15659. << coordsToPixels(rectRight, rectTop);
  15660. result.append(result.last());
  15661. result << coordsToPixels(rectLeft, rectTop);
  15662. }
  15663. break;
  15664. }
  15665. }
  15666. break;
  15667. }
  15668. }
  15669. return result;
  15670. }
  15671. /*! \internal
  15672. This function is part of the curve optimization algorithm of \ref getCurveData.
  15673. This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref
  15674. getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion
  15675. nor \a currentRegion is 5 itself.
  15676. If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the
  15677. segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref
  15678. getTraverse).
  15679. */
  15680. bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const
  15681. {
  15682. switch (prevRegion) {
  15683. case 1: {
  15684. switch (currentRegion) {
  15685. case 4:
  15686. case 7:
  15687. case 2:
  15688. case 3:
  15689. return false;
  15690. default:
  15691. return true;
  15692. }
  15693. }
  15694. case 2: {
  15695. switch (currentRegion) {
  15696. case 1:
  15697. case 3:
  15698. return false;
  15699. default:
  15700. return true;
  15701. }
  15702. }
  15703. case 3: {
  15704. switch (currentRegion) {
  15705. case 1:
  15706. case 2:
  15707. case 6:
  15708. case 9:
  15709. return false;
  15710. default:
  15711. return true;
  15712. }
  15713. }
  15714. case 4: {
  15715. switch (currentRegion) {
  15716. case 1:
  15717. case 7:
  15718. return false;
  15719. default:
  15720. return true;
  15721. }
  15722. }
  15723. case 5:
  15724. return false; // should never occur
  15725. case 6: {
  15726. switch (currentRegion) {
  15727. case 3:
  15728. case 9:
  15729. return false;
  15730. default:
  15731. return true;
  15732. }
  15733. }
  15734. case 7: {
  15735. switch (currentRegion) {
  15736. case 1:
  15737. case 4:
  15738. case 8:
  15739. case 9:
  15740. return false;
  15741. default:
  15742. return true;
  15743. }
  15744. }
  15745. case 8: {
  15746. switch (currentRegion) {
  15747. case 7:
  15748. case 9:
  15749. return false;
  15750. default:
  15751. return true;
  15752. }
  15753. }
  15754. case 9: {
  15755. switch (currentRegion) {
  15756. case 3:
  15757. case 6:
  15758. case 8:
  15759. case 7:
  15760. return false;
  15761. default:
  15762. return true;
  15763. }
  15764. }
  15765. default:
  15766. return true;
  15767. }
  15768. }
  15769. /*! \internal
  15770. This function is part of the curve optimization algorithm of \ref getCurveData.
  15771. This method assumes that the \ref mayTraverse test has returned true, so there is a chance the
  15772. segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible
  15773. region 5.
  15774. The return value of this method indicates whether the segment actually traverses region 5 or not.
  15775. If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and
  15776. exit points of region 5. They will become the optimized points for that segment.
  15777. */
  15778. bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value,
  15779. double rectLeft, double rectTop, double rectRight, double rectBottom,
  15780. QPointF& crossA, QPointF& crossB) const
  15781. {
  15782. QList<QPointF> intersections; // x of QPointF corresponds to key and y to value
  15783. if (qFuzzyIsNull(key - prevKey)) // line is parallel to value axis
  15784. {
  15785. // due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is
  15786. // traversed here
  15787. intersections.append(
  15788. QPointF(key, rectBottom)); // direction will be taken care of at end of method
  15789. intersections.append(QPointF(key, rectTop));
  15790. } else if (qFuzzyIsNull(value - prevValue)) // line is parallel to key axis
  15791. {
  15792. // due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is
  15793. // traversed here
  15794. intersections.append(
  15795. QPointF(rectLeft, value)); // direction will be taken care of at end of method
  15796. intersections.append(QPointF(rectRight, value));
  15797. } else // line is skewed
  15798. {
  15799. double gamma;
  15800. double keyPerValue = (key - prevKey) / (value - prevValue);
  15801. // check top of rect:
  15802. gamma = prevKey + (rectTop - prevValue) * keyPerValue;
  15803. if (gamma >= rectLeft && gamma <= rectRight)
  15804. intersections.append(QPointF(gamma, rectTop));
  15805. // check bottom of rect:
  15806. gamma = prevKey + (rectBottom - prevValue) * keyPerValue;
  15807. if (gamma >= rectLeft && gamma <= rectRight)
  15808. intersections.append(QPointF(gamma, rectBottom));
  15809. double valuePerKey = 1.0 / keyPerValue;
  15810. // check left of rect:
  15811. gamma = prevValue + (rectLeft - prevKey) * valuePerKey;
  15812. if (gamma >= rectBottom && gamma <= rectTop)
  15813. intersections.append(QPointF(rectLeft, gamma));
  15814. // check right of rect:
  15815. gamma = prevValue + (rectRight - prevKey) * valuePerKey;
  15816. if (gamma >= rectBottom && gamma <= rectTop)
  15817. intersections.append(QPointF(rectRight, gamma));
  15818. }
  15819. // handle cases where found points isn't exactly 2:
  15820. if (intersections.size() > 2) {
  15821. // line probably goes through corner of rect, and we got duplicate points there. single out
  15822. // the point pair with greatest distance in between:
  15823. double distSqrMax = 0;
  15824. QPointF pv1, pv2;
  15825. for (int i = 0; i < intersections.size() - 1; ++i) {
  15826. for (int k = i + 1; k < intersections.size(); ++k) {
  15827. QPointF distPoint = intersections.at(i) - intersections.at(k);
  15828. double distSqr = distPoint.x() * distPoint.x() + distPoint.y() + distPoint.y();
  15829. if (distSqr > distSqrMax) {
  15830. pv1 = intersections.at(i);
  15831. pv2 = intersections.at(k);
  15832. distSqrMax = distSqr;
  15833. }
  15834. }
  15835. }
  15836. intersections = QList<QPointF>() << pv1 << pv2;
  15837. } else if (intersections.size() != 2) {
  15838. // one or even zero points found (shouldn't happen unless line perfectly tangent to corner),
  15839. // no need to draw segment
  15840. return false;
  15841. }
  15842. // possibly re-sort points so optimized point segment has same direction as original segment:
  15843. if ((key - prevKey) * (intersections.at(1).x() - intersections.at(0).x())
  15844. + (value - prevValue) * (intersections.at(1).y() - intersections.at(0).y())
  15845. < 0) // scalar product of both segments < 0 -> opposite direction
  15846. intersections.move(0, 1);
  15847. crossA = coordsToPixels(intersections.at(0).x(), intersections.at(0).y());
  15848. crossB = coordsToPixels(intersections.at(1).x(), intersections.at(1).y());
  15849. return true;
  15850. }
  15851. /*! \internal
  15852. This function is part of the curve optimization algorithm of \ref getCurveData.
  15853. This method assumes that the \ref getTraverse test has returned true, so the segment definitely
  15854. traverses the visible region 5 when going from \a prevRegion to \a currentRegion.
  15855. In certain situations it is not sufficient to merely generate the entry and exit points of the
  15856. segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment,
  15857. in addition to traversing region 5, skips another region outside of region 5, which makes it
  15858. necessary to add an optimized corner point there (very similar to the job \ref
  15859. getOptimizedCornerPoints does for segments that are completely in outside regions and don't
  15860. traverse 5).
  15861. As an example, consider a segment going from region 1 to region 6, traversing the lower left
  15862. corner of region 5. In this configuration, the segment additionally crosses the border between
  15863. region 1 and 2 before entering region 5. This makes it necessary to add an additional point in
  15864. the top left corner, before adding the optimized traverse points. So in this case, the output
  15865. parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be
  15866. empty.
  15867. In some cases, such as when going from region 1 to 9, it may even be necessary to add additional
  15868. corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse
  15869. return the respective corner points.
  15870. */
  15871. void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double rectLeft,
  15872. double rectTop, double rectRight, double rectBottom,
  15873. QVector<QPointF>& beforeTraverse,
  15874. QVector<QPointF>& afterTraverse) const
  15875. {
  15876. switch (prevRegion) {
  15877. case 1: {
  15878. switch (currentRegion) {
  15879. case 6: {
  15880. beforeTraverse << coordsToPixels(rectLeft, rectTop);
  15881. break;
  15882. }
  15883. case 9: {
  15884. beforeTraverse << coordsToPixels(rectLeft, rectTop);
  15885. afterTraverse << coordsToPixels(rectRight, rectBottom);
  15886. break;
  15887. }
  15888. case 8: {
  15889. beforeTraverse << coordsToPixels(rectLeft, rectTop);
  15890. break;
  15891. }
  15892. }
  15893. break;
  15894. }
  15895. case 2: {
  15896. switch (currentRegion) {
  15897. case 7: {
  15898. afterTraverse << coordsToPixels(rectRight, rectTop);
  15899. break;
  15900. }
  15901. case 9: {
  15902. afterTraverse << coordsToPixels(rectRight, rectBottom);
  15903. break;
  15904. }
  15905. }
  15906. break;
  15907. }
  15908. case 3: {
  15909. switch (currentRegion) {
  15910. case 4: {
  15911. beforeTraverse << coordsToPixels(rectLeft, rectBottom);
  15912. break;
  15913. }
  15914. case 7: {
  15915. beforeTraverse << coordsToPixels(rectLeft, rectBottom);
  15916. afterTraverse << coordsToPixels(rectRight, rectTop);
  15917. break;
  15918. }
  15919. case 8: {
  15920. beforeTraverse << coordsToPixels(rectLeft, rectBottom);
  15921. break;
  15922. }
  15923. }
  15924. break;
  15925. }
  15926. case 4: {
  15927. switch (currentRegion) {
  15928. case 3: {
  15929. afterTraverse << coordsToPixels(rectLeft, rectBottom);
  15930. break;
  15931. }
  15932. case 9: {
  15933. afterTraverse << coordsToPixels(rectRight, rectBottom);
  15934. break;
  15935. }
  15936. }
  15937. break;
  15938. }
  15939. case 5: {
  15940. break;
  15941. } // shouldn't happen because this method only handles full traverses
  15942. case 6: {
  15943. switch (currentRegion) {
  15944. case 1: {
  15945. afterTraverse << coordsToPixels(rectLeft, rectTop);
  15946. break;
  15947. }
  15948. case 7: {
  15949. afterTraverse << coordsToPixels(rectRight, rectTop);
  15950. break;
  15951. }
  15952. }
  15953. break;
  15954. }
  15955. case 7: {
  15956. switch (currentRegion) {
  15957. case 2: {
  15958. beforeTraverse << coordsToPixels(rectRight, rectTop);
  15959. break;
  15960. }
  15961. case 3: {
  15962. beforeTraverse << coordsToPixels(rectRight, rectTop);
  15963. afterTraverse << coordsToPixels(rectLeft, rectBottom);
  15964. break;
  15965. }
  15966. case 6: {
  15967. beforeTraverse << coordsToPixels(rectRight, rectTop);
  15968. break;
  15969. }
  15970. }
  15971. break;
  15972. }
  15973. case 8: {
  15974. switch (currentRegion) {
  15975. case 1: {
  15976. afterTraverse << coordsToPixels(rectLeft, rectTop);
  15977. break;
  15978. }
  15979. case 3: {
  15980. afterTraverse << coordsToPixels(rectLeft, rectBottom);
  15981. break;
  15982. }
  15983. }
  15984. break;
  15985. }
  15986. case 9: {
  15987. switch (currentRegion) {
  15988. case 2: {
  15989. beforeTraverse << coordsToPixels(rectRight, rectBottom);
  15990. break;
  15991. }
  15992. case 1: {
  15993. beforeTraverse << coordsToPixels(rectRight, rectBottom);
  15994. afterTraverse << coordsToPixels(rectLeft, rectTop);
  15995. break;
  15996. }
  15997. case 4: {
  15998. beforeTraverse << coordsToPixels(rectRight, rectBottom);
  15999. break;
  16000. }
  16001. }
  16002. break;
  16003. }
  16004. }
  16005. }
  16006. /*! \internal
  16007. Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a
  16008. pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in
  16009. \ref selectTest.
  16010. */
  16011. double QCPCurve::pointDistance(const QPointF& pixelPoint) const
  16012. {
  16013. if (mData->isEmpty()) {
  16014. qDebug() << Q_FUNC_INFO << "requested point distance on curve" << mName << "without data";
  16015. return 500;
  16016. }
  16017. if (mData->size() == 1) {
  16018. QPointF dataPoint =
  16019. coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value);
  16020. return QVector2D(dataPoint - pixelPoint).length();
  16021. }
  16022. // calculate minimum distance to line segments:
  16023. QVector<QPointF>* lineData = new QVector<QPointF>;
  16024. getCurveData(lineData);
  16025. double minDistSqr = std::numeric_limits<double>::max();
  16026. for (int i = 0; i < lineData->size() - 1; ++i) {
  16027. double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i + 1), pixelPoint);
  16028. if (currentDistSqr < minDistSqr)
  16029. minDistSqr = currentDistSqr;
  16030. }
  16031. delete lineData;
  16032. return qSqrt(minDistSqr);
  16033. }
  16034. /* inherits documentation from base class */
  16035. QCPRange QCPCurve::getKeyRange(bool& foundRange, SignDomain inSignDomain) const
  16036. {
  16037. QCPRange range;
  16038. bool haveLower = false;
  16039. bool haveUpper = false;
  16040. double current;
  16041. QCPCurveDataMap::const_iterator it = mData->constBegin();
  16042. while (it != mData->constEnd()) {
  16043. current = it.value().key;
  16044. if (!qIsNaN(current) && !qIsNaN(it.value().value)) {
  16045. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0)
  16046. || (inSignDomain == sdPositive && current > 0)) {
  16047. if (current < range.lower || !haveLower) {
  16048. range.lower = current;
  16049. haveLower = true;
  16050. }
  16051. if (current > range.upper || !haveUpper) {
  16052. range.upper = current;
  16053. haveUpper = true;
  16054. }
  16055. }
  16056. }
  16057. ++it;
  16058. }
  16059. foundRange = haveLower && haveUpper;
  16060. return range;
  16061. }
  16062. /* inherits documentation from base class */
  16063. QCPRange QCPCurve::getValueRange(bool& foundRange, SignDomain inSignDomain) const
  16064. {
  16065. QCPRange range;
  16066. bool haveLower = false;
  16067. bool haveUpper = false;
  16068. double current;
  16069. QCPCurveDataMap::const_iterator it = mData->constBegin();
  16070. while (it != mData->constEnd()) {
  16071. current = it.value().value;
  16072. if (!qIsNaN(current) && !qIsNaN(it.value().key)) {
  16073. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0)
  16074. || (inSignDomain == sdPositive && current > 0)) {
  16075. if (current < range.lower || !haveLower) {
  16076. range.lower = current;
  16077. haveLower = true;
  16078. }
  16079. if (current > range.upper || !haveUpper) {
  16080. range.upper = current;
  16081. haveUpper = true;
  16082. }
  16083. }
  16084. }
  16085. ++it;
  16086. }
  16087. foundRange = haveLower && haveUpper;
  16088. return range;
  16089. }
  16090. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16091. //////////////////// QCPBarsGroup
  16092. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16093. /*! \class QCPBarsGroup
  16094. \brief Groups multiple QCPBars together so they appear side by side
  16095. \image html QCPBarsGroup.png
  16096. When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable
  16097. to have them appearing next to each other at each key. This is what adding the respective QCPBars
  16098. plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each
  16099. other, see \ref QCPBars::moveAbove.)
  16100. \section qcpbarsgroup-usage Usage
  16101. To add a QCPBars plottable to the group, create a new group and then add the respective bars
  16102. intances:
  16103. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation
  16104. Alternatively to appending to the group like shown above, you can also set the group on the
  16105. QCPBars plottable via \ref QCPBars::setBarsGroup.
  16106. The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The
  16107. bars in this group appear in the plot in the order they were appended. To insert a bars plottable
  16108. at a certain index position, or to reposition a bars plottable which is already in the group, use
  16109. \ref insert.
  16110. To remove specific bars from the group, use either \ref remove or call \ref
  16111. QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable.
  16112. To clear the entire group, call \ref clear, or simply delete the group.
  16113. \section qcpbarsgroup-example Example
  16114. The image above is generated with the following code:
  16115. \snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example
  16116. */
  16117. /* start of documentation of inline functions */
  16118. /*! \fn QList<QCPBars*> QCPBarsGroup::bars() const
  16119. Returns all bars currently in this group.
  16120. \see bars(int index)
  16121. */
  16122. /*! \fn int QCPBarsGroup::size() const
  16123. Returns the number of QCPBars plottables that are part of this group.
  16124. */
  16125. /*! \fn bool QCPBarsGroup::isEmpty() const
  16126. Returns whether this bars group is empty.
  16127. \see size
  16128. */
  16129. /*! \fn bool QCPBarsGroup::contains(QCPBars *bars)
  16130. Returns whether the specified \a bars plottable is part of this group.
  16131. */
  16132. /* end of documentation of inline functions */
  16133. /*!
  16134. Constructs a new bars group for the specified QCustomPlot instance.
  16135. */
  16136. QCPBarsGroup::QCPBarsGroup(QCustomPlot* parentPlot)
  16137. : QObject(parentPlot), mParentPlot(parentPlot), mSpacingType(stAbsolute), mSpacing(4)
  16138. {}
  16139. QCPBarsGroup::~QCPBarsGroup()
  16140. {
  16141. clear();
  16142. }
  16143. /*!
  16144. Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType.
  16145. The actual spacing can then be specified with \ref setSpacing.
  16146. \see setSpacing
  16147. */
  16148. void QCPBarsGroup::setSpacingType(SpacingType spacingType)
  16149. {
  16150. mSpacingType = spacingType;
  16151. }
  16152. /*!
  16153. Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is
  16154. defined by the current \ref SpacingType, which can be set with \ref setSpacingType.
  16155. \see setSpacingType
  16156. */
  16157. void QCPBarsGroup::setSpacing(double spacing)
  16158. {
  16159. mSpacing = spacing;
  16160. }
  16161. /*!
  16162. Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars
  16163. exists, returns 0.
  16164. \see bars(), size
  16165. */
  16166. QCPBars* QCPBarsGroup::bars(int index) const
  16167. {
  16168. if (index >= 0 && index < mBars.size()) {
  16169. return mBars.at(index);
  16170. } else {
  16171. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  16172. return 0;
  16173. }
  16174. }
  16175. /*!
  16176. Removes all QCPBars plottables from this group.
  16177. \see isEmpty
  16178. */
  16179. void QCPBarsGroup::clear()
  16180. {
  16181. foreach (QCPBars* bars, mBars) // since foreach takes a copy, removing bars in the loop is okay
  16182. bars->setBarsGroup(0); // removes itself via removeBars
  16183. }
  16184. /*!
  16185. Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref
  16186. QCPBars::setBarsGroup on the \a bars instance.
  16187. \see insert, remove
  16188. */
  16189. void QCPBarsGroup::append(QCPBars* bars)
  16190. {
  16191. if (!bars) {
  16192. qDebug() << Q_FUNC_INFO << "bars is 0";
  16193. return;
  16194. }
  16195. if (!mBars.contains(bars))
  16196. bars->setBarsGroup(this);
  16197. else
  16198. qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:"
  16199. << reinterpret_cast<quintptr>(bars);
  16200. }
  16201. /*!
  16202. Inserts the specified \a bars plottable into this group at the specified index position \a i.
  16203. This gives you full control over the ordering of the bars.
  16204. \a bars may already be part of this group. In that case, \a bars is just moved to the new index
  16205. position.
  16206. \see append, remove
  16207. */
  16208. void QCPBarsGroup::insert(int i, QCPBars* bars)
  16209. {
  16210. if (!bars) {
  16211. qDebug() << Q_FUNC_INFO << "bars is 0";
  16212. return;
  16213. }
  16214. // first append to bars list normally:
  16215. if (!mBars.contains(bars))
  16216. bars->setBarsGroup(this);
  16217. // then move to according position:
  16218. mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size() - 1));
  16219. }
  16220. /*!
  16221. Removes the specified \a bars plottable from this group.
  16222. \see contains, clear
  16223. */
  16224. void QCPBarsGroup::remove(QCPBars* bars)
  16225. {
  16226. if (!bars) {
  16227. qDebug() << Q_FUNC_INFO << "bars is 0";
  16228. return;
  16229. }
  16230. if (mBars.contains(bars))
  16231. bars->setBarsGroup(0);
  16232. else
  16233. qDebug() << Q_FUNC_INFO
  16234. << "bars plottable is not in this bars group:" << reinterpret_cast<quintptr>(bars);
  16235. }
  16236. /*! \internal
  16237. Adds the specified \a bars to the internal mBars list of bars. This method does not change the
  16238. barsGroup property on \a bars.
  16239. \see unregisterBars
  16240. */
  16241. void QCPBarsGroup::registerBars(QCPBars* bars)
  16242. {
  16243. if (!mBars.contains(bars))
  16244. mBars.append(bars);
  16245. }
  16246. /*! \internal
  16247. Removes the specified \a bars from the internal mBars list of bars. This method does not change
  16248. the barsGroup property on \a bars.
  16249. \see registerBars
  16250. */
  16251. void QCPBarsGroup::unregisterBars(QCPBars* bars)
  16252. {
  16253. mBars.removeOne(bars);
  16254. }
  16255. /*! \internal
  16256. Returns the pixel offset in the key dimension the specified \a bars plottable should have at the
  16257. given key coordinate \a keyCoord. The offset is relative to the pixel position of the key
  16258. coordinate \a keyCoord.
  16259. */
  16260. double QCPBarsGroup::keyPixelOffset(const QCPBars* bars, double keyCoord)
  16261. {
  16262. // find list of all base bars in case some mBars are stacked:
  16263. QList<const QCPBars*> baseBars;
  16264. foreach (const QCPBars* b, mBars) {
  16265. while (b->barBelow())
  16266. b = b->barBelow();
  16267. if (!baseBars.contains(b))
  16268. baseBars.append(b);
  16269. }
  16270. // find base bar this "bars" is stacked on:
  16271. const QCPBars* thisBase = bars;
  16272. while (thisBase->barBelow())
  16273. thisBase = thisBase->barBelow();
  16274. // determine key pixel offset of this base bars considering all other base bars in this
  16275. // barsgroup:
  16276. double result = 0;
  16277. int index = baseBars.indexOf(thisBase);
  16278. if (index >= 0) {
  16279. int startIndex;
  16280. double lowerPixelWidth, upperPixelWidth;
  16281. if (baseBars.size() % 2 == 1
  16282. && index == (baseBars.size() - 1) / 2) // is center bar (int division on purpose)
  16283. {
  16284. return result;
  16285. } else if (index < (baseBars.size() - 1) / 2.0) // bar is to the left of center
  16286. {
  16287. if (baseBars.size() % 2 == 0) // even number of bars
  16288. {
  16289. startIndex = baseBars.size() / 2 - 1;
  16290. result -= getPixelSpacing(baseBars.at(startIndex), keyCoord)
  16291. * 0.5; // half of middle spacing
  16292. } else // uneven number of bars
  16293. {
  16294. startIndex = (baseBars.size() - 1) / 2 - 1;
  16295. baseBars.at((baseBars.size() - 1) / 2)
  16296. ->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  16297. result -= qAbs(upperPixelWidth - lowerPixelWidth) * 0.5; // half of center bar
  16298. result -= getPixelSpacing(baseBars.at((baseBars.size() - 1) / 2),
  16299. keyCoord); // center bar spacing
  16300. }
  16301. for (int i = startIndex; i > index;
  16302. --i) // add widths and spacings of bars in between center and our bars
  16303. {
  16304. baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  16305. result -= qAbs(upperPixelWidth - lowerPixelWidth);
  16306. result -= getPixelSpacing(baseBars.at(i), keyCoord);
  16307. }
  16308. // finally half of our bars width:
  16309. baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  16310. result -= qAbs(upperPixelWidth - lowerPixelWidth) * 0.5;
  16311. } else // bar is to the right of center
  16312. {
  16313. if (baseBars.size() % 2 == 0) // even number of bars
  16314. {
  16315. startIndex = baseBars.size() / 2;
  16316. result += getPixelSpacing(baseBars.at(startIndex), keyCoord)
  16317. * 0.5; // half of middle spacing
  16318. } else // uneven number of bars
  16319. {
  16320. startIndex = (baseBars.size() - 1) / 2 + 1;
  16321. baseBars.at((baseBars.size() - 1) / 2)
  16322. ->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  16323. result += qAbs(upperPixelWidth - lowerPixelWidth) * 0.5; // half of center bar
  16324. result += getPixelSpacing(baseBars.at((baseBars.size() - 1) / 2),
  16325. keyCoord); // center bar spacing
  16326. }
  16327. for (int i = startIndex; i < index;
  16328. ++i) // add widths and spacings of bars in between center and our bars
  16329. {
  16330. baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  16331. result += qAbs(upperPixelWidth - lowerPixelWidth);
  16332. result += getPixelSpacing(baseBars.at(i), keyCoord);
  16333. }
  16334. // finally half of our bars width:
  16335. baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  16336. result += qAbs(upperPixelWidth - lowerPixelWidth) * 0.5;
  16337. }
  16338. }
  16339. return result;
  16340. }
  16341. /*! \internal
  16342. Returns the spacing in pixels which is between this \a bars and the following one, both at the
  16343. key coordinate \a keyCoord.
  16344. \note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only
  16345. needed to get acces to the key axis transformation and axis rect for the modes \ref
  16346. stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in
  16347. \ref stPlotCoords on a logarithmic axis.
  16348. */
  16349. double QCPBarsGroup::getPixelSpacing(const QCPBars* bars, double keyCoord)
  16350. {
  16351. switch (mSpacingType) {
  16352. case stAbsolute: {
  16353. return mSpacing;
  16354. }
  16355. case stAxisRectRatio: {
  16356. if (bars->keyAxis()->orientation() == Qt::Horizontal)
  16357. return bars->keyAxis()->axisRect()->width() * mSpacing;
  16358. else
  16359. return bars->keyAxis()->axisRect()->height() * mSpacing;
  16360. }
  16361. case stPlotCoords: {
  16362. double keyPixel = bars->keyAxis()->coordToPixel(keyCoord);
  16363. return bars->keyAxis()->coordToPixel(keyCoord + mSpacing) - keyPixel;
  16364. }
  16365. }
  16366. return 0;
  16367. }
  16368. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16369. //////////////////// QCPBarData
  16370. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16371. /*! \class QCPBarData
  16372. \brief Holds the data of one single data point (one bar) for QCPBars.
  16373. The container for storing multiple data points is \ref QCPBarDataMap.
  16374. The stored data is:
  16375. \li \a key: coordinate on the key axis of this bar
  16376. \li \a value: height coordinate on the value axis of this bar
  16377. \see QCPBarDataaMap
  16378. */
  16379. /*!
  16380. Constructs a bar data point with key and value set to zero.
  16381. */
  16382. QCPBarData::QCPBarData() : key(0), value(0)
  16383. {}
  16384. /*!
  16385. Constructs a bar data point with the specified \a key and \a value.
  16386. */
  16387. QCPBarData::QCPBarData(double key, double value) : key(key), value(value)
  16388. {}
  16389. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16390. //////////////////// QCPBars
  16391. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16392. /*! \class QCPBars
  16393. \brief A plottable representing a bar chart in a plot.
  16394. \image html QCPBars.png
  16395. To plot data, assign it with the \ref setData or \ref addData functions.
  16396. \section appearance Changing the appearance
  16397. The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush).
  16398. The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth.
  16399. Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other
  16400. (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear
  16401. stacked.
  16402. If you would like to group multiple QCPBars plottables together so they appear side by side as
  16403. shown below, use QCPBarsGroup.
  16404. \image html QCPBarsGroup.png
  16405. \section usage Usage
  16406. Like all data representing objects in QCustomPlot, the QCPBars is a plottable
  16407. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  16408. (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
  16409. Usually, you first create an instance:
  16410. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1
  16411. add it to the customPlot with QCustomPlot::addPlottable:
  16412. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-2
  16413. and then modify the properties of the newly created plottable, e.g.:
  16414. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-3
  16415. */
  16416. /* start of documentation of inline functions */
  16417. /*! \fn QCPBars *QCPBars::barBelow() const
  16418. Returns the bars plottable that is directly below this bars plottable.
  16419. If there is no such plottable, returns 0.
  16420. \see barAbove, moveBelow, moveAbove
  16421. */
  16422. /*! \fn QCPBars *QCPBars::barAbove() const
  16423. Returns the bars plottable that is directly above this bars plottable.
  16424. If there is no such plottable, returns 0.
  16425. \see barBelow, moveBelow, moveAbove
  16426. */
  16427. /* end of documentation of inline functions */
  16428. /*!
  16429. Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  16430. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  16431. the same orientation. If either of these restrictions is violated, a corresponding message is
  16432. printed to the debug output (qDebug), the construction is not aborted, though.
  16433. The constructed QCPBars can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
  16434. then takes ownership of the bar chart.
  16435. */
  16436. QCPBars::QCPBars(QCPAxis* keyAxis, QCPAxis* valueAxis)
  16437. : QCPAbstractPlottable(keyAxis, valueAxis)
  16438. , mData(new QCPBarDataMap)
  16439. , mWidth(0.75)
  16440. , mWidthType(wtPlotCoords)
  16441. , mBarsGroup(0)
  16442. , mBaseValue(0)
  16443. {
  16444. // modify inherited properties from abstract plottable:
  16445. mPen.setColor(Qt::blue);
  16446. mPen.setStyle(Qt::SolidLine);
  16447. mBrush.setColor(QColor(40, 50, 255, 30));
  16448. mBrush.setStyle(Qt::SolidPattern);
  16449. mSelectedPen = mPen;
  16450. mSelectedPen.setWidthF(2.5);
  16451. mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen
  16452. mSelectedBrush = mBrush;
  16453. }
  16454. QCPBars::~QCPBars()
  16455. {
  16456. setBarsGroup(0);
  16457. if (mBarBelow || mBarAbove)
  16458. connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking
  16459. delete mData;
  16460. }
  16461. /*!
  16462. Sets the width of the bars.
  16463. How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...),
  16464. depends on the currently set width type, see \ref setWidthType and \ref WidthType.
  16465. */
  16466. void QCPBars::setWidth(double width)
  16467. {
  16468. mWidth = width;
  16469. }
  16470. /*!
  16471. Sets how the width of the bars is defined. See the documentation of \ref WidthType for an
  16472. explanation of the possible values for \a widthType.
  16473. The default value is \ref wtPlotCoords.
  16474. \see setWidth
  16475. */
  16476. void QCPBars::setWidthType(QCPBars::WidthType widthType)
  16477. {
  16478. mWidthType = widthType;
  16479. }
  16480. /*!
  16481. Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref
  16482. QCPBarsGroup::append.
  16483. To remove this QCPBars from any group, set \a barsGroup to 0.
  16484. */
  16485. void QCPBars::setBarsGroup(QCPBarsGroup* barsGroup)
  16486. {
  16487. // deregister at old group:
  16488. if (mBarsGroup)
  16489. mBarsGroup->unregisterBars(this);
  16490. mBarsGroup = barsGroup;
  16491. // register at new group:
  16492. if (mBarsGroup)
  16493. mBarsGroup->registerBars(this);
  16494. }
  16495. /*!
  16496. Sets the base value of this bars plottable.
  16497. The base value defines where on the value coordinate the bars start. How far the bars extend from
  16498. the base value is given by their individual value data. For example, if the base value is set to
  16499. 1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at
  16500. 3.
  16501. For stacked bars, only the base value of the bottom-most QCPBars has meaning.
  16502. The default base value is 0.
  16503. */
  16504. void QCPBars::setBaseValue(double baseValue)
  16505. {
  16506. mBaseValue = baseValue;
  16507. }
  16508. /*!
  16509. Replaces the current data with the provided \a data.
  16510. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable
  16511. takes ownership of the passed data and replaces the internal data pointer with it. This is
  16512. significantly faster than copying for large datasets.
  16513. */
  16514. void QCPBars::setData(QCPBarDataMap* data, bool copy)
  16515. {
  16516. if (mData == data) {
  16517. qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable"
  16518. << reinterpret_cast<quintptr>(data);
  16519. return;
  16520. }
  16521. if (copy) {
  16522. *mData = *data;
  16523. } else {
  16524. delete mData;
  16525. mData = data;
  16526. }
  16527. }
  16528. /*! \overload
  16529. Replaces the current data with the provided points in \a key and \a value tuples. The
  16530. provided vectors should have equal length. Else, the number of added points will be the size of
  16531. the smallest vector.
  16532. */
  16533. void QCPBars::setData(const QVector<double>& key, const QVector<double>& value)
  16534. {
  16535. mData->clear();
  16536. int n = key.size();
  16537. n = qMin(n, value.size());
  16538. QCPBarData newData;
  16539. for (int i = 0; i < n; ++i) {
  16540. newData.key = key[i];
  16541. newData.value = value[i];
  16542. mData->insertMulti(newData.key, newData);
  16543. }
  16544. }
  16545. /*!
  16546. Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear
  16547. below the bars of \a bars. The move target \a bars must use the same key and value axis as this
  16548. plottable.
  16549. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  16550. has a bars object below itself, this bars object is inserted between the two. If this bars object
  16551. is already between two other bars, the two other bars will be stacked on top of each other after
  16552. the operation.
  16553. To remove this bars plottable from any stacking, set \a bars to 0.
  16554. \see moveBelow, barAbove, barBelow
  16555. */
  16556. void QCPBars::moveBelow(QCPBars* bars)
  16557. {
  16558. if (bars == this)
  16559. return;
  16560. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) {
  16561. qDebug() << Q_FUNC_INFO
  16562. << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  16563. return;
  16564. }
  16565. // remove from stacking:
  16566. connectBars(mBarBelow.data(),
  16567. mBarAbove.data()); // Note: also works if one (or both) of them is 0
  16568. // if new bar given, insert this bar below it:
  16569. if (bars) {
  16570. if (bars->mBarBelow)
  16571. connectBars(bars->mBarBelow.data(), this);
  16572. connectBars(this, bars);
  16573. }
  16574. }
  16575. /*!
  16576. Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear
  16577. above the bars of \a bars. The move target \a bars must use the same key and value axis as this
  16578. plottable.
  16579. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  16580. has a bars object above itself, this bars object is inserted between the two. If this bars object
  16581. is already between two other bars, the two other bars will be stacked on top of each other after
  16582. the operation.
  16583. To remove this bars plottable from any stacking, set \a bars to 0.
  16584. \see moveBelow, barBelow, barAbove
  16585. */
  16586. void QCPBars::moveAbove(QCPBars* bars)
  16587. {
  16588. if (bars == this)
  16589. return;
  16590. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) {
  16591. qDebug() << Q_FUNC_INFO
  16592. << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  16593. return;
  16594. }
  16595. // remove from stacking:
  16596. connectBars(mBarBelow.data(),
  16597. mBarAbove.data()); // Note: also works if one (or both) of them is 0
  16598. // if new bar given, insert this bar above it:
  16599. if (bars) {
  16600. if (bars->mBarAbove)
  16601. connectBars(this, bars->mBarAbove.data());
  16602. connectBars(bars, this);
  16603. }
  16604. }
  16605. /*!
  16606. Adds the provided data points in \a dataMap to the current data.
  16607. \see removeData
  16608. */
  16609. void QCPBars::addData(const QCPBarDataMap& dataMap)
  16610. {
  16611. mData->unite(dataMap);
  16612. }
  16613. /*! \overload
  16614. Adds the provided single data point in \a data to the current data.
  16615. \see removeData
  16616. */
  16617. void QCPBars::addData(const QCPBarData& data)
  16618. {
  16619. mData->insertMulti(data.key, data);
  16620. }
  16621. /*! \overload
  16622. Adds the provided single data point as \a key and \a value tuple to the current data
  16623. \see removeData
  16624. */
  16625. void QCPBars::addData(double key, double value)
  16626. {
  16627. QCPBarData newData;
  16628. newData.key = key;
  16629. newData.value = value;
  16630. mData->insertMulti(newData.key, newData);
  16631. }
  16632. /*! \overload
  16633. Adds the provided data points as \a key and \a value tuples to the current data.
  16634. \see removeData
  16635. */
  16636. void QCPBars::addData(const QVector<double>& keys, const QVector<double>& values)
  16637. {
  16638. int n = keys.size();
  16639. n = qMin(n, values.size());
  16640. QCPBarData newData;
  16641. for (int i = 0; i < n; ++i) {
  16642. newData.key = keys[i];
  16643. newData.value = values[i];
  16644. mData->insertMulti(newData.key, newData);
  16645. }
  16646. }
  16647. /*!
  16648. Removes all data points with key smaller than \a key.
  16649. \see addData, clearData
  16650. */
  16651. void QCPBars::removeDataBefore(double key)
  16652. {
  16653. QCPBarDataMap::iterator it = mData->begin();
  16654. while (it != mData->end() && it.key() < key)
  16655. it = mData->erase(it);
  16656. }
  16657. /*!
  16658. Removes all data points with key greater than \a key.
  16659. \see addData, clearData
  16660. */
  16661. void QCPBars::removeDataAfter(double key)
  16662. {
  16663. if (mData->isEmpty())
  16664. return;
  16665. QCPBarDataMap::iterator it = mData->upperBound(key);
  16666. while (it != mData->end())
  16667. it = mData->erase(it);
  16668. }
  16669. /*!
  16670. Removes all data points with key between \a fromKey and \a toKey. if \a fromKey is
  16671. greater or equal to \a toKey, the function does nothing. To remove a single data point with known
  16672. key, use \ref removeData(double key).
  16673. \see addData, clearData
  16674. */
  16675. void QCPBars::removeData(double fromKey, double toKey)
  16676. {
  16677. if (fromKey >= toKey || mData->isEmpty())
  16678. return;
  16679. QCPBarDataMap::iterator it = mData->upperBound(fromKey);
  16680. QCPBarDataMap::iterator itEnd = mData->upperBound(toKey);
  16681. while (it != itEnd)
  16682. it = mData->erase(it);
  16683. }
  16684. /*! \overload
  16685. Removes a single data point at \a key. If the position is not known with absolute precision,
  16686. consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval
  16687. around the suspected position, depeding on the precision with which the key is known.
  16688. \see addData, clearData
  16689. */
  16690. void QCPBars::removeData(double key)
  16691. {
  16692. mData->remove(key);
  16693. }
  16694. /*!
  16695. Removes all data points.
  16696. \see removeData, removeDataAfter, removeDataBefore
  16697. */
  16698. void QCPBars::clearData()
  16699. {
  16700. mData->clear();
  16701. }
  16702. /* inherits documentation from base class */
  16703. double QCPBars::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  16704. {
  16705. Q_UNUSED(details)
  16706. if (onlySelectable && !mSelectable)
  16707. return -1;
  16708. if (!mKeyAxis || !mValueAxis) {
  16709. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  16710. return -1;
  16711. }
  16712. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) {
  16713. QCPBarDataMap::ConstIterator it;
  16714. for (it = mData->constBegin(); it != mData->constEnd(); ++it) {
  16715. if (getBarPolygon(it.value().key, it.value().value).boundingRect().contains(pos))
  16716. return mParentPlot->selectionTolerance() * 0.99;
  16717. }
  16718. }
  16719. return -1;
  16720. }
  16721. /* inherits documentation from base class */
  16722. void QCPBars::draw(QCPPainter* painter)
  16723. {
  16724. if (!mKeyAxis || !mValueAxis) {
  16725. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  16726. return;
  16727. }
  16728. if (mData->isEmpty())
  16729. return;
  16730. QCPBarDataMap::const_iterator it, lower, upperEnd;
  16731. getVisibleDataBounds(lower, upperEnd);
  16732. for (it = lower; it != upperEnd; ++it) {
  16733. // check data validity if flag set:
  16734. #ifdef QCUSTOMPLOT_CHECK_DATA
  16735. if (QCP::isInvalidData(it.value().key, it.value().value))
  16736. qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "of drawn range invalid."
  16737. << "Plottable name:" << name();
  16738. #endif
  16739. QPolygonF barPolygon = getBarPolygon(it.key(), it.value().value);
  16740. // draw bar fill:
  16741. if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) {
  16742. applyFillAntialiasingHint(painter);
  16743. painter->setPen(Qt::NoPen);
  16744. painter->setBrush(mainBrush());
  16745. painter->drawPolygon(barPolygon);
  16746. }
  16747. // draw bar line:
  16748. if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) {
  16749. applyDefaultAntialiasingHint(painter);
  16750. painter->setPen(mainPen());
  16751. painter->setBrush(Qt::NoBrush);
  16752. painter->drawPolyline(barPolygon);
  16753. }
  16754. }
  16755. }
  16756. /* inherits documentation from base class */
  16757. void QCPBars::drawLegendIcon(QCPPainter* painter, const QRectF& rect) const
  16758. {
  16759. // draw filled rect:
  16760. applyDefaultAntialiasingHint(painter);
  16761. painter->setBrush(mBrush);
  16762. painter->setPen(mPen);
  16763. QRectF r = QRectF(0, 0, rect.width() * 0.67, rect.height() * 0.67);
  16764. r.moveCenter(rect.center());
  16765. painter->drawRect(r);
  16766. }
  16767. /*! \internal
  16768. called by \ref draw to determine which data (key) range is visible at the current key axis range
  16769. setting, so only that needs to be processed. It also takes into account the bar width.
  16770. \a lower returns an iterator to the lowest data point that needs to be taken into account when
  16771. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  16772. lower may still be just outside the visible range.
  16773. \a upperEnd returns an iterator one higher than the highest visible data point. Same as before, \a
  16774. upperEnd may also lie just outside of the visible range.
  16775. if the bars plottable contains no data, both \a lower and \a upperEnd point to constEnd.
  16776. */
  16777. void QCPBars::getVisibleDataBounds(QCPBarDataMap::const_iterator& lower,
  16778. QCPBarDataMap::const_iterator& upperEnd) const
  16779. {
  16780. if (!mKeyAxis) {
  16781. qDebug() << Q_FUNC_INFO << "invalid key axis";
  16782. return;
  16783. }
  16784. if (mData->isEmpty()) {
  16785. lower = mData->constEnd();
  16786. upperEnd = mData->constEnd();
  16787. return;
  16788. }
  16789. // get visible data range as QMap iterators
  16790. lower = mData->lowerBound(mKeyAxis.data()->range().lower);
  16791. upperEnd = mData->upperBound(mKeyAxis.data()->range().upper);
  16792. double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower);
  16793. double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper);
  16794. bool isVisible = false;
  16795. // walk left from lbound to find lower bar that actually is completely outside visible pixel
  16796. // range:
  16797. QCPBarDataMap::const_iterator it = lower;
  16798. while (it != mData->constBegin()) {
  16799. --it;
  16800. QRectF barBounds = getBarPolygon(it.value().key, it.value().value).boundingRect();
  16801. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  16802. isVisible =
  16803. ((!mKeyAxis.data()->rangeReversed() && barBounds.right() >= lowerPixelBound)
  16804. || (mKeyAxis.data()->rangeReversed() && barBounds.left() <= lowerPixelBound));
  16805. else // keyaxis is vertical
  16806. isVisible =
  16807. ((!mKeyAxis.data()->rangeReversed() && barBounds.top() <= lowerPixelBound)
  16808. || (mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= lowerPixelBound));
  16809. if (isVisible)
  16810. lower = it;
  16811. else
  16812. break;
  16813. }
  16814. // walk right from ubound to find upper bar that actually is completely outside visible pixel
  16815. // range:
  16816. it = upperEnd;
  16817. while (it != mData->constEnd()) {
  16818. QRectF barBounds =
  16819. getBarPolygon(upperEnd.value().key, upperEnd.value().value).boundingRect();
  16820. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  16821. isVisible =
  16822. ((!mKeyAxis.data()->rangeReversed() && barBounds.left() <= upperPixelBound)
  16823. || (mKeyAxis.data()->rangeReversed() && barBounds.right() >= upperPixelBound));
  16824. else // keyaxis is vertical
  16825. isVisible =
  16826. ((!mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= upperPixelBound)
  16827. || (mKeyAxis.data()->rangeReversed() && barBounds.top() <= upperPixelBound));
  16828. if (isVisible)
  16829. upperEnd = it + 1;
  16830. else
  16831. break;
  16832. ++it;
  16833. }
  16834. }
  16835. /*! \internal
  16836. Returns the polygon of a single bar with \a key and \a value. The Polygon is open at the bottom
  16837. and shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref
  16838. setBaseValue).
  16839. */
  16840. QPolygonF QCPBars::getBarPolygon(double key, double value) const
  16841. {
  16842. QCPAxis* keyAxis = mKeyAxis.data();
  16843. QCPAxis* valueAxis = mValueAxis.data();
  16844. if (!keyAxis || !valueAxis) {
  16845. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  16846. return QPolygonF();
  16847. }
  16848. QPolygonF result;
  16849. double lowerPixelWidth, upperPixelWidth;
  16850. getPixelWidth(key, lowerPixelWidth, upperPixelWidth);
  16851. double base = getStackedBaseValue(key, value >= 0);
  16852. double basePixel = valueAxis->coordToPixel(base);
  16853. double valuePixel = valueAxis->coordToPixel(base + value);
  16854. double keyPixel = keyAxis->coordToPixel(key);
  16855. if (mBarsGroup)
  16856. keyPixel += mBarsGroup->keyPixelOffset(this, key);
  16857. if (keyAxis->orientation() == Qt::Horizontal) {
  16858. result << QPointF(keyPixel + lowerPixelWidth, basePixel);
  16859. result << QPointF(keyPixel + lowerPixelWidth, valuePixel);
  16860. result << QPointF(keyPixel + upperPixelWidth, valuePixel);
  16861. result << QPointF(keyPixel + upperPixelWidth, basePixel);
  16862. } else {
  16863. result << QPointF(basePixel, keyPixel + lowerPixelWidth);
  16864. result << QPointF(valuePixel, keyPixel + lowerPixelWidth);
  16865. result << QPointF(valuePixel, keyPixel + upperPixelWidth);
  16866. result << QPointF(basePixel, keyPixel + upperPixelWidth);
  16867. }
  16868. return result;
  16869. }
  16870. /*! \internal
  16871. This function is used to determine the width of the bar at coordinate \a key, according to the
  16872. specified width (\ref setWidth) and width type (\ref setWidthType).
  16873. The output parameters \a lower and \a upper return the number of pixels the bar extends to lower
  16874. and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a
  16875. lower is negative and \a upper positive).
  16876. */
  16877. void QCPBars::getPixelWidth(double key, double& lower, double& upper) const
  16878. {
  16879. switch (mWidthType) {
  16880. case wtAbsolute: {
  16881. upper = mWidth * 0.5;
  16882. lower = -upper;
  16883. if (mKeyAxis
  16884. && (mKeyAxis.data()->rangeReversed()
  16885. ^ (mKeyAxis.data()->orientation() == Qt::Vertical)))
  16886. qSwap(lower, upper);
  16887. break;
  16888. }
  16889. case wtAxisRectRatio: {
  16890. if (mKeyAxis && mKeyAxis.data()->axisRect()) {
  16891. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  16892. upper = mKeyAxis.data()->axisRect()->width() * mWidth * 0.5;
  16893. else
  16894. upper = mKeyAxis.data()->axisRect()->height() * mWidth * 0.5;
  16895. lower = -upper;
  16896. if (mKeyAxis
  16897. && (mKeyAxis.data()->rangeReversed()
  16898. ^ (mKeyAxis.data()->orientation() == Qt::Vertical)))
  16899. qSwap(lower, upper);
  16900. } else
  16901. qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
  16902. break;
  16903. }
  16904. case wtPlotCoords: {
  16905. if (mKeyAxis) {
  16906. double keyPixel = mKeyAxis.data()->coordToPixel(key);
  16907. upper = mKeyAxis.data()->coordToPixel(key + mWidth * 0.5) - keyPixel;
  16908. lower = mKeyAxis.data()->coordToPixel(key - mWidth * 0.5) - keyPixel;
  16909. // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained
  16910. // by coordinate transform which includes range direction
  16911. } else
  16912. qDebug() << Q_FUNC_INFO << "No key axis defined";
  16913. break;
  16914. }
  16915. }
  16916. }
  16917. /*! \internal
  16918. This function is called to find at which value to start drawing the base of a bar at \a key, when
  16919. it is stacked on top of another QCPBars (e.g. with \ref moveAbove).
  16920. positive and negative bars are separated per stack (positive are stacked above baseValue upwards,
  16921. negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the
  16922. bar for which we need the base value is negative, set \a positive to false.
  16923. */
  16924. double QCPBars::getStackedBaseValue(double key, bool positive) const
  16925. {
  16926. if (mBarBelow) {
  16927. double max = 0; // don't use mBaseValue here because only base value of bottom-most bar has
  16928. // meaning in a bar stack
  16929. // find bars of mBarBelow that are approximately at key and find largest one:
  16930. double epsilon =
  16931. qAbs(key) * 1e-6; // should be safe even when changed to use float at some point
  16932. if (key == 0)
  16933. epsilon = 1e-6;
  16934. QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound(key - epsilon);
  16935. QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound(key + epsilon);
  16936. while (it != itEnd) {
  16937. if ((positive && it.value().value > max) || (!positive && it.value().value < max))
  16938. max = it.value().value;
  16939. ++it;
  16940. }
  16941. // recurse down the bar-stack to find the total height:
  16942. return max + mBarBelow.data()->getStackedBaseValue(key, positive);
  16943. } else
  16944. return mBaseValue;
  16945. }
  16946. /*! \internal
  16947. Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s)
  16948. currently above lower and below upper will become disconnected to lower/upper.
  16949. If lower is zero, upper will be disconnected at the bottom.
  16950. If upper is zero, lower will be disconnected at the top.
  16951. */
  16952. void QCPBars::connectBars(QCPBars* lower, QCPBars* upper)
  16953. {
  16954. if (!lower && !upper)
  16955. return;
  16956. if (!lower) // disconnect upper at bottom
  16957. {
  16958. // disconnect old bar below upper:
  16959. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  16960. upper->mBarBelow.data()->mBarAbove = 0;
  16961. upper->mBarBelow = 0;
  16962. } else if (!upper) // disconnect lower at top
  16963. {
  16964. // disconnect old bar above lower:
  16965. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  16966. lower->mBarAbove.data()->mBarBelow = 0;
  16967. lower->mBarAbove = 0;
  16968. } else // connect lower and upper
  16969. {
  16970. // disconnect old bar above lower:
  16971. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  16972. lower->mBarAbove.data()->mBarBelow = 0;
  16973. // disconnect old bar below upper:
  16974. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  16975. upper->mBarBelow.data()->mBarAbove = 0;
  16976. lower->mBarAbove = upper;
  16977. upper->mBarBelow = lower;
  16978. }
  16979. }
  16980. /* inherits documentation from base class */
  16981. QCPRange QCPBars::getKeyRange(bool& foundRange, SignDomain inSignDomain) const
  16982. {
  16983. QCPRange range;
  16984. bool haveLower = false;
  16985. bool haveUpper = false;
  16986. double current;
  16987. QCPBarDataMap::const_iterator it = mData->constBegin();
  16988. while (it != mData->constEnd()) {
  16989. current = it.value().key;
  16990. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0)
  16991. || (inSignDomain == sdPositive && current > 0)) {
  16992. if (current < range.lower || !haveLower) {
  16993. range.lower = current;
  16994. haveLower = true;
  16995. }
  16996. if (current > range.upper || !haveUpper) {
  16997. range.upper = current;
  16998. haveUpper = true;
  16999. }
  17000. }
  17001. ++it;
  17002. }
  17003. // determine exact range of bars by including bar width and barsgroup offset:
  17004. if (haveLower && mKeyAxis) {
  17005. double lowerPixelWidth, upperPixelWidth, keyPixel;
  17006. getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth);
  17007. keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth;
  17008. if (mBarsGroup)
  17009. keyPixel += mBarsGroup->keyPixelOffset(this, range.lower);
  17010. range.lower = mKeyAxis.data()->pixelToCoord(keyPixel);
  17011. }
  17012. if (haveUpper && mKeyAxis) {
  17013. double lowerPixelWidth, upperPixelWidth, keyPixel;
  17014. getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth);
  17015. keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth;
  17016. if (mBarsGroup)
  17017. keyPixel += mBarsGroup->keyPixelOffset(this, range.upper);
  17018. range.upper = mKeyAxis.data()->pixelToCoord(keyPixel);
  17019. }
  17020. foundRange = haveLower && haveUpper;
  17021. return range;
  17022. }
  17023. /* inherits documentation from base class */
  17024. QCPRange QCPBars::getValueRange(bool& foundRange, SignDomain inSignDomain) const
  17025. {
  17026. QCPRange range;
  17027. range.lower = mBaseValue;
  17028. range.upper = mBaseValue;
  17029. bool haveLower = true; // set to true, because baseValue should always be visible in bar charts
  17030. bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts
  17031. double current;
  17032. QCPBarDataMap::const_iterator it = mData->constBegin();
  17033. while (it != mData->constEnd()) {
  17034. current = it.value().value + getStackedBaseValue(it.value().key, it.value().value >= 0);
  17035. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0)
  17036. || (inSignDomain == sdPositive && current > 0)) {
  17037. if (current < range.lower || !haveLower) {
  17038. range.lower = current;
  17039. haveLower = true;
  17040. }
  17041. if (current > range.upper || !haveUpper) {
  17042. range.upper = current;
  17043. haveUpper = true;
  17044. }
  17045. }
  17046. ++it;
  17047. }
  17048. foundRange = true; // return true because bar charts always have the 0-line visible
  17049. return range;
  17050. }
  17051. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17052. //////////////////// QCPStatisticalBox
  17053. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17054. /*! \class QCPStatisticalBox
  17055. \brief A plottable representing a single statistical box in a plot.
  17056. \image html QCPStatisticalBox.png
  17057. To plot data, assign it with the individual parameter functions or use \ref setData to set all
  17058. parameters at once. The individual functions are:
  17059. \li \ref setMinimum
  17060. \li \ref setLowerQuartile
  17061. \li \ref setMedian
  17062. \li \ref setUpperQuartile
  17063. \li \ref setMaximum
  17064. Additionally you can define a list of outliers, drawn as scatter datapoints:
  17065. \li \ref setOutliers
  17066. \section appearance Changing the appearance
  17067. The appearance of the box itself is controlled via \ref setPen and \ref setBrush. You may change
  17068. the width of the box with \ref setWidth in plot coordinates (not pixels).
  17069. Analog functions exist for the minimum/maximum-whiskers: \ref setWhiskerPen, \ref
  17070. setWhiskerBarPen, \ref setWhiskerWidth. The whisker width is the width of the bar at the top
  17071. (maximum) and bottom (minimum).
  17072. The median indicator line has its own pen, \ref setMedianPen.
  17073. If the whisker backbone pen is changed, make sure to set the capStyle to Qt::FlatCap. Else, the
  17074. backbone line might exceed the whisker bars by a few pixels due to the pen cap being not
  17075. perfectly flat.
  17076. The Outlier data points are drawn as normal scatter points. Their look can be controlled with
  17077. \ref setOutlierStyle
  17078. \section usage Usage
  17079. Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable.
  17080. Usually, you first create an instance and add it to the customPlot:
  17081. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1
  17082. and then modify the properties of the newly created plottable, e.g.:
  17083. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-2
  17084. */
  17085. /*!
  17086. Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its
  17087. value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and
  17088. not have the same orientation. If either of these restrictions is violated, a corresponding
  17089. message is printed to the debug output (qDebug), the construction is not aborted, though.
  17090. The constructed statistical box can be added to the plot with QCustomPlot::addPlottable,
  17091. QCustomPlot then takes ownership of the statistical box.
  17092. */
  17093. QCPStatisticalBox::QCPStatisticalBox(QCPAxis* keyAxis, QCPAxis* valueAxis)
  17094. : QCPAbstractPlottable(keyAxis, valueAxis)
  17095. , mKey(0)
  17096. , mMinimum(0)
  17097. , mLowerQuartile(0)
  17098. , mMedian(0)
  17099. , mUpperQuartile(0)
  17100. , mMaximum(0)
  17101. {
  17102. setOutlierStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, 6));
  17103. setWhiskerWidth(0.2);
  17104. setWidth(0.5);
  17105. setPen(QPen(Qt::black));
  17106. setSelectedPen(QPen(Qt::blue, 2.5));
  17107. setMedianPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap));
  17108. setWhiskerPen(QPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap));
  17109. setWhiskerBarPen(QPen(Qt::black));
  17110. setBrush(Qt::NoBrush);
  17111. setSelectedBrush(Qt::NoBrush);
  17112. }
  17113. /*!
  17114. Sets the key coordinate of the statistical box.
  17115. */
  17116. void QCPStatisticalBox::setKey(double key)
  17117. {
  17118. mKey = key;
  17119. }
  17120. /*!
  17121. Sets the parameter "minimum" of the statistical box plot. This is the position of the lower
  17122. whisker, typically the minimum measurement of the sample that's not considered an outlier.
  17123. \see setMaximum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth
  17124. */
  17125. void QCPStatisticalBox::setMinimum(double value)
  17126. {
  17127. mMinimum = value;
  17128. }
  17129. /*!
  17130. Sets the parameter "lower Quartile" of the statistical box plot. This is the lower end of the
  17131. box. The lower and the upper quartiles are the two statistical quartiles around the median of the
  17132. sample, they contain 50% of the sample data.
  17133. \see setUpperQuartile, setPen, setBrush, setWidth
  17134. */
  17135. void QCPStatisticalBox::setLowerQuartile(double value)
  17136. {
  17137. mLowerQuartile = value;
  17138. }
  17139. /*!
  17140. Sets the parameter "median" of the statistical box plot. This is the value of the median mark
  17141. inside the quartile box. The median separates the sample data in half (50% of the sample data is
  17142. below/above the median).
  17143. \see setMedianPen
  17144. */
  17145. void QCPStatisticalBox::setMedian(double value)
  17146. {
  17147. mMedian = value;
  17148. }
  17149. /*!
  17150. Sets the parameter "upper Quartile" of the statistical box plot. This is the upper end of the
  17151. box. The lower and the upper quartiles are the two statistical quartiles around the median of the
  17152. sample, they contain 50% of the sample data.
  17153. \see setLowerQuartile, setPen, setBrush, setWidth
  17154. */
  17155. void QCPStatisticalBox::setUpperQuartile(double value)
  17156. {
  17157. mUpperQuartile = value;
  17158. }
  17159. /*!
  17160. Sets the parameter "maximum" of the statistical box plot. This is the position of the upper
  17161. whisker, typically the maximum measurement of the sample that's not considered an outlier.
  17162. \see setMinimum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth
  17163. */
  17164. void QCPStatisticalBox::setMaximum(double value)
  17165. {
  17166. mMaximum = value;
  17167. }
  17168. /*!
  17169. Sets a vector of outlier values that will be drawn as scatters. Any data points in the sample
  17170. that are not within the whiskers (\ref setMinimum, \ref setMaximum) should be considered outliers
  17171. and displayed as such.
  17172. \see setOutlierStyle
  17173. */
  17174. void QCPStatisticalBox::setOutliers(const QVector<double>& values)
  17175. {
  17176. mOutliers = values;
  17177. }
  17178. /*!
  17179. Sets all parameters of the statistical box plot at once.
  17180. \see setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, setMaximum
  17181. */
  17182. void QCPStatisticalBox::setData(double key, double minimum, double lowerQuartile, double median,
  17183. double upperQuartile, double maximum)
  17184. {
  17185. setKey(key);
  17186. setMinimum(minimum);
  17187. setLowerQuartile(lowerQuartile);
  17188. setMedian(median);
  17189. setUpperQuartile(upperQuartile);
  17190. setMaximum(maximum);
  17191. }
  17192. /*!
  17193. Sets the width of the box in key coordinates.
  17194. \see setWhiskerWidth
  17195. */
  17196. void QCPStatisticalBox::setWidth(double width)
  17197. {
  17198. mWidth = width;
  17199. }
  17200. /*!
  17201. Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key coordinates.
  17202. \see setWidth
  17203. */
  17204. void QCPStatisticalBox::setWhiskerWidth(double width)
  17205. {
  17206. mWhiskerWidth = width;
  17207. }
  17208. /*!
  17209. Sets the pen used for drawing the whisker backbone (That's the line parallel to the value axis).
  17210. Make sure to set the \a pen capStyle to Qt::FlatCap to prevent the whisker backbone from reaching
  17211. a few pixels past the whisker bars, when using a non-zero pen width.
  17212. \see setWhiskerBarPen
  17213. */
  17214. void QCPStatisticalBox::setWhiskerPen(const QPen& pen)
  17215. {
  17216. mWhiskerPen = pen;
  17217. }
  17218. /*!
  17219. Sets the pen used for drawing the whisker bars (Those are the lines parallel to the key axis at
  17220. each end of the whisker backbone).
  17221. \see setWhiskerPen
  17222. */
  17223. void QCPStatisticalBox::setWhiskerBarPen(const QPen& pen)
  17224. {
  17225. mWhiskerBarPen = pen;
  17226. }
  17227. /*!
  17228. Sets the pen used for drawing the median indicator line inside the statistical box.
  17229. */
  17230. void QCPStatisticalBox::setMedianPen(const QPen& pen)
  17231. {
  17232. mMedianPen = pen;
  17233. }
  17234. /*!
  17235. Sets the appearance of the outlier data points.
  17236. \see setOutliers
  17237. */
  17238. void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle& style)
  17239. {
  17240. mOutlierStyle = style;
  17241. }
  17242. /* inherits documentation from base class */
  17243. void QCPStatisticalBox::clearData()
  17244. {
  17245. setOutliers(QVector<double>());
  17246. setKey(0);
  17247. setMinimum(0);
  17248. setLowerQuartile(0);
  17249. setMedian(0);
  17250. setUpperQuartile(0);
  17251. setMaximum(0);
  17252. }
  17253. /* inherits documentation from base class */
  17254. double QCPStatisticalBox::selectTest(const QPointF& pos, bool onlySelectable,
  17255. QVariant* details) const
  17256. {
  17257. Q_UNUSED(details)
  17258. if (onlySelectable && !mSelectable)
  17259. return -1;
  17260. if (!mKeyAxis || !mValueAxis) {
  17261. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  17262. return -1;
  17263. }
  17264. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) {
  17265. double posKey, posValue;
  17266. pixelsToCoords(pos, posKey, posValue);
  17267. // quartile box:
  17268. QCPRange keyRange(mKey - mWidth * 0.5, mKey + mWidth * 0.5);
  17269. QCPRange valueRange(mLowerQuartile, mUpperQuartile);
  17270. if (keyRange.contains(posKey) && valueRange.contains(posValue))
  17271. return mParentPlot->selectionTolerance() * 0.99;
  17272. // min/max whiskers:
  17273. if (QCPRange(mMinimum, mMaximum).contains(posValue))
  17274. return qAbs(mKeyAxis.data()->coordToPixel(mKey)
  17275. - mKeyAxis.data()->coordToPixel(posKey));
  17276. }
  17277. return -1;
  17278. }
  17279. /* inherits documentation from base class */
  17280. void QCPStatisticalBox::draw(QCPPainter* painter)
  17281. {
  17282. if (!mKeyAxis || !mValueAxis) {
  17283. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  17284. return;
  17285. }
  17286. // check data validity if flag set:
  17287. #ifdef QCUSTOMPLOT_CHECK_DATA
  17288. if (QCP::isInvalidData(mKey, mMedian) || QCP::isInvalidData(mLowerQuartile, mUpperQuartile)
  17289. || QCP::isInvalidData(mMinimum, mMaximum))
  17290. qDebug() << Q_FUNC_INFO << "Data point at" << mKey << "of drawn range has invalid data."
  17291. << "Plottable name:" << name();
  17292. for (int i = 0; i < mOutliers.size(); ++i)
  17293. if (QCP::isInvalidData(mOutliers.at(i)))
  17294. qDebug() << Q_FUNC_INFO << "Data point outlier at" << mKey << "of drawn range invalid."
  17295. << "Plottable name:" << name();
  17296. #endif
  17297. QRectF quartileBox;
  17298. drawQuartileBox(painter, &quartileBox);
  17299. painter->save();
  17300. painter->setClipRect(quartileBox, Qt::IntersectClip);
  17301. drawMedian(painter);
  17302. painter->restore();
  17303. drawWhiskers(painter);
  17304. drawOutliers(painter);
  17305. }
  17306. /* inherits documentation from base class */
  17307. void QCPStatisticalBox::drawLegendIcon(QCPPainter* painter, const QRectF& rect) const
  17308. {
  17309. // draw filled rect:
  17310. applyDefaultAntialiasingHint(painter);
  17311. painter->setPen(mPen);
  17312. painter->setBrush(mBrush);
  17313. QRectF r = QRectF(0, 0, rect.width() * 0.67, rect.height() * 0.67);
  17314. r.moveCenter(rect.center());
  17315. painter->drawRect(r);
  17316. }
  17317. /*! \internal
  17318. Draws the quartile box. \a box is an output parameter that returns the quartile box (in pixel
  17319. coordinates) which is used to set the clip rect of the painter before calling \ref drawMedian (so
  17320. the median doesn't draw outside the quartile box).
  17321. */
  17322. void QCPStatisticalBox::drawQuartileBox(QCPPainter* painter, QRectF* quartileBox) const
  17323. {
  17324. QRectF box;
  17325. box.setTopLeft(coordsToPixels(mKey - mWidth * 0.5, mUpperQuartile));
  17326. box.setBottomRight(coordsToPixels(mKey + mWidth * 0.5, mLowerQuartile));
  17327. applyDefaultAntialiasingHint(painter);
  17328. painter->setPen(mainPen());
  17329. painter->setBrush(mainBrush());
  17330. painter->drawRect(box);
  17331. if (quartileBox)
  17332. *quartileBox = box;
  17333. }
  17334. /*! \internal
  17335. Draws the median line inside the quartile box.
  17336. */
  17337. void QCPStatisticalBox::drawMedian(QCPPainter* painter) const
  17338. {
  17339. QLineF medianLine;
  17340. medianLine.setP1(coordsToPixels(mKey - mWidth * 0.5, mMedian));
  17341. medianLine.setP2(coordsToPixels(mKey + mWidth * 0.5, mMedian));
  17342. applyDefaultAntialiasingHint(painter);
  17343. painter->setPen(mMedianPen);
  17344. painter->drawLine(medianLine);
  17345. }
  17346. /*! \internal
  17347. Draws both whisker backbones and bars.
  17348. */
  17349. void QCPStatisticalBox::drawWhiskers(QCPPainter* painter) const
  17350. {
  17351. QLineF backboneMin, backboneMax, barMin, barMax;
  17352. backboneMax.setPoints(coordsToPixels(mKey, mUpperQuartile), coordsToPixels(mKey, mMaximum));
  17353. backboneMin.setPoints(coordsToPixels(mKey, mLowerQuartile), coordsToPixels(mKey, mMinimum));
  17354. barMax.setPoints(coordsToPixels(mKey - mWhiskerWidth * 0.5, mMaximum),
  17355. coordsToPixels(mKey + mWhiskerWidth * 0.5, mMaximum));
  17356. barMin.setPoints(coordsToPixels(mKey - mWhiskerWidth * 0.5, mMinimum),
  17357. coordsToPixels(mKey + mWhiskerWidth * 0.5, mMinimum));
  17358. applyErrorBarsAntialiasingHint(painter);
  17359. painter->setPen(mWhiskerPen);
  17360. painter->drawLine(backboneMin);
  17361. painter->drawLine(backboneMax);
  17362. painter->setPen(mWhiskerBarPen);
  17363. painter->drawLine(barMin);
  17364. painter->drawLine(barMax);
  17365. }
  17366. /*! \internal
  17367. Draws the outlier scatter points.
  17368. */
  17369. void QCPStatisticalBox::drawOutliers(QCPPainter* painter) const
  17370. {
  17371. applyScattersAntialiasingHint(painter);
  17372. mOutlierStyle.applyTo(painter, mPen);
  17373. for (int i = 0; i < mOutliers.size(); ++i)
  17374. mOutlierStyle.drawShape(painter, coordsToPixels(mKey, mOutliers.at(i)));
  17375. }
  17376. /* inherits documentation from base class */
  17377. QCPRange QCPStatisticalBox::getKeyRange(bool& foundRange, SignDomain inSignDomain) const
  17378. {
  17379. foundRange = true;
  17380. if (inSignDomain == sdBoth) {
  17381. return QCPRange(mKey - mWidth * 0.5, mKey + mWidth * 0.5);
  17382. } else if (inSignDomain == sdNegative) {
  17383. if (mKey + mWidth * 0.5 < 0)
  17384. return QCPRange(mKey - mWidth * 0.5, mKey + mWidth * 0.5);
  17385. else if (mKey < 0)
  17386. return QCPRange(mKey - mWidth * 0.5, mKey);
  17387. else {
  17388. foundRange = false;
  17389. return QCPRange();
  17390. }
  17391. } else if (inSignDomain == sdPositive) {
  17392. if (mKey - mWidth * 0.5 > 0)
  17393. return QCPRange(mKey - mWidth * 0.5, mKey + mWidth * 0.5);
  17394. else if (mKey > 0)
  17395. return QCPRange(mKey, mKey + mWidth * 0.5);
  17396. else {
  17397. foundRange = false;
  17398. return QCPRange();
  17399. }
  17400. }
  17401. foundRange = false;
  17402. return QCPRange();
  17403. }
  17404. /* inherits documentation from base class */
  17405. QCPRange QCPStatisticalBox::getValueRange(bool& foundRange, SignDomain inSignDomain) const
  17406. {
  17407. QVector<double>
  17408. values; // values that must be considered (i.e. all outliers and the five box-parameters)
  17409. values.reserve(mOutliers.size() + 5);
  17410. values << mMaximum << mUpperQuartile << mMedian << mLowerQuartile << mMinimum;
  17411. values << mOutliers;
  17412. // go through values and find the ones in legal range:
  17413. bool haveUpper = false;
  17414. bool haveLower = false;
  17415. double upper = 0;
  17416. double lower = 0;
  17417. for (int i = 0; i < values.size(); ++i) {
  17418. if ((inSignDomain == sdNegative && values.at(i) < 0)
  17419. || (inSignDomain == sdPositive && values.at(i) > 0) || (inSignDomain == sdBoth)) {
  17420. if (values.at(i) > upper || !haveUpper) {
  17421. upper = values.at(i);
  17422. haveUpper = true;
  17423. }
  17424. if (values.at(i) < lower || !haveLower) {
  17425. lower = values.at(i);
  17426. haveLower = true;
  17427. }
  17428. }
  17429. }
  17430. // return the bounds if we found some sensible values:
  17431. if (haveLower && haveUpper) {
  17432. foundRange = true;
  17433. return QCPRange(lower, upper);
  17434. } else // might happen if all values are in other sign domain
  17435. {
  17436. foundRange = false;
  17437. return QCPRange();
  17438. }
  17439. }
  17440. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17441. //////////////////// QCPColorMapData
  17442. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17443. /*! \class QCPColorMapData
  17444. \brief Holds the two-dimensional data of a QCPColorMap plottable.
  17445. This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref
  17446. QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a
  17447. color, depending on the value.
  17448. The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize).
  17449. Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref
  17450. setKeyRange, \ref setValueRange).
  17451. The data cells can be accessed in two ways: They can be directly addressed by an integer index
  17452. with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot
  17453. coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are
  17454. provided by the functions \ref coordToCell and \ref cellToCoord.
  17455. This class also buffers the minimum and maximum values that are in the data set, to provide
  17456. QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value
  17457. that is greater than the current maximum increases this maximum to the new value. However,
  17458. setting the cell that currently holds the maximum value to a smaller value doesn't decrease the
  17459. maximum again, because finding the true new maximum would require going through the entire data
  17460. array, which might be time consuming. The same holds for the data minimum. This functionality is
  17461. given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the
  17462. true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience
  17463. parameter \a recalculateDataBounds which may be set to true to automatically call \ref
  17464. recalculateDataBounds internally.
  17465. */
  17466. /* start of documentation of inline functions */
  17467. /*! \fn bool QCPColorMapData::isEmpty() const
  17468. Returns whether this instance carries no data. This is equivalent to having a size where at least
  17469. one of the dimensions is 0 (see \ref setSize).
  17470. */
  17471. /* end of documentation of inline functions */
  17472. /*!
  17473. Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction
  17474. and \a valueSize cells in the value direction. These cells will be displayed by the \ref
  17475. QCPColorMap at the coordinates \a keyRange and \a valueRange.
  17476. \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange
  17477. */
  17478. QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange& keyRange,
  17479. const QCPRange& valueRange)
  17480. : mKeySize(0)
  17481. , mValueSize(0)
  17482. , mKeyRange(keyRange)
  17483. , mValueRange(valueRange)
  17484. , mIsEmpty(true)
  17485. , mData(0)
  17486. , mDataModified(true)
  17487. {
  17488. setSize(keySize, valueSize);
  17489. fill(0);
  17490. }
  17491. QCPColorMapData::~QCPColorMapData()
  17492. {
  17493. if (mData)
  17494. delete[] mData;
  17495. }
  17496. /*!
  17497. Constructs a new QCPColorMapData instance copying the data and range of \a other.
  17498. */
  17499. QCPColorMapData::QCPColorMapData(const QCPColorMapData& other)
  17500. : mKeySize(0), mValueSize(0), mIsEmpty(true), mData(0), mDataModified(true)
  17501. {
  17502. *this = other;
  17503. }
  17504. /*!
  17505. Overwrites this color map data instance with the data stored in \a other.
  17506. */
  17507. QCPColorMapData& QCPColorMapData::operator=(const QCPColorMapData& other)
  17508. {
  17509. if (&other != this) {
  17510. const int keySize = other.keySize();
  17511. const int valueSize = other.valueSize();
  17512. setSize(keySize, valueSize);
  17513. setRange(other.keyRange(), other.valueRange());
  17514. if (!mIsEmpty)
  17515. memcpy(mData, other.mData, sizeof(mData[0]) * keySize * valueSize);
  17516. mDataBounds = other.mDataBounds;
  17517. mDataModified = true;
  17518. }
  17519. return *this;
  17520. }
  17521. /* undocumented getter */
  17522. double QCPColorMapData::data(double key, double value)
  17523. {
  17524. int keyCell =
  17525. (key - mKeyRange.lower) / (mKeyRange.upper - mKeyRange.lower) * (mKeySize - 1) + 0.5;
  17526. int valueCell =
  17527. (value - mValueRange.lower) / (mValueRange.upper - mValueRange.lower) * (mValueSize - 1)
  17528. + 0.5;
  17529. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  17530. return mData[valueCell * mKeySize + keyCell];
  17531. else
  17532. return 0;
  17533. }
  17534. /* undocumented getter */
  17535. double QCPColorMapData::cell(int keyIndex, int valueIndex)
  17536. {
  17537. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  17538. return mData[valueIndex * mKeySize + keyIndex];
  17539. else
  17540. return 0;
  17541. }
  17542. /*!
  17543. Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in
  17544. the value dimension.
  17545. The current data is discarded and the map cells are set to 0, unless the map had already the
  17546. requested size.
  17547. Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref
  17548. isEmpty returns true.
  17549. \see setRange, setKeySize, setValueSize
  17550. */
  17551. void QCPColorMapData::setSize(int keySize, int valueSize)
  17552. {
  17553. if (keySize != mKeySize || valueSize != mValueSize) {
  17554. mKeySize = keySize;
  17555. mValueSize = valueSize;
  17556. if (mData)
  17557. delete[] mData;
  17558. mIsEmpty = mKeySize == 0 || mValueSize == 0;
  17559. if (!mIsEmpty) {
  17560. #ifdef __EXCEPTIONS
  17561. try { // 2D arrays get memory intensive fast. So if the allocation fails, at least
  17562. // output debug message
  17563. #endif
  17564. mData = new double[mKeySize * mValueSize];
  17565. #ifdef __EXCEPTIONS
  17566. } catch (...) {
  17567. mData = 0;
  17568. }
  17569. #endif
  17570. if (mData)
  17571. fill(0);
  17572. else
  17573. qDebug() << Q_FUNC_INFO << "out of memory for data dimensions " << mKeySize << "*"
  17574. << mValueSize;
  17575. } else
  17576. mData = 0;
  17577. mDataModified = true;
  17578. }
  17579. }
  17580. /*!
  17581. Resizes the data array to have \a keySize cells in the key dimension.
  17582. The current data is discarded and the map cells are set to 0, unless the map had already the
  17583. requested size.
  17584. Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true.
  17585. \see setKeyRange, setSize, setValueSize
  17586. */
  17587. void QCPColorMapData::setKeySize(int keySize)
  17588. {
  17589. setSize(keySize, mValueSize);
  17590. }
  17591. /*!
  17592. Resizes the data array to have \a valueSize cells in the value dimension.
  17593. The current data is discarded and the map cells are set to 0, unless the map had already the
  17594. requested size.
  17595. Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true.
  17596. \see setValueRange, setSize, setKeySize
  17597. */
  17598. void QCPColorMapData::setValueSize(int valueSize)
  17599. {
  17600. setSize(mKeySize, valueSize);
  17601. }
  17602. /*!
  17603. Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area
  17604. covered by the color map in plot coordinates.
  17605. The outer cells will be centered on the range boundaries given to this function. For example, if
  17606. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  17607. be cells centered on the key coordinates 2, 2.5 and 3.
  17608. \see setSize
  17609. */
  17610. void QCPColorMapData::setRange(const QCPRange& keyRange, const QCPRange& valueRange)
  17611. {
  17612. setKeyRange(keyRange);
  17613. setValueRange(valueRange);
  17614. }
  17615. /*!
  17616. Sets the coordinate range the data shall be distributed over in the key dimension. Together with
  17617. the value range, This defines the rectangular area covered by the color map in plot coordinates.
  17618. The outer cells will be centered on the range boundaries given to this function. For example, if
  17619. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  17620. be cells centered on the key coordinates 2, 2.5 and 3.
  17621. \see setRange, setValueRange, setSize
  17622. */
  17623. void QCPColorMapData::setKeyRange(const QCPRange& keyRange)
  17624. {
  17625. mKeyRange = keyRange;
  17626. }
  17627. /*!
  17628. Sets the coordinate range the data shall be distributed over in the value dimension. Together with
  17629. the key range, This defines the rectangular area covered by the color map in plot coordinates.
  17630. The outer cells will be centered on the range boundaries given to this function. For example, if
  17631. the value size (\ref setValueSize) is 3 and \a valueRange is set to <tt>QCPRange(2, 3)</tt> there
  17632. will be cells centered on the value coordinates 2, 2.5 and 3.
  17633. \see setRange, setKeyRange, setSize
  17634. */
  17635. void QCPColorMapData::setValueRange(const QCPRange& valueRange)
  17636. {
  17637. mValueRange = valueRange;
  17638. }
  17639. /*!
  17640. Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a
  17641. z.
  17642. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  17643. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  17644. you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
  17645. determine the cell index. Rather directly access the cell index with \ref
  17646. QCPColorMapData::setCell.
  17647. \see setCell, setRange
  17648. */
  17649. void QCPColorMapData::setData(double key, double value, double z)
  17650. {
  17651. int keyCell =
  17652. (key - mKeyRange.lower) / (mKeyRange.upper - mKeyRange.lower) * (mKeySize - 1) + 0.5;
  17653. int valueCell =
  17654. (value - mValueRange.lower) / (mValueRange.upper - mValueRange.lower) * (mValueSize - 1)
  17655. + 0.5;
  17656. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) {
  17657. mData[valueCell * mKeySize + keyCell] = z;
  17658. if (z < mDataBounds.lower)
  17659. mDataBounds.lower = z;
  17660. if (z > mDataBounds.upper)
  17661. mDataBounds.upper = z;
  17662. mDataModified = true;
  17663. }
  17664. }
  17665. /*!
  17666. Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices
  17667. enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see
  17668. \ref setSize).
  17669. In the standard plot configuration (horizontal key axis and vertical value axis, both not
  17670. range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with
  17671. indices (keySize-1, valueSize-1) is in the top right corner of the color map.
  17672. \see setData, setSize
  17673. */
  17674. void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z)
  17675. {
  17676. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) {
  17677. mData[valueIndex * mKeySize + keyIndex] = z;
  17678. if (z < mDataBounds.lower)
  17679. mDataBounds.lower = z;
  17680. if (z > mDataBounds.upper)
  17681. mDataBounds.upper = z;
  17682. mDataModified = true;
  17683. }
  17684. }
  17685. /*!
  17686. Goes through the data and updates the buffered minimum and maximum data values.
  17687. Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange
  17688. and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten
  17689. with a smaller or larger value respectively, since the buffered maximum/minimum values have been
  17690. updated the last time. Why this is the case is explained in the class description (\ref
  17691. QCPColorMapData).
  17692. Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a
  17693. recalculateDataBounds for convenience. Setting this to true will call this method for you, before
  17694. doing the rescale.
  17695. */
  17696. void QCPColorMapData::recalculateDataBounds()
  17697. {
  17698. if (mKeySize > 0 && mValueSize > 0) {
  17699. double minHeight = mData[0];
  17700. double maxHeight = mData[0];
  17701. const int dataCount = mValueSize * mKeySize;
  17702. for (int i = 0; i < dataCount; ++i) {
  17703. if (mData[i] > maxHeight)
  17704. maxHeight = mData[i];
  17705. if (mData[i] < minHeight)
  17706. minHeight = mData[i];
  17707. }
  17708. mDataBounds.lower = minHeight;
  17709. mDataBounds.upper = maxHeight;
  17710. }
  17711. }
  17712. /*!
  17713. Frees the internal data memory.
  17714. This is equivalent to calling \ref setSize "setSize(0, 0)".
  17715. */
  17716. void QCPColorMapData::clear()
  17717. {
  17718. setSize(0, 0);
  17719. }
  17720. /*!
  17721. Sets all cells to the value \a z.
  17722. */
  17723. void QCPColorMapData::fill(double z)
  17724. {
  17725. const int dataCount = mValueSize * mKeySize;
  17726. for (int i = 0; i < dataCount; ++i)
  17727. mData[i] = z;
  17728. mDataBounds = QCPRange(z, z);
  17729. mDataModified = true;
  17730. }
  17731. /*!
  17732. Transforms plot coordinates given by \a key and \a value to cell indices of this QCPColorMapData
  17733. instance. The resulting cell indices are returned via the output parameters \a keyIndex and \a
  17734. valueIndex.
  17735. The retrieved key/value cell indices can then be used for example with \ref setCell.
  17736. If you are only interested in a key or value index, you may pass 0 as \a valueIndex or \a
  17737. keyIndex.
  17738. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  17739. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  17740. you shouldn't use the \ref QCPColorMapData::coordToCell method as it uses a linear transformation
  17741. to determine the cell index.
  17742. \see cellToCoord, QCPAxis::coordToPixel
  17743. */
  17744. void QCPColorMapData::coordToCell(double key, double value, int* keyIndex, int* valueIndex) const
  17745. {
  17746. if (keyIndex)
  17747. *keyIndex =
  17748. (key - mKeyRange.lower) / (mKeyRange.upper - mKeyRange.lower) * (mKeySize - 1) + 0.5;
  17749. if (valueIndex)
  17750. *valueIndex =
  17751. (value - mValueRange.lower) / (mValueRange.upper - mValueRange.lower) * (mValueSize - 1)
  17752. + 0.5;
  17753. }
  17754. /*!
  17755. Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices of this
  17756. QCPColorMapData instance. The resulting coordinates are returned via the output parameters \a key
  17757. and \a value.
  17758. If you are only interested in a key or value coordinate, you may pass 0 as \a key or \a
  17759. value.
  17760. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  17761. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  17762. you shouldn't use the \ref QCPColorMapData::cellToCoord method as it uses a linear transformation
  17763. to determine the cell index.
  17764. \see coordToCell, QCPAxis::pixelToCoord
  17765. */
  17766. void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double* key, double* value) const
  17767. {
  17768. if (key)
  17769. *key = keyIndex / (double)(mKeySize - 1) * (mKeyRange.upper - mKeyRange.lower)
  17770. + mKeyRange.lower;
  17771. if (value)
  17772. *value = valueIndex / (double)(mValueSize - 1) * (mValueRange.upper - mValueRange.lower)
  17773. + mValueRange.lower;
  17774. }
  17775. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17776. //////////////////// QCPColorMap
  17777. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17778. /*! \class QCPColorMap
  17779. \brief A plottable representing a two-dimensional color map in a plot.
  17780. \image html QCPColorMap.png
  17781. The data is stored in the class \ref QCPColorMapData, which can be accessed via the data()
  17782. method.
  17783. A color map has three dimensions to represent a data point: The \a key dimension, the \a value
  17784. dimension and the \a data dimension. As with other plottables such as graphs, \a key and \a value
  17785. correspond to two orthogonal axes on the QCustomPlot surface that you specify in the QCPColorMap
  17786. constructor. The \a data dimension however is encoded as the color of the point at (\a key, \a
  17787. value).
  17788. Set the number of points (or \a cells) in the key/value dimension via \ref
  17789. QCPColorMapData::setSize. The plot coordinate range over which these points will be displayed is
  17790. specified via \ref QCPColorMapData::setRange. The first cell will be centered on the lower range
  17791. boundary and the last cell will be centered on the upper range boundary. The data can be set by
  17792. either accessing the cells directly with QCPColorMapData::setCell or by addressing the cells via
  17793. their plot coordinates with \ref QCPColorMapData::setData. If possible, you should prefer
  17794. setCell, since it doesn't need to do any coordinate transformation and thus performs a bit
  17795. better.
  17796. The cell with index (0, 0) is at the bottom left, if the color map uses normal (i.e. not reversed)
  17797. key and value axes.
  17798. To show the user which colors correspond to which \a data values, a \ref QCPColorScale is
  17799. typically placed to the right of the axis rect. See the documentation there for details on how to
  17800. add and use a color scale.
  17801. \section appearance Changing the appearance
  17802. The central part of the appearance is the color gradient, which can be specified via \ref
  17803. setGradient. See the documentation of \ref QCPColorGradient for details on configuring a color
  17804. gradient.
  17805. The \a data range that is mapped to the colors of the gradient can be specified with \ref
  17806. setDataRange. To make the data range encompass the whole data set minimum to maximum, call \ref
  17807. rescaleDataRange.
  17808. \section usage Usage
  17809. Like all data representing objects in QCustomPlot, the QCPColorMap is a plottable
  17810. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  17811. (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.)
  17812. Usually, you first create an instance and add it to the customPlot:
  17813. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-1
  17814. and then modify the properties of the newly created color map, e.g.:
  17815. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-2
  17816. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  17817. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  17818. you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
  17819. determine the cell index. Rather directly access the cell index with \ref
  17820. QCPColorMapData::setCell.
  17821. */
  17822. /* start documentation of inline functions */
  17823. /*! \fn QCPColorMapData *QCPColorMap::data() const
  17824. Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to
  17825. modify data points (cells) and the color map key/value range.
  17826. \see setData
  17827. */
  17828. /* end documentation of inline functions */
  17829. /* start documentation of signals */
  17830. /*! \fn void QCPColorMap::dataRangeChanged(QCPRange newRange);
  17831. This signal is emitted when the data range changes.
  17832. \see setDataRange
  17833. */
  17834. /*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  17835. This signal is emitted when the data scale type changes.
  17836. \see setDataScaleType
  17837. */
  17838. /*! \fn void QCPColorMap::gradientChanged(QCPColorGradient newGradient);
  17839. This signal is emitted when the gradient changes.
  17840. \see setGradient
  17841. */
  17842. /* end documentation of signals */
  17843. /*!
  17844. Constructs a color map with the specified \a keyAxis and \a valueAxis.
  17845. The constructed QCPColorMap can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
  17846. then takes ownership of the color map.
  17847. */
  17848. QCPColorMap::QCPColorMap(QCPAxis* keyAxis, QCPAxis* valueAxis)
  17849. : QCPAbstractPlottable(keyAxis, valueAxis)
  17850. , mDataScaleType(QCPAxis::stLinear)
  17851. , mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5)))
  17852. , mInterpolate(true)
  17853. , mTightBoundary(false)
  17854. , mMapImageInvalidated(true)
  17855. {}
  17856. QCPColorMap::~QCPColorMap()
  17857. {
  17858. delete mMapData;
  17859. }
  17860. /*!
  17861. Replaces the current \ref data with the provided \a data.
  17862. If \a copy is set to true, the \a data object will only be copied. if false, the color map
  17863. takes ownership of the passed data and replaces the internal data pointer with it. This is
  17864. significantly faster than copying for large datasets.
  17865. */
  17866. void QCPColorMap::setData(QCPColorMapData* data, bool copy)
  17867. {
  17868. if (mMapData == data) {
  17869. qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable"
  17870. << reinterpret_cast<quintptr>(data);
  17871. return;
  17872. }
  17873. if (copy) {
  17874. *mMapData = *data;
  17875. } else {
  17876. delete mMapData;
  17877. mMapData = data;
  17878. }
  17879. mMapImageInvalidated = true;
  17880. }
  17881. /*!
  17882. Sets the data range of this color map to \a dataRange. The data range defines which data values
  17883. are mapped to the color gradient.
  17884. To make the data range span the full range of the data set, use \ref rescaleDataRange.
  17885. \see QCPColorScale::setDataRange
  17886. */
  17887. void QCPColorMap::setDataRange(const QCPRange& dataRange)
  17888. {
  17889. if (!QCPRange::validRange(dataRange))
  17890. return;
  17891. if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) {
  17892. if (mDataScaleType == QCPAxis::stLogarithmic)
  17893. mDataRange = dataRange.sanitizedForLogScale();
  17894. else
  17895. mDataRange = dataRange.sanitizedForLinScale();
  17896. mMapImageInvalidated = true;
  17897. emit dataRangeChanged(mDataRange);
  17898. }
  17899. }
  17900. /*!
  17901. Sets whether the data is correlated with the color gradient linearly or logarithmically.
  17902. \see QCPColorScale::setDataScaleType
  17903. */
  17904. void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType)
  17905. {
  17906. if (mDataScaleType != scaleType) {
  17907. mDataScaleType = scaleType;
  17908. mMapImageInvalidated = true;
  17909. emit dataScaleTypeChanged(mDataScaleType);
  17910. if (mDataScaleType == QCPAxis::stLogarithmic)
  17911. setDataRange(mDataRange.sanitizedForLogScale());
  17912. }
  17913. }
  17914. /*!
  17915. Sets the color gradient that is used to represent the data. For more details on how to create an
  17916. own gradient or use one of the preset gradients, see \ref QCPColorGradient.
  17917. The colors defined by the gradient will be used to represent data values in the currently set
  17918. data range, see \ref setDataRange. Data points that are outside this data range will either be
  17919. colored uniformly with the respective gradient boundary color, or the gradient will repeat,
  17920. depending on \ref QCPColorGradient::setPeriodic.
  17921. \see QCPColorScale::setGradient
  17922. */
  17923. void QCPColorMap::setGradient(const QCPColorGradient& gradient)
  17924. {
  17925. if (mGradient != gradient) {
  17926. mGradient = gradient;
  17927. mMapImageInvalidated = true;
  17928. emit gradientChanged(mGradient);
  17929. }
  17930. }
  17931. /*!
  17932. Sets whether the color map image shall use bicubic interpolation when displaying the color map
  17933. shrinked or expanded, and not at a 1:1 pixel-to-data scale.
  17934. \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without
  17935. interpolation enabled"
  17936. */
  17937. void QCPColorMap::setInterpolate(bool enabled)
  17938. {
  17939. mInterpolate = enabled;
  17940. mMapImageInvalidated = true; // because oversampling factors might need to change
  17941. }
  17942. /*!
  17943. Sets whether the outer most data rows and columns are clipped to the specified key and value
  17944. range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange).
  17945. if \a enabled is set to false, the data points at the border of the color map are drawn with the
  17946. same width and height as all other data points. Since the data points are represented by
  17947. rectangles of one color centered on the data coordinate, this means that the shown color map
  17948. extends by half a data point over the specified key/value range in each direction.
  17949. \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled"
  17950. */
  17951. void QCPColorMap::setTightBoundary(bool enabled)
  17952. {
  17953. mTightBoundary = enabled;
  17954. }
  17955. /*!
  17956. Associates the color scale \a colorScale with this color map.
  17957. This means that both the color scale and the color map synchronize their gradient, data range and
  17958. data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps
  17959. can be associated with one single color scale. This causes the color maps to also synchronize
  17960. those properties, via the mutual color scale.
  17961. This function causes the color map to adopt the current color gradient, data range and data scale
  17962. type of \a colorScale. After this call, you may change these properties at either the color map
  17963. or the color scale, and the setting will be applied to both.
  17964. Pass 0 as \a colorScale to disconnect the color scale from this color map again.
  17965. */
  17966. void QCPColorMap::setColorScale(QCPColorScale* colorScale)
  17967. {
  17968. if (mColorScale) // unconnect signals from old color scale
  17969. {
  17970. disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(),
  17971. SLOT(setDataRange(QCPRange)));
  17972. disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(),
  17973. SLOT(setDataScaleType(QCPAxis::ScaleType)));
  17974. disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(),
  17975. SLOT(setGradient(QCPColorGradient)));
  17976. disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this,
  17977. SLOT(setDataRange(QCPRange)));
  17978. disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this,
  17979. SLOT(setGradient(QCPColorGradient)));
  17980. disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this,
  17981. SLOT(setDataScaleType(QCPAxis::ScaleType)));
  17982. }
  17983. mColorScale = colorScale;
  17984. if (mColorScale) // connect signals to new color scale
  17985. {
  17986. setGradient(mColorScale.data()->gradient());
  17987. setDataRange(mColorScale.data()->dataRange());
  17988. setDataScaleType(mColorScale.data()->dataScaleType());
  17989. connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(),
  17990. SLOT(setDataRange(QCPRange)));
  17991. connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(),
  17992. SLOT(setDataScaleType(QCPAxis::ScaleType)));
  17993. connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(),
  17994. SLOT(setGradient(QCPColorGradient)));
  17995. connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this,
  17996. SLOT(setDataRange(QCPRange)));
  17997. connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this,
  17998. SLOT(setGradient(QCPColorGradient)));
  17999. connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this,
  18000. SLOT(setDataScaleType(QCPAxis::ScaleType)));
  18001. }
  18002. }
  18003. /*!
  18004. Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the
  18005. current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods,
  18006. only for the third data dimension of the color map.
  18007. The minimum and maximum values of the data set are buffered in the internal QCPColorMapData
  18008. instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref
  18009. QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For
  18010. performance reasons, however, they are only updated in an expanding fashion. So the buffered
  18011. maximum can only increase and the buffered minimum can only decrease. In consequence, changes to
  18012. the data that actually lower the maximum of the data set (by overwriting the cell holding the
  18013. current maximum with a smaller value), aren't recognized and the buffered maximum overestimates
  18014. the true maximum of the data set. The same happens for the buffered minimum. To recalculate the
  18015. true minimum and maximum by explicitly looking at each cell, the method
  18016. QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a
  18017. recalculateDataBounds calls this method before setting the data range to the buffered minimum and
  18018. maximum.
  18019. \see setDataRange
  18020. */
  18021. void QCPColorMap::rescaleDataRange(bool recalculateDataBounds)
  18022. {
  18023. if (recalculateDataBounds)
  18024. mMapData->recalculateDataBounds();
  18025. setDataRange(mMapData->dataBounds());
  18026. }
  18027. /*!
  18028. Takes the current appearance of the color map and updates the legend icon, which is used to
  18029. represent this color map in the legend (see \ref QCPLegend).
  18030. The \a transformMode specifies whether the rescaling is done by a faster, low quality image
  18031. scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm
  18032. (Qt::SmoothTransformation).
  18033. The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to
  18034. the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured
  18035. legend icon size, the thumb will be rescaled during drawing of the legend item.
  18036. \see setDataRange
  18037. */
  18038. void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize& thumbSize)
  18039. {
  18040. if (mMapImage.isNull() && !data()->isEmpty())
  18041. updateMapImage(); // try to update map image if it's null (happens if no draw has happened
  18042. // yet)
  18043. if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again
  18044. {
  18045. bool mirrorX =
  18046. (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  18047. bool mirrorY =
  18048. (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  18049. mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY))
  18050. .scaled(thumbSize, Qt::KeepAspectRatio, transformMode);
  18051. }
  18052. }
  18053. /*!
  18054. Clears the colormap data by calling \ref QCPColorMapData::clear() on the internal data. This also
  18055. resizes the map to 0x0 cells.
  18056. */
  18057. void QCPColorMap::clearData()
  18058. {
  18059. mMapData->clear();
  18060. }
  18061. /* inherits documentation from base class */
  18062. double QCPColorMap::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  18063. {
  18064. Q_UNUSED(details)
  18065. if (onlySelectable && !mSelectable)
  18066. return -1;
  18067. if (!mKeyAxis || !mValueAxis) {
  18068. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  18069. return -1;
  18070. }
  18071. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) {
  18072. double posKey, posValue;
  18073. pixelsToCoords(pos, posKey, posValue);
  18074. if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue))
  18075. return mParentPlot->selectionTolerance() * 0.99;
  18076. }
  18077. return -1;
  18078. }
  18079. /*! \internal
  18080. Updates the internal map image buffer by going through the internal \ref QCPColorMapData and
  18081. turning the data values into color pixels with \ref QCPColorGradient::colorize.
  18082. This method is called by \ref QCPColorMap::draw if either the data has been modified or the map
  18083. image has been invalidated for a different reason (e.g. a change of the data range with \ref
  18084. setDataRange).
  18085. If the map cell count is low, the image created will be oversampled in order to avoid a
  18086. QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images
  18087. without smooth transform enabled. Accordingly, oversampling isn't performed if \ref
  18088. setInterpolate is true.
  18089. */
  18090. void QCPColorMap::updateMapImage()
  18091. {
  18092. QCPAxis* keyAxis = mKeyAxis.data();
  18093. if (!keyAxis)
  18094. return;
  18095. if (mMapData->isEmpty())
  18096. return;
  18097. const int keySize = mMapData->keySize();
  18098. const int valueSize = mMapData->valueSize();
  18099. int keyOversamplingFactor =
  18100. mInterpolate
  18101. ? 1
  18102. : (int)(1.0
  18103. + 100.0 / (double)keySize); // make mMapImage have at least size 100, factor
  18104. // becomes 1 if size > 200 or interpolation is on
  18105. int valueOversamplingFactor =
  18106. mInterpolate
  18107. ? 1
  18108. : (int)(1.0
  18109. + 100.0 / (double)valueSize); // make mMapImage have at least size 100, factor
  18110. // becomes 1 if size > 200 or interpolation is on
  18111. // resize mMapImage to correct dimensions including possible oversampling factors, according to
  18112. // key/value axes orientation:
  18113. if (keyAxis->orientation() == Qt::Horizontal
  18114. && (mMapImage.width() != keySize * keyOversamplingFactor
  18115. || mMapImage.height() != valueSize * valueOversamplingFactor))
  18116. mMapImage =
  18117. QImage(QSize(keySize * keyOversamplingFactor, valueSize * valueOversamplingFactor),
  18118. QImage::Format_RGB32);
  18119. else if (keyAxis->orientation() == Qt::Vertical
  18120. && (mMapImage.width() != valueSize * valueOversamplingFactor
  18121. || mMapImage.height() != keySize * keyOversamplingFactor))
  18122. mMapImage =
  18123. QImage(QSize(valueSize * valueOversamplingFactor, keySize * keyOversamplingFactor),
  18124. QImage::Format_RGB32);
  18125. QImage* localMapImage =
  18126. &mMapImage; // this is the image on which the colorization operates. Either the final
  18127. // mMapImage, or if we need oversampling, mUndersampledMapImage
  18128. if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) {
  18129. // resize undersampled map image to actual key/value cell sizes:
  18130. if (keyAxis->orientation() == Qt::Horizontal
  18131. && (mUndersampledMapImage.width() != keySize
  18132. || mUndersampledMapImage.height() != valueSize))
  18133. mUndersampledMapImage = QImage(QSize(keySize, valueSize), QImage::Format_RGB32);
  18134. else if (keyAxis->orientation() == Qt::Vertical
  18135. && (mUndersampledMapImage.width() != valueSize
  18136. || mUndersampledMapImage.height() != keySize))
  18137. mUndersampledMapImage = QImage(QSize(valueSize, keySize), QImage::Format_RGB32);
  18138. localMapImage =
  18139. &mUndersampledMapImage; // make the colorization run on the undersampled image
  18140. } else if (!mUndersampledMapImage.isNull())
  18141. mUndersampledMapImage =
  18142. QImage(); // don't need oversampling mechanism anymore (map size has changed) but
  18143. // mUndersampledMapImage still has nonzero size, free it
  18144. const double* rawData = mMapData->mData;
  18145. if (keyAxis->orientation() == Qt::Horizontal) {
  18146. const int lineCount = valueSize;
  18147. const int rowCount = keySize;
  18148. for (int line = 0; line < lineCount; ++line) {
  18149. QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(
  18150. lineCount - 1
  18151. - line)); // invert scanline index because QImage counts scanlines from top, but our
  18152. // vertical index counts from bottom (mathematical coordinate system)
  18153. mGradient.colorize(rawData + line * rowCount, mDataRange, pixels, rowCount, 1,
  18154. mDataScaleType == QCPAxis::stLogarithmic);
  18155. }
  18156. } else // keyAxis->orientation() == Qt::Vertical
  18157. {
  18158. const int lineCount = keySize;
  18159. const int rowCount = valueSize;
  18160. for (int line = 0; line < lineCount; ++line) {
  18161. QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(
  18162. lineCount - 1
  18163. - line)); // invert scanline index because QImage counts scanlines from top, but our
  18164. // vertical index counts from bottom (mathematical coordinate system)
  18165. mGradient.colorize(rawData + line, mDataRange, pixels, rowCount, lineCount,
  18166. mDataScaleType == QCPAxis::stLogarithmic);
  18167. }
  18168. }
  18169. if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1) {
  18170. if (keyAxis->orientation() == Qt::Horizontal)
  18171. mMapImage = mUndersampledMapImage.scaled(keySize * keyOversamplingFactor,
  18172. valueSize * valueOversamplingFactor,
  18173. Qt::IgnoreAspectRatio, Qt::FastTransformation);
  18174. else
  18175. mMapImage = mUndersampledMapImage.scaled(valueSize * valueOversamplingFactor,
  18176. keySize * keyOversamplingFactor,
  18177. Qt::IgnoreAspectRatio, Qt::FastTransformation);
  18178. }
  18179. mMapData->mDataModified = false;
  18180. mMapImageInvalidated = false;
  18181. }
  18182. /* inherits documentation from base class */
  18183. void QCPColorMap::draw(QCPPainter* painter)
  18184. {
  18185. if (mMapData->isEmpty())
  18186. return;
  18187. if (!mKeyAxis || !mValueAxis)
  18188. return;
  18189. applyDefaultAntialiasingHint(painter);
  18190. if (mMapData->mDataModified || mMapImageInvalidated)
  18191. updateMapImage();
  18192. // use buffer if painting vectorized (PDF):
  18193. bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized);
  18194. QCPPainter* localPainter =
  18195. painter; // will be redirected to paint on mapBuffer if painting vectorized
  18196. QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map
  18197. // portion/buffer will end up in
  18198. QPixmap mapBuffer;
  18199. double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps
  18200. if (useBuffer) {
  18201. mapBufferTarget = painter->clipRegion().boundingRect();
  18202. mapBuffer = QPixmap((mapBufferTarget.size() * mapBufferPixelRatio).toSize());
  18203. mapBuffer.fill(Qt::transparent);
  18204. localPainter = new QCPPainter(&mapBuffer);
  18205. localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio);
  18206. localPainter->translate(-mapBufferTarget.topLeft());
  18207. }
  18208. QRectF imageRect =
  18209. QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
  18210. coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper))
  18211. .normalized();
  18212. // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are
  18213. // centered on map range boundary):
  18214. double halfCellWidth = 0; // in pixels
  18215. double halfCellHeight = 0; // in pixels
  18216. if (keyAxis()->orientation() == Qt::Horizontal) {
  18217. if (mMapData->keySize() > 1)
  18218. halfCellWidth = 0.5 * imageRect.width() / (double)(mMapData->keySize() - 1);
  18219. if (mMapData->valueSize() > 1)
  18220. halfCellHeight = 0.5 * imageRect.height() / (double)(mMapData->valueSize() - 1);
  18221. } else // keyAxis orientation is Qt::Vertical
  18222. {
  18223. if (mMapData->keySize() > 1)
  18224. halfCellHeight = 0.5 * imageRect.height() / (double)(mMapData->keySize() - 1);
  18225. if (mMapData->valueSize() > 1)
  18226. halfCellWidth = 0.5 * imageRect.width() / (double)(mMapData->valueSize() - 1);
  18227. }
  18228. imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight);
  18229. bool mirrorX =
  18230. (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  18231. bool mirrorY =
  18232. (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  18233. bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform);
  18234. localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate);
  18235. QRegion clipBackup;
  18236. if (mTightBoundary) {
  18237. clipBackup = localPainter->clipRegion();
  18238. QRectF tightClipRect =
  18239. QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
  18240. coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper))
  18241. .normalized();
  18242. localPainter->setClipRect(tightClipRect, Qt::IntersectClip);
  18243. }
  18244. localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY));
  18245. if (mTightBoundary)
  18246. localPainter->setClipRegion(clipBackup);
  18247. localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup);
  18248. if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter
  18249. {
  18250. delete localPainter;
  18251. painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer);
  18252. }
  18253. }
  18254. /* inherits documentation from base class */
  18255. void QCPColorMap::drawLegendIcon(QCPPainter* painter, const QRectF& rect) const
  18256. {
  18257. applyDefaultAntialiasingHint(painter);
  18258. // draw map thumbnail:
  18259. if (!mLegendIcon.isNull()) {
  18260. QPixmap scaledIcon =
  18261. mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation);
  18262. QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height());
  18263. iconRect.moveCenter(rect.center());
  18264. painter->drawPixmap(iconRect.topLeft(), scaledIcon);
  18265. }
  18266. /*
  18267. // draw frame:
  18268. painter->setBrush(Qt::NoBrush);
  18269. painter->setPen(Qt::black);
  18270. painter->drawRect(rect.adjusted(1, 1, 0, 0));
  18271. */
  18272. }
  18273. /* inherits documentation from base class */
  18274. QCPRange QCPColorMap::getKeyRange(bool& foundRange, SignDomain inSignDomain) const
  18275. {
  18276. foundRange = true;
  18277. QCPRange result = mMapData->keyRange();
  18278. result.normalize();
  18279. if (inSignDomain == QCPAbstractPlottable::sdPositive) {
  18280. if (result.lower <= 0 && result.upper > 0)
  18281. result.lower = result.upper * 1e-3;
  18282. else if (result.lower <= 0 && result.upper <= 0)
  18283. foundRange = false;
  18284. } else if (inSignDomain == QCPAbstractPlottable::sdNegative) {
  18285. if (result.upper >= 0 && result.lower < 0)
  18286. result.upper = result.lower * 1e-3;
  18287. else if (result.upper >= 0 && result.lower >= 0)
  18288. foundRange = false;
  18289. }
  18290. return result;
  18291. }
  18292. /* inherits documentation from base class */
  18293. QCPRange QCPColorMap::getValueRange(bool& foundRange, SignDomain inSignDomain) const
  18294. {
  18295. foundRange = true;
  18296. QCPRange result = mMapData->valueRange();
  18297. result.normalize();
  18298. if (inSignDomain == QCPAbstractPlottable::sdPositive) {
  18299. if (result.lower <= 0 && result.upper > 0)
  18300. result.lower = result.upper * 1e-3;
  18301. else if (result.lower <= 0 && result.upper <= 0)
  18302. foundRange = false;
  18303. } else if (inSignDomain == QCPAbstractPlottable::sdNegative) {
  18304. if (result.upper >= 0 && result.lower < 0)
  18305. result.upper = result.lower * 1e-3;
  18306. else if (result.upper >= 0 && result.lower >= 0)
  18307. foundRange = false;
  18308. }
  18309. return result;
  18310. }
  18311. ////////////////////////////////////////////////////////////////////////////////////////////////////
  18312. //////////////////// QCPFinancialData
  18313. ////////////////////////////////////////////////////////////////////////////////////////////////////
  18314. /*! \class QCPFinancialData
  18315. \brief Holds the data of one single data point for QCPFinancial.
  18316. The container for storing multiple data points is \ref QCPFinancialDataMap.
  18317. The stored data is:
  18318. \li \a key: coordinate on the key axis of this data point
  18319. \li \a open: The opening value at the data point
  18320. \li \a high: The high/maximum value at the data point
  18321. \li \a low: The low/minimum value at the data point
  18322. \li \a close: The closing value at the data point
  18323. \see QCPFinancialDataMap
  18324. */
  18325. /*!
  18326. Constructs a data point with key and all values set to zero.
  18327. */
  18328. QCPFinancialData::QCPFinancialData() : key(0), open(0), high(0), low(0), close(0)
  18329. {}
  18330. /*!
  18331. Constructs a data point with the specified \a key and OHLC values.
  18332. */
  18333. QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close)
  18334. : key(key), open(open), high(high), low(low), close(close)
  18335. {}
  18336. ////////////////////////////////////////////////////////////////////////////////////////////////////
  18337. //////////////////// QCPFinancial
  18338. ////////////////////////////////////////////////////////////////////////////////////////////////////
  18339. /*! \class QCPFinancial
  18340. \brief A plottable representing a financial stock chart
  18341. \image html QCPFinancial.png
  18342. This plottable represents time series data binned to certain intervals, mainly used for stock
  18343. charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be
  18344. set via \ref setChartStyle.
  18345. The data is passed via \ref setData as a set of open/high/low/close values at certain keys
  18346. (typically times). This means the data must be already binned appropriately. If data is only
  18347. available as a series of values (e.g. \a price against \a time), you can use the static
  18348. convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed
  18349. to \ref setData.
  18350. The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and is given in plot
  18351. key coordinates. A typical choice is to set it to (or slightly less than) one bin interval width.
  18352. \section appearance Changing the appearance
  18353. Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored,
  18354. lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush).
  18355. If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are
  18356. represented with a different pen and brush than negative changes (\a close < \a open). These can
  18357. be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref
  18358. setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection
  18359. however, the normal selected pen/brush (\ref setSelectedPen, \ref setSelectedBrush) is used,
  18360. irrespective of whether the chart is single- or two-colored.
  18361. */
  18362. /* start of documentation of inline functions */
  18363. /*! \fn QCPFinancialDataMap *QCPFinancial::data() const
  18364. Returns a pointer to the internal data storage of type \ref QCPFinancialDataMap. You may use it to
  18365. directly manipulate the data, which may be more convenient and faster than using the regular \ref
  18366. setData or \ref addData methods, in certain situations.
  18367. */
  18368. /* end of documentation of inline functions */
  18369. /*!
  18370. Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its
  18371. value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not
  18372. have the same orientation. If either of these restrictions is violated, a corresponding message is
  18373. printed to the debug output (qDebug), the construction is not aborted, though.
  18374. The constructed QCPFinancial can be added to the plot with QCustomPlot::addPlottable, QCustomPlot
  18375. then takes ownership of the financial chart.
  18376. */
  18377. QCPFinancial::QCPFinancial(QCPAxis* keyAxis, QCPAxis* valueAxis)
  18378. : QCPAbstractPlottable(keyAxis, valueAxis)
  18379. , mData(0)
  18380. , mChartStyle(csOhlc)
  18381. , mWidth(0.5)
  18382. , mTwoColored(false)
  18383. , mBrushPositive(QBrush(QColor(210, 210, 255)))
  18384. , mBrushNegative(QBrush(QColor(255, 210, 210)))
  18385. , mPenPositive(QPen(QColor(10, 40, 180)))
  18386. , mPenNegative(QPen(QColor(180, 40, 10)))
  18387. {
  18388. mData = new QCPFinancialDataMap;
  18389. setSelectedPen(QPen(QColor(80, 80, 255), 2.5));
  18390. setSelectedBrush(QBrush(QColor(80, 80, 255)));
  18391. }
  18392. QCPFinancial::~QCPFinancial()
  18393. {
  18394. delete mData;
  18395. }
  18396. /*!
  18397. Replaces the current data with the provided \a data.
  18398. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable
  18399. takes ownership of the passed data and replaces the internal data pointer with it. This is
  18400. significantly faster than copying for large datasets.
  18401. Alternatively, you can also access and modify the plottable's data via the \ref data method, which
  18402. returns a pointer to the internal \ref QCPFinancialDataMap.
  18403. \see timeSeriesToOhlc
  18404. */
  18405. void QCPFinancial::setData(QCPFinancialDataMap* data, bool copy)
  18406. {
  18407. if (mData == data) {
  18408. qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable"
  18409. << reinterpret_cast<quintptr>(data);
  18410. return;
  18411. }
  18412. if (copy) {
  18413. *mData = *data;
  18414. } else {
  18415. delete mData;
  18416. mData = data;
  18417. }
  18418. }
  18419. /*! \overload
  18420. Replaces the current data with the provided open/high/low/close data. The provided vectors should
  18421. have equal length. Else, the number of added points will be the size of the smallest vector.
  18422. \see timeSeriesToOhlc
  18423. */
  18424. void QCPFinancial::setData(const QVector<double>& key, const QVector<double>& open,
  18425. const QVector<double>& high, const QVector<double>& low,
  18426. const QVector<double>& close)
  18427. {
  18428. mData->clear();
  18429. int n = key.size();
  18430. n = qMin(n, open.size());
  18431. n = qMin(n, high.size());
  18432. n = qMin(n, low.size());
  18433. n = qMin(n, close.size());
  18434. for (int i = 0; i < n; ++i) {
  18435. mData->insertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i]));
  18436. }
  18437. }
  18438. /*!
  18439. Sets which representation style shall be used to display the OHLC data.
  18440. */
  18441. void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style)
  18442. {
  18443. mChartStyle = style;
  18444. }
  18445. /*!
  18446. Sets the width of the individual bars/candlesticks to \a width in plot key coordinates.
  18447. A typical choice is to set it to (or slightly less than) one bin interval width.
  18448. */
  18449. void QCPFinancial::setWidth(double width)
  18450. {
  18451. mWidth = width;
  18452. }
  18453. /*!
  18454. Sets whether this chart shall contrast positive from negative trends per data point by using two
  18455. separate colors to draw the respective bars/candlesticks.
  18456. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  18457. setBrush).
  18458. \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative
  18459. */
  18460. void QCPFinancial::setTwoColored(bool twoColored)
  18461. {
  18462. mTwoColored = twoColored;
  18463. }
  18464. /*!
  18465. If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
  18466. of data points with a positive trend (i.e. bars/candlesticks with close >= open).
  18467. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  18468. setBrush).
  18469. \see setBrushNegative, setPenPositive, setPenNegative
  18470. */
  18471. void QCPFinancial::setBrushPositive(const QBrush& brush)
  18472. {
  18473. mBrushPositive = brush;
  18474. }
  18475. /*!
  18476. If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
  18477. of data points with a negative trend (i.e. bars/candlesticks with close < open).
  18478. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  18479. setBrush).
  18480. \see setBrushPositive, setPenNegative, setPenPositive
  18481. */
  18482. void QCPFinancial::setBrushNegative(const QBrush& brush)
  18483. {
  18484. mBrushNegative = brush;
  18485. }
  18486. /*!
  18487. If \ref setTwoColored is set to true, this function controls the pen that is used to draw
  18488. outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open).
  18489. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  18490. setBrush).
  18491. \see setPenNegative, setBrushPositive, setBrushNegative
  18492. */
  18493. void QCPFinancial::setPenPositive(const QPen& pen)
  18494. {
  18495. mPenPositive = pen;
  18496. }
  18497. /*!
  18498. If \ref setTwoColored is set to true, this function controls the pen that is used to draw
  18499. outlines of data points with a negative trend (i.e. bars/candlesticks with close < open).
  18500. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  18501. setBrush).
  18502. \see setPenPositive, setBrushNegative, setBrushPositive
  18503. */
  18504. void QCPFinancial::setPenNegative(const QPen& pen)
  18505. {
  18506. mPenNegative = pen;
  18507. }
  18508. /*!
  18509. Adds the provided data points in \a dataMap to the current data.
  18510. Alternatively, you can also access and modify the data via the \ref data method, which returns a
  18511. pointer to the internal \ref QCPFinancialDataMap.
  18512. \see removeData
  18513. */
  18514. void QCPFinancial::addData(const QCPFinancialDataMap& dataMap)
  18515. {
  18516. mData->unite(dataMap);
  18517. }
  18518. /*! \overload
  18519. Adds the provided single data point in \a data to the current data.
  18520. Alternatively, you can also access and modify the data via the \ref data method, which returns a
  18521. pointer to the internal \ref QCPFinancialData.
  18522. \see removeData
  18523. */
  18524. void QCPFinancial::addData(const QCPFinancialData& data)
  18525. {
  18526. mData->insertMulti(data.key, data);
  18527. }
  18528. /*! \overload
  18529. Adds the provided single data point given by \a key, \a open, \a high, \a low, and \a close to
  18530. the current data.
  18531. Alternatively, you can also access and modify the data via the \ref data method, which returns a
  18532. pointer to the internal \ref QCPFinancialData.
  18533. \see removeData
  18534. */
  18535. void QCPFinancial::addData(double key, double open, double high, double low, double close)
  18536. {
  18537. mData->insertMulti(key, QCPFinancialData(key, open, high, low, close));
  18538. }
  18539. /*! \overload
  18540. Adds the provided open/high/low/close data to the current data.
  18541. Alternatively, you can also access and modify the data via the \ref data method, which returns a
  18542. pointer to the internal \ref QCPFinancialData.
  18543. \see removeData
  18544. */
  18545. void QCPFinancial::addData(const QVector<double>& key, const QVector<double>& open,
  18546. const QVector<double>& high, const QVector<double>& low,
  18547. const QVector<double>& close)
  18548. {
  18549. int n = key.size();
  18550. n = qMin(n, open.size());
  18551. n = qMin(n, high.size());
  18552. n = qMin(n, low.size());
  18553. n = qMin(n, close.size());
  18554. for (int i = 0; i < n; ++i) {
  18555. mData->insertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i]));
  18556. }
  18557. }
  18558. /*!
  18559. Removes all data points with keys smaller than \a key.
  18560. \see addData, clearData
  18561. */
  18562. void QCPFinancial::removeDataBefore(double key)
  18563. {
  18564. QCPFinancialDataMap::iterator it = mData->begin();
  18565. while (it != mData->end() && it.key() < key)
  18566. it = mData->erase(it);
  18567. }
  18568. /*!
  18569. Removes all data points with keys greater than \a key.
  18570. \see addData, clearData
  18571. */
  18572. void QCPFinancial::removeDataAfter(double key)
  18573. {
  18574. if (mData->isEmpty())
  18575. return;
  18576. QCPFinancialDataMap::iterator it = mData->upperBound(key);
  18577. while (it != mData->end())
  18578. it = mData->erase(it);
  18579. }
  18580. /*!
  18581. Removes all data points with keys between \a fromKey and \a toKey. if \a fromKey is greater or
  18582. equal to \a toKey, the function does nothing. To remove a single data point with known key, use
  18583. \ref removeData(double key).
  18584. \see addData, clearData
  18585. */
  18586. void QCPFinancial::removeData(double fromKey, double toKey)
  18587. {
  18588. if (fromKey >= toKey || mData->isEmpty())
  18589. return;
  18590. QCPFinancialDataMap::iterator it = mData->upperBound(fromKey);
  18591. QCPFinancialDataMap::iterator itEnd = mData->upperBound(toKey);
  18592. while (it != itEnd)
  18593. it = mData->erase(it);
  18594. }
  18595. /*! \overload
  18596. Removes a single data point at \a key. If the position is not known with absolute precision,
  18597. consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval
  18598. around the suspected position, depeding on the precision with which the key is known.
  18599. \see addData, clearData
  18600. */
  18601. void QCPFinancial::removeData(double key)
  18602. {
  18603. mData->remove(key);
  18604. }
  18605. /*!
  18606. Removes all data points.
  18607. \see removeData, removeDataAfter, removeDataBefore
  18608. */
  18609. void QCPFinancial::clearData()
  18610. {
  18611. mData->clear();
  18612. }
  18613. /* inherits documentation from base class */
  18614. double QCPFinancial::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  18615. {
  18616. Q_UNUSED(details)
  18617. if (onlySelectable && !mSelectable)
  18618. return -1;
  18619. if (!mKeyAxis || !mValueAxis) {
  18620. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  18621. return -1;
  18622. }
  18623. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) {
  18624. // get visible data range:
  18625. QCPFinancialDataMap::const_iterator lower,
  18626. upper; // note that upper is the actual upper point, and not 1 step after the upper
  18627. // point
  18628. getVisibleDataBounds(lower, upper);
  18629. if (lower == mData->constEnd() || upper == mData->constEnd())
  18630. return -1;
  18631. // perform select test according to configured style:
  18632. switch (mChartStyle) {
  18633. case QCPFinancial::csOhlc:
  18634. return ohlcSelectTest(pos, lower, upper + 1);
  18635. break;
  18636. case QCPFinancial::csCandlestick:
  18637. return candlestickSelectTest(pos, lower, upper + 1);
  18638. break;
  18639. }
  18640. }
  18641. return -1;
  18642. }
  18643. /*!
  18644. A convenience function that converts time series data (\a value against \a time) to OHLC binned
  18645. data points. The return value can then be passed on to \ref setData.
  18646. The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given.
  18647. For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour
  18648. each, set \a timeBinSize to 3600.
  18649. \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The
  18650. value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys.
  18651. It merely defines the mathematical offset/phase of the bins that will be used to process the
  18652. data.
  18653. */
  18654. QCPFinancialDataMap QCPFinancial::timeSeriesToOhlc(const QVector<double>& time,
  18655. const QVector<double>& value, double timeBinSize,
  18656. double timeBinOffset)
  18657. {
  18658. QCPFinancialDataMap map;
  18659. int count = qMin(time.size(), value.size());
  18660. if (count == 0)
  18661. return QCPFinancialDataMap();
  18662. QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first());
  18663. int currentBinIndex = qFloor((time.first() - timeBinOffset) / timeBinSize + 0.5);
  18664. for (int i = 0; i < count; ++i) {
  18665. int index = qFloor((time.at(i) - timeBinOffset) / timeBinSize + 0.5);
  18666. if (currentBinIndex == index) // data point still in current bin, extend high/low:
  18667. {
  18668. if (value.at(i) < currentBinData.low)
  18669. currentBinData.low = value.at(i);
  18670. if (value.at(i) > currentBinData.high)
  18671. currentBinData.high = value.at(i);
  18672. if (i == count - 1) // last data point is in current bin, finalize bin:
  18673. {
  18674. currentBinData.close = value.at(i);
  18675. currentBinData.key = timeBinOffset + (index)*timeBinSize;
  18676. map.insert(currentBinData.key, currentBinData);
  18677. }
  18678. } else // data point not anymore in current bin, set close of old and open of new bin, and
  18679. // add old to map:
  18680. {
  18681. // finalize current bin:
  18682. currentBinData.close = value.at(i - 1);
  18683. currentBinData.key = timeBinOffset + (index - 1) * timeBinSize;
  18684. map.insert(currentBinData.key, currentBinData);
  18685. // start next bin:
  18686. currentBinIndex = index;
  18687. currentBinData.open = value.at(i);
  18688. currentBinData.high = value.at(i);
  18689. currentBinData.low = value.at(i);
  18690. }
  18691. }
  18692. return map;
  18693. }
  18694. /* inherits documentation from base class */
  18695. void QCPFinancial::draw(QCPPainter* painter)
  18696. {
  18697. // get visible data range:
  18698. QCPFinancialDataMap::const_iterator lower,
  18699. upper; // note that upper is the actual upper point, and not 1 step after the upper point
  18700. getVisibleDataBounds(lower, upper);
  18701. if (lower == mData->constEnd() || upper == mData->constEnd())
  18702. return;
  18703. // draw visible data range according to configured style:
  18704. switch (mChartStyle) {
  18705. case QCPFinancial::csOhlc:
  18706. drawOhlcPlot(painter, lower, upper + 1);
  18707. break;
  18708. case QCPFinancial::csCandlestick:
  18709. drawCandlestickPlot(painter, lower, upper + 1);
  18710. break;
  18711. }
  18712. }
  18713. /* inherits documentation from base class */
  18714. void QCPFinancial::drawLegendIcon(QCPPainter* painter, const QRectF& rect) const
  18715. {
  18716. painter->setAntialiasing(
  18717. false); // legend icon especially of csCandlestick looks better without antialiasing
  18718. if (mChartStyle == csOhlc) {
  18719. if (mTwoColored) {
  18720. // draw upper left half icon with positive color:
  18721. painter->setBrush(mBrushPositive);
  18722. painter->setPen(mPenPositive);
  18723. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint()
  18724. << rect.topRight().toPoint()
  18725. << rect.topLeft().toPoint()));
  18726. painter->drawLine(QLineF(0, rect.height() * 0.5, rect.width(), rect.height() * 0.5)
  18727. .translated(rect.topLeft()));
  18728. painter->drawLine(QLineF(rect.width() * 0.2, rect.height() * 0.3, rect.width() * 0.2,
  18729. rect.height() * 0.5)
  18730. .translated(rect.topLeft()));
  18731. painter->drawLine(QLineF(rect.width() * 0.8, rect.height() * 0.5, rect.width() * 0.8,
  18732. rect.height() * 0.7)
  18733. .translated(rect.topLeft()));
  18734. // draw bottom right hald icon with negative color:
  18735. painter->setBrush(mBrushNegative);
  18736. painter->setPen(mPenNegative);
  18737. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint()
  18738. << rect.topRight().toPoint()
  18739. << rect.bottomRight().toPoint()));
  18740. painter->drawLine(QLineF(0, rect.height() * 0.5, rect.width(), rect.height() * 0.5)
  18741. .translated(rect.topLeft()));
  18742. painter->drawLine(QLineF(rect.width() * 0.2, rect.height() * 0.3, rect.width() * 0.2,
  18743. rect.height() * 0.5)
  18744. .translated(rect.topLeft()));
  18745. painter->drawLine(QLineF(rect.width() * 0.8, rect.height() * 0.5, rect.width() * 0.8,
  18746. rect.height() * 0.7)
  18747. .translated(rect.topLeft()));
  18748. } else {
  18749. painter->setBrush(mBrush);
  18750. painter->setPen(mPen);
  18751. painter->drawLine(QLineF(0, rect.height() * 0.5, rect.width(), rect.height() * 0.5)
  18752. .translated(rect.topLeft()));
  18753. painter->drawLine(QLineF(rect.width() * 0.2, rect.height() * 0.3, rect.width() * 0.2,
  18754. rect.height() * 0.5)
  18755. .translated(rect.topLeft()));
  18756. painter->drawLine(QLineF(rect.width() * 0.8, rect.height() * 0.5, rect.width() * 0.8,
  18757. rect.height() * 0.7)
  18758. .translated(rect.topLeft()));
  18759. }
  18760. } else if (mChartStyle == csCandlestick) {
  18761. if (mTwoColored) {
  18762. // draw upper left half icon with positive color:
  18763. painter->setBrush(mBrushPositive);
  18764. painter->setPen(mPenPositive);
  18765. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint()
  18766. << rect.topRight().toPoint()
  18767. << rect.topLeft().toPoint()));
  18768. painter->drawLine(
  18769. QLineF(0, rect.height() * 0.5, rect.width() * 0.25, rect.height() * 0.5)
  18770. .translated(rect.topLeft()));
  18771. painter->drawLine(
  18772. QLineF(rect.width() * 0.75, rect.height() * 0.5, rect.width(), rect.height() * 0.5)
  18773. .translated(rect.topLeft()));
  18774. painter->drawRect(QRectF(rect.width() * 0.25, rect.height() * 0.25, rect.width() * 0.5,
  18775. rect.height() * 0.5)
  18776. .translated(rect.topLeft()));
  18777. // draw bottom right hald icon with negative color:
  18778. painter->setBrush(mBrushNegative);
  18779. painter->setPen(mPenNegative);
  18780. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint()
  18781. << rect.topRight().toPoint()
  18782. << rect.bottomRight().toPoint()));
  18783. painter->drawLine(
  18784. QLineF(0, rect.height() * 0.5, rect.width() * 0.25, rect.height() * 0.5)
  18785. .translated(rect.topLeft()));
  18786. painter->drawLine(
  18787. QLineF(rect.width() * 0.75, rect.height() * 0.5, rect.width(), rect.height() * 0.5)
  18788. .translated(rect.topLeft()));
  18789. painter->drawRect(QRectF(rect.width() * 0.25, rect.height() * 0.25, rect.width() * 0.5,
  18790. rect.height() * 0.5)
  18791. .translated(rect.topLeft()));
  18792. } else {
  18793. painter->setBrush(mBrush);
  18794. painter->setPen(mPen);
  18795. painter->drawLine(
  18796. QLineF(0, rect.height() * 0.5, rect.width() * 0.25, rect.height() * 0.5)
  18797. .translated(rect.topLeft()));
  18798. painter->drawLine(
  18799. QLineF(rect.width() * 0.75, rect.height() * 0.5, rect.width(), rect.height() * 0.5)
  18800. .translated(rect.topLeft()));
  18801. painter->drawRect(QRectF(rect.width() * 0.25, rect.height() * 0.25, rect.width() * 0.5,
  18802. rect.height() * 0.5)
  18803. .translated(rect.topLeft()));
  18804. }
  18805. }
  18806. }
  18807. /* inherits documentation from base class */
  18808. QCPRange QCPFinancial::getKeyRange(bool& foundRange,
  18809. QCPAbstractPlottable::SignDomain inSignDomain) const
  18810. {
  18811. QCPRange range;
  18812. bool haveLower = false;
  18813. bool haveUpper = false;
  18814. double current;
  18815. QCPFinancialDataMap::const_iterator it = mData->constBegin();
  18816. while (it != mData->constEnd()) {
  18817. current = it.value().key;
  18818. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0)
  18819. || (inSignDomain == sdPositive && current > 0)) {
  18820. if (current < range.lower || !haveLower) {
  18821. range.lower = current;
  18822. haveLower = true;
  18823. }
  18824. if (current > range.upper || !haveUpper) {
  18825. range.upper = current;
  18826. haveUpper = true;
  18827. }
  18828. }
  18829. ++it;
  18830. }
  18831. // determine exact range by including width of bars/flags:
  18832. if (haveLower && mKeyAxis)
  18833. range.lower = range.lower - mWidth * 0.5;
  18834. if (haveUpper && mKeyAxis)
  18835. range.upper = range.upper + mWidth * 0.5;
  18836. foundRange = haveLower && haveUpper;
  18837. return range;
  18838. }
  18839. /* inherits documentation from base class */
  18840. QCPRange QCPFinancial::getValueRange(bool& foundRange,
  18841. QCPAbstractPlottable::SignDomain inSignDomain) const
  18842. {
  18843. QCPRange range;
  18844. bool haveLower = false;
  18845. bool haveUpper = false;
  18846. QCPFinancialDataMap::const_iterator it = mData->constBegin();
  18847. while (it != mData->constEnd()) {
  18848. // high:
  18849. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && it.value().high < 0)
  18850. || (inSignDomain == sdPositive && it.value().high > 0)) {
  18851. if (it.value().high < range.lower || !haveLower) {
  18852. range.lower = it.value().high;
  18853. haveLower = true;
  18854. }
  18855. if (it.value().high > range.upper || !haveUpper) {
  18856. range.upper = it.value().high;
  18857. haveUpper = true;
  18858. }
  18859. }
  18860. // low:
  18861. if (inSignDomain == sdBoth || (inSignDomain == sdNegative && it.value().low < 0)
  18862. || (inSignDomain == sdPositive && it.value().low > 0)) {
  18863. if (it.value().low < range.lower || !haveLower) {
  18864. range.lower = it.value().low;
  18865. haveLower = true;
  18866. }
  18867. if (it.value().low > range.upper || !haveUpper) {
  18868. range.upper = it.value().low;
  18869. haveUpper = true;
  18870. }
  18871. }
  18872. ++it;
  18873. }
  18874. foundRange = haveLower && haveUpper;
  18875. return range;
  18876. }
  18877. /*! \internal
  18878. Draws the data from \a begin to \a end as OHLC bars with the provided \a painter.
  18879. This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc.
  18880. */
  18881. void QCPFinancial::drawOhlcPlot(QCPPainter* painter,
  18882. const QCPFinancialDataMap::const_iterator& begin,
  18883. const QCPFinancialDataMap::const_iterator& end)
  18884. {
  18885. QCPAxis* keyAxis = mKeyAxis.data();
  18886. QCPAxis* valueAxis = mValueAxis.data();
  18887. if (!keyAxis || !valueAxis) {
  18888. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  18889. return;
  18890. }
  18891. QPen linePen;
  18892. if (keyAxis->orientation() == Qt::Horizontal) {
  18893. for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) {
  18894. if (mSelected)
  18895. linePen = mSelectedPen;
  18896. else if (mTwoColored)
  18897. linePen = it.value().close >= it.value().open ? mPenPositive : mPenNegative;
  18898. else
  18899. linePen = mPen;
  18900. painter->setPen(linePen);
  18901. double keyPixel = keyAxis->coordToPixel(it.value().key);
  18902. double openPixel = valueAxis->coordToPixel(it.value().open);
  18903. double closePixel = valueAxis->coordToPixel(it.value().close);
  18904. // draw backbone:
  18905. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)),
  18906. QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)));
  18907. // draw open:
  18908. double keyWidthPixels =
  18909. keyPixel
  18910. - keyAxis->coordToPixel(
  18911. it.value().key
  18912. - mWidth * 0.5); // sign of this makes sure open/close are on correct sides
  18913. painter->drawLine(QPointF(keyPixel - keyWidthPixels, openPixel),
  18914. QPointF(keyPixel, openPixel));
  18915. // draw close:
  18916. painter->drawLine(QPointF(keyPixel, closePixel),
  18917. QPointF(keyPixel + keyWidthPixels, closePixel));
  18918. }
  18919. } else {
  18920. for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) {
  18921. if (mSelected)
  18922. linePen = mSelectedPen;
  18923. else if (mTwoColored)
  18924. linePen = it.value().close >= it.value().open ? mPenPositive : mPenNegative;
  18925. else
  18926. linePen = mPen;
  18927. painter->setPen(linePen);
  18928. double keyPixel = keyAxis->coordToPixel(it.value().key);
  18929. double openPixel = valueAxis->coordToPixel(it.value().open);
  18930. double closePixel = valueAxis->coordToPixel(it.value().close);
  18931. // draw backbone:
  18932. painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel),
  18933. QPointF(valueAxis->coordToPixel(it.value().low), keyPixel));
  18934. // draw open:
  18935. double keyWidthPixels =
  18936. keyPixel
  18937. - keyAxis->coordToPixel(
  18938. it.value().key
  18939. - mWidth * 0.5); // sign of this makes sure open/close are on correct sides
  18940. painter->drawLine(QPointF(openPixel, keyPixel - keyWidthPixels),
  18941. QPointF(openPixel, keyPixel));
  18942. // draw close:
  18943. painter->drawLine(QPointF(closePixel, keyPixel),
  18944. QPointF(closePixel, keyPixel + keyWidthPixels));
  18945. }
  18946. }
  18947. }
  18948. /*! \internal
  18949. Draws the data from \a begin to \a end as Candlesticks with the provided \a painter.
  18950. This method is a helper function for \ref draw. It is used when the chart style is \ref
  18951. csCandlestick.
  18952. */
  18953. void QCPFinancial::drawCandlestickPlot(QCPPainter* painter,
  18954. const QCPFinancialDataMap::const_iterator& begin,
  18955. const QCPFinancialDataMap::const_iterator& end)
  18956. {
  18957. QCPAxis* keyAxis = mKeyAxis.data();
  18958. QCPAxis* valueAxis = mValueAxis.data();
  18959. if (!keyAxis || !valueAxis) {
  18960. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  18961. return;
  18962. }
  18963. QPen linePen;
  18964. QBrush boxBrush;
  18965. if (keyAxis->orientation() == Qt::Horizontal) {
  18966. for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) {
  18967. if (mSelected) {
  18968. linePen = mSelectedPen;
  18969. boxBrush = mSelectedBrush;
  18970. } else if (mTwoColored) {
  18971. if (it.value().close >= it.value().open) {
  18972. linePen = mPenPositive;
  18973. boxBrush = mBrushPositive;
  18974. } else {
  18975. linePen = mPenNegative;
  18976. boxBrush = mBrushNegative;
  18977. }
  18978. } else {
  18979. linePen = mPen;
  18980. boxBrush = mBrush;
  18981. }
  18982. painter->setPen(linePen);
  18983. painter->setBrush(boxBrush);
  18984. double keyPixel = keyAxis->coordToPixel(it.value().key);
  18985. double openPixel = valueAxis->coordToPixel(it.value().open);
  18986. double closePixel = valueAxis->coordToPixel(it.value().close);
  18987. // draw high:
  18988. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)),
  18989. QPointF(keyPixel, valueAxis->coordToPixel(
  18990. qMax(it.value().open, it.value().close))));
  18991. // draw low:
  18992. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)),
  18993. QPointF(keyPixel, valueAxis->coordToPixel(
  18994. qMin(it.value().open, it.value().close))));
  18995. // draw open-close box:
  18996. double keyWidthPixels = keyPixel - keyAxis->coordToPixel(it.value().key - mWidth * 0.5);
  18997. painter->drawRect(QRectF(QPointF(keyPixel - keyWidthPixels, closePixel),
  18998. QPointF(keyPixel + keyWidthPixels, openPixel)));
  18999. }
  19000. } else // keyAxis->orientation() == Qt::Vertical
  19001. {
  19002. for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) {
  19003. if (mSelected) {
  19004. linePen = mSelectedPen;
  19005. boxBrush = mSelectedBrush;
  19006. } else if (mTwoColored) {
  19007. if (it.value().close >= it.value().open) {
  19008. linePen = mPenPositive;
  19009. boxBrush = mBrushPositive;
  19010. } else {
  19011. linePen = mPenNegative;
  19012. boxBrush = mBrushNegative;
  19013. }
  19014. } else {
  19015. linePen = mPen;
  19016. boxBrush = mBrush;
  19017. }
  19018. painter->setPen(linePen);
  19019. painter->setBrush(boxBrush);
  19020. double keyPixel = keyAxis->coordToPixel(it.value().key);
  19021. double openPixel = valueAxis->coordToPixel(it.value().open);
  19022. double closePixel = valueAxis->coordToPixel(it.value().close);
  19023. // draw high:
  19024. painter->drawLine(
  19025. QPointF(valueAxis->coordToPixel(it.value().high), keyPixel),
  19026. QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)),
  19027. keyPixel));
  19028. // draw low:
  19029. painter->drawLine(
  19030. QPointF(valueAxis->coordToPixel(it.value().low), keyPixel),
  19031. QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().close)),
  19032. keyPixel));
  19033. // draw open-close box:
  19034. double keyWidthPixels = keyPixel - keyAxis->coordToPixel(it.value().key - mWidth * 0.5);
  19035. painter->drawRect(QRectF(QPointF(closePixel, keyPixel - keyWidthPixels),
  19036. QPointF(openPixel, keyPixel + keyWidthPixels)));
  19037. }
  19038. }
  19039. }
  19040. /*! \internal
  19041. This method is a helper function for \ref selectTest. It is used to test for selection when the
  19042. chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end.
  19043. */
  19044. double QCPFinancial::ohlcSelectTest(const QPointF& pos,
  19045. const QCPFinancialDataMap::const_iterator& begin,
  19046. const QCPFinancialDataMap::const_iterator& end) const
  19047. {
  19048. QCPAxis* keyAxis = mKeyAxis.data();
  19049. QCPAxis* valueAxis = mValueAxis.data();
  19050. if (!keyAxis || !valueAxis) {
  19051. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  19052. return -1;
  19053. }
  19054. double minDistSqr = std::numeric_limits<double>::max();
  19055. QCPFinancialDataMap::const_iterator it;
  19056. if (keyAxis->orientation() == Qt::Horizontal) {
  19057. for (it = begin; it != end; ++it) {
  19058. double keyPixel = keyAxis->coordToPixel(it.value().key);
  19059. // calculate distance to backbone:
  19060. double currentDistSqr =
  19061. distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)),
  19062. QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), pos);
  19063. if (currentDistSqr < minDistSqr)
  19064. minDistSqr = currentDistSqr;
  19065. }
  19066. } else // keyAxis->orientation() == Qt::Vertical
  19067. {
  19068. for (it = begin; it != end; ++it) {
  19069. double keyPixel = keyAxis->coordToPixel(it.value().key);
  19070. // calculate distance to backbone:
  19071. double currentDistSqr =
  19072. distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel),
  19073. QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), pos);
  19074. if (currentDistSqr < minDistSqr)
  19075. minDistSqr = currentDistSqr;
  19076. }
  19077. }
  19078. return qSqrt(minDistSqr);
  19079. }
  19080. /*! \internal
  19081. This method is a helper function for \ref selectTest. It is used to test for selection when the
  19082. chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a
  19083. end.
  19084. */
  19085. double QCPFinancial::candlestickSelectTest(const QPointF& pos,
  19086. const QCPFinancialDataMap::const_iterator& begin,
  19087. const QCPFinancialDataMap::const_iterator& end) const
  19088. {
  19089. QCPAxis* keyAxis = mKeyAxis.data();
  19090. QCPAxis* valueAxis = mValueAxis.data();
  19091. if (!keyAxis || !valueAxis) {
  19092. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  19093. return -1;
  19094. }
  19095. double minDistSqr = std::numeric_limits<double>::max();
  19096. QCPFinancialDataMap::const_iterator it;
  19097. if (keyAxis->orientation() == Qt::Horizontal) {
  19098. for (it = begin; it != end; ++it) {
  19099. double currentDistSqr;
  19100. // determine whether pos is in open-close-box:
  19101. QCPRange boxKeyRange(it.value().key - mWidth * 0.5, it.value().key + mWidth * 0.5);
  19102. QCPRange boxValueRange(it.value().close, it.value().open);
  19103. double posKey, posValue;
  19104. pixelsToCoords(pos, posKey, posValue);
  19105. if (boxKeyRange.contains(posKey)
  19106. && boxValueRange.contains(posValue)) // is in open-close-box
  19107. {
  19108. currentDistSqr = mParentPlot->selectionTolerance() * 0.99
  19109. * mParentPlot->selectionTolerance() * 0.99;
  19110. } else {
  19111. // calculate distance to high/low lines:
  19112. double keyPixel = keyAxis->coordToPixel(it.value().key);
  19113. double highLineDistSqr = distSqrToLine(
  19114. QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)),
  19115. QPointF(keyPixel,
  19116. valueAxis->coordToPixel(qMax(it.value().open, it.value().close))),
  19117. pos);
  19118. double lowLineDistSqr = distSqrToLine(
  19119. QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)),
  19120. QPointF(keyPixel,
  19121. valueAxis->coordToPixel(qMin(it.value().open, it.value().close))),
  19122. pos);
  19123. currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
  19124. }
  19125. if (currentDistSqr < minDistSqr)
  19126. minDistSqr = currentDistSqr;
  19127. }
  19128. } else // keyAxis->orientation() == Qt::Vertical
  19129. {
  19130. for (it = begin; it != end; ++it) {
  19131. double currentDistSqr;
  19132. // determine whether pos is in open-close-box:
  19133. QCPRange boxKeyRange(it.value().key - mWidth * 0.5, it.value().key + mWidth * 0.5);
  19134. QCPRange boxValueRange(it.value().close, it.value().open);
  19135. double posKey, posValue;
  19136. pixelsToCoords(pos, posKey, posValue);
  19137. if (boxKeyRange.contains(posKey)
  19138. && boxValueRange.contains(posValue)) // is in open-close-box
  19139. {
  19140. currentDistSqr = mParentPlot->selectionTolerance() * 0.99
  19141. * mParentPlot->selectionTolerance() * 0.99;
  19142. } else {
  19143. // calculate distance to high/low lines:
  19144. double keyPixel = keyAxis->coordToPixel(it.value().key);
  19145. double highLineDistSqr = distSqrToLine(
  19146. QPointF(valueAxis->coordToPixel(it.value().high), keyPixel),
  19147. QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)),
  19148. keyPixel),
  19149. pos);
  19150. double lowLineDistSqr = distSqrToLine(
  19151. QPointF(valueAxis->coordToPixel(it.value().low), keyPixel),
  19152. QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().close)),
  19153. keyPixel),
  19154. pos);
  19155. currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
  19156. }
  19157. if (currentDistSqr < minDistSqr)
  19158. minDistSqr = currentDistSqr;
  19159. }
  19160. }
  19161. return qSqrt(minDistSqr);
  19162. }
  19163. /*! \internal
  19164. called by the drawing methods to determine which data (key) range is visible at the current key
  19165. axis range setting, so only that needs to be processed.
  19166. \a lower returns an iterator to the lowest data point that needs to be taken into account when
  19167. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  19168. lower may still be just outside the visible range.
  19169. \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie
  19170. just outside of the visible range.
  19171. if the plottable contains no data, both \a lower and \a upper point to constEnd.
  19172. \see QCPGraph::getVisibleDataBounds
  19173. */
  19174. void QCPFinancial::getVisibleDataBounds(QCPFinancialDataMap::const_iterator& lower,
  19175. QCPFinancialDataMap::const_iterator& upper) const
  19176. {
  19177. if (!mKeyAxis) {
  19178. qDebug() << Q_FUNC_INFO << "invalid key axis";
  19179. return;
  19180. }
  19181. if (mData->isEmpty()) {
  19182. lower = mData->constEnd();
  19183. upper = mData->constEnd();
  19184. return;
  19185. }
  19186. // get visible data range as QMap iterators
  19187. QCPFinancialDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower);
  19188. QCPFinancialDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper);
  19189. bool lowoutlier =
  19190. lbound != mData->constBegin(); // indicates whether there exist points below axis range
  19191. bool highoutlier =
  19192. ubound != mData->constEnd(); // indicates whether there exist points above axis range
  19193. lower = (lowoutlier ? lbound - 1 : lbound); // data point range that will be actually drawn
  19194. upper = (highoutlier ? ubound : ubound - 1); // data point range that will be actually drawn
  19195. }
  19196. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19197. //////////////////// QCPItemStraightLine
  19198. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19199. /*! \class QCPItemStraightLine
  19200. \brief A straight line that spans infinitely in both directions
  19201. \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid
  19202. blue discs are positions."
  19203. It has two positions, \a point1 and \a point2, which define the straight line.
  19204. */
  19205. /*!
  19206. Creates a straight line item and sets default values.
  19207. The constructed item can be added to the plot with QCustomPlot::addItem.
  19208. */
  19209. QCPItemStraightLine::QCPItemStraightLine(QCustomPlot* parentPlot)
  19210. : QCPAbstractItem(parentPlot)
  19211. , point1(createPosition(QLatin1String("point1")))
  19212. , point2(createPosition(QLatin1String("point2")))
  19213. {
  19214. point1->setCoords(0, 0);
  19215. point2->setCoords(1, 1);
  19216. setPen(QPen(Qt::black));
  19217. setSelectedPen(QPen(Qt::blue, 2));
  19218. }
  19219. QCPItemStraightLine::~QCPItemStraightLine()
  19220. {}
  19221. /*!
  19222. Sets the pen that will be used to draw the line
  19223. \see setSelectedPen
  19224. */
  19225. void QCPItemStraightLine::setPen(const QPen& pen)
  19226. {
  19227. mPen = pen;
  19228. }
  19229. /*!
  19230. Sets the pen that will be used to draw the line when selected
  19231. \see setPen, setSelected
  19232. */
  19233. void QCPItemStraightLine::setSelectedPen(const QPen& pen)
  19234. {
  19235. mSelectedPen = pen;
  19236. }
  19237. /* inherits documentation from base class */
  19238. double QCPItemStraightLine::selectTest(const QPointF& pos, bool onlySelectable,
  19239. QVariant* details) const
  19240. {
  19241. Q_UNUSED(details)
  19242. if (onlySelectable && !mSelectable)
  19243. return -1;
  19244. return distToStraightLine(QVector2D(point1->pixelPoint()),
  19245. QVector2D(point2->pixelPoint() - point1->pixelPoint()),
  19246. QVector2D(pos));
  19247. }
  19248. /* inherits documentation from base class */
  19249. void QCPItemStraightLine::draw(QCPPainter* painter)
  19250. {
  19251. QVector2D start(point1->pixelPoint());
  19252. QVector2D end(point2->pixelPoint());
  19253. // get visible segment of straight line inside clipRect:
  19254. double clipPad = mainPen().widthF();
  19255. QLineF line = getRectClippedStraightLine(
  19256. start, end - start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  19257. // paint visible segment, if existent:
  19258. if (!line.isNull()) {
  19259. painter->setPen(mainPen());
  19260. painter->drawLine(line);
  19261. }
  19262. }
  19263. /*! \internal
  19264. finds the shortest distance of \a point to the straight line defined by the base point \a
  19265. base and the direction vector \a vec.
  19266. This is a helper function for \ref selectTest.
  19267. */
  19268. double QCPItemStraightLine::distToStraightLine(const QVector2D& base, const QVector2D& vec,
  19269. const QVector2D& point) const
  19270. {
  19271. return qAbs((base.y() - point.y()) * vec.x() - (base.x() - point.x()) * vec.y()) / vec.length();
  19272. }
  19273. /*! \internal
  19274. Returns the section of the straight line defined by \a base and direction vector \a
  19275. vec, that is visible in the specified \a rect.
  19276. This is a helper function for \ref draw.
  19277. */
  19278. QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D& base, const QVector2D& vec,
  19279. const QRect& rect) const
  19280. {
  19281. double bx, by;
  19282. double gamma;
  19283. QLineF result;
  19284. if (vec.x() == 0 && vec.y() == 0)
  19285. return result;
  19286. if (qFuzzyIsNull(vec.x())) // line is vertical
  19287. {
  19288. // check top of rect:
  19289. bx = rect.left();
  19290. by = rect.top();
  19291. gamma = base.x() - bx + (by - base.y()) * vec.x() / vec.y();
  19292. if (gamma >= 0 && gamma <= rect.width())
  19293. result.setLine(
  19294. bx + gamma, rect.top(), bx + gamma,
  19295. rect.bottom()); // no need to check bottom because we know line is vertical
  19296. } else if (qFuzzyIsNull(vec.y())) // line is horizontal
  19297. {
  19298. // check left of rect:
  19299. bx = rect.left();
  19300. by = rect.top();
  19301. gamma = base.y() - by + (bx - base.x()) * vec.y() / vec.x();
  19302. if (gamma >= 0 && gamma <= rect.height())
  19303. result.setLine(rect.left(), by + gamma, rect.right(),
  19304. by + gamma); // no need to check right because we know line is horizontal
  19305. } else // line is skewed
  19306. {
  19307. QList<QVector2D> pointVectors;
  19308. // check top of rect:
  19309. bx = rect.left();
  19310. by = rect.top();
  19311. gamma = base.x() - bx + (by - base.y()) * vec.x() / vec.y();
  19312. if (gamma >= 0 && gamma <= rect.width())
  19313. pointVectors.append(QVector2D(bx + gamma, by));
  19314. // check bottom of rect:
  19315. bx = rect.left();
  19316. by = rect.bottom();
  19317. gamma = base.x() - bx + (by - base.y()) * vec.x() / vec.y();
  19318. if (gamma >= 0 && gamma <= rect.width())
  19319. pointVectors.append(QVector2D(bx + gamma, by));
  19320. // check left of rect:
  19321. bx = rect.left();
  19322. by = rect.top();
  19323. gamma = base.y() - by + (bx - base.x()) * vec.y() / vec.x();
  19324. if (gamma >= 0 && gamma <= rect.height())
  19325. pointVectors.append(QVector2D(bx, by + gamma));
  19326. // check right of rect:
  19327. bx = rect.right();
  19328. by = rect.top();
  19329. gamma = base.y() - by + (bx - base.x()) * vec.y() / vec.x();
  19330. if (gamma >= 0 && gamma <= rect.height())
  19331. pointVectors.append(QVector2D(bx, by + gamma));
  19332. // evaluate points:
  19333. if (pointVectors.size() == 2) {
  19334. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  19335. } else if (pointVectors.size() > 2) {
  19336. // line probably goes through corner of rect, and we got two points there. single out
  19337. // the point pair with greatest distance:
  19338. double distSqrMax = 0;
  19339. QVector2D pv1, pv2;
  19340. for (int i = 0; i < pointVectors.size() - 1; ++i) {
  19341. for (int k = i + 1; k < pointVectors.size(); ++k) {
  19342. double distSqr = (pointVectors.at(i) - pointVectors.at(k)).lengthSquared();
  19343. if (distSqr > distSqrMax) {
  19344. pv1 = pointVectors.at(i);
  19345. pv2 = pointVectors.at(k);
  19346. distSqrMax = distSqr;
  19347. }
  19348. }
  19349. }
  19350. result.setPoints(pv1.toPointF(), pv2.toPointF());
  19351. }
  19352. }
  19353. return result;
  19354. }
  19355. /*! \internal
  19356. Returns the pen that should be used for drawing lines. Returns mPen when the
  19357. item is not selected and mSelectedPen when it is.
  19358. */
  19359. QPen QCPItemStraightLine::mainPen() const
  19360. {
  19361. return mSelected ? mSelectedPen : mPen;
  19362. }
  19363. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19364. //////////////////// QCPItemLine
  19365. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19366. /*! \class QCPItemLine
  19367. \brief A line from one point to another
  19368. \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are
  19369. positions."
  19370. It has two positions, \a start and \a end, which define the end points of the line.
  19371. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an
  19372. arrow.
  19373. */
  19374. /*!
  19375. Creates a line item and sets default values.
  19376. The constructed item can be added to the plot with QCustomPlot::addItem.
  19377. */
  19378. QCPItemLine::QCPItemLine(QCustomPlot* parentPlot)
  19379. : QCPAbstractItem(parentPlot)
  19380. , start(createPosition(QLatin1String("start")))
  19381. , end(createPosition(QLatin1String("end")))
  19382. {
  19383. start->setCoords(0, 0);
  19384. end->setCoords(1, 1);
  19385. setPen(QPen(Qt::black));
  19386. setSelectedPen(QPen(Qt::blue, 2));
  19387. }
  19388. QCPItemLine::~QCPItemLine()
  19389. {}
  19390. /*!
  19391. Sets the pen that will be used to draw the line
  19392. \see setSelectedPen
  19393. */
  19394. void QCPItemLine::setPen(const QPen& pen)
  19395. {
  19396. mPen = pen;
  19397. }
  19398. /*!
  19399. Sets the pen that will be used to draw the line when selected
  19400. \see setPen, setSelected
  19401. */
  19402. void QCPItemLine::setSelectedPen(const QPen& pen)
  19403. {
  19404. mSelectedPen = pen;
  19405. }
  19406. /*!
  19407. Sets the line ending style of the head. The head corresponds to the \a end position.
  19408. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  19409. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  19410. \see setTail
  19411. */
  19412. void QCPItemLine::setHead(const QCPLineEnding& head)
  19413. {
  19414. mHead = head;
  19415. }
  19416. /*!
  19417. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  19418. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  19419. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  19420. \see setHead
  19421. */
  19422. void QCPItemLine::setTail(const QCPLineEnding& tail)
  19423. {
  19424. mTail = tail;
  19425. }
  19426. /* inherits documentation from base class */
  19427. double QCPItemLine::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  19428. {
  19429. Q_UNUSED(details)
  19430. if (onlySelectable && !mSelectable)
  19431. return -1;
  19432. return qSqrt(distSqrToLine(start->pixelPoint(), end->pixelPoint(), pos));
  19433. }
  19434. /* inherits documentation from base class */
  19435. void QCPItemLine::draw(QCPPainter* painter)
  19436. {
  19437. QVector2D startVec(start->pixelPoint());
  19438. QVector2D endVec(end->pixelPoint());
  19439. if (startVec.toPoint() == endVec.toPoint())
  19440. return;
  19441. // get visible segment of straight line inside clipRect:
  19442. double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance());
  19443. clipPad = qMax(clipPad, (double)mainPen().widthF());
  19444. QLineF line = getRectClippedLine(startVec, endVec,
  19445. clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  19446. // paint visible segment, if existent:
  19447. if (!line.isNull()) {
  19448. painter->setPen(mainPen());
  19449. painter->drawLine(line);
  19450. painter->setBrush(Qt::SolidPattern);
  19451. if (mTail.style() != QCPLineEnding::esNone)
  19452. mTail.draw(painter, startVec, startVec - endVec);
  19453. if (mHead.style() != QCPLineEnding::esNone)
  19454. mHead.draw(painter, endVec, endVec - startVec);
  19455. }
  19456. }
  19457. /*! \internal
  19458. Returns the section of the line defined by \a start and \a end, that is visible in the specified
  19459. \a rect.
  19460. This is a helper function for \ref draw.
  19461. */
  19462. QLineF QCPItemLine::getRectClippedLine(const QVector2D& start, const QVector2D& end,
  19463. const QRect& rect) const
  19464. {
  19465. bool containsStart = rect.contains(start.x(), start.y());
  19466. bool containsEnd = rect.contains(end.x(), end.y());
  19467. if (containsStart && containsEnd)
  19468. return QLineF(start.toPointF(), end.toPointF());
  19469. QVector2D base = start;
  19470. QVector2D vec = end - start;
  19471. double bx, by;
  19472. double gamma, mu;
  19473. QLineF result;
  19474. QList<QVector2D> pointVectors;
  19475. if (!qFuzzyIsNull(vec.y())) // line is not horizontal
  19476. {
  19477. // check top of rect:
  19478. bx = rect.left();
  19479. by = rect.top();
  19480. mu = (by - base.y()) / vec.y();
  19481. if (mu >= 0 && mu <= 1) {
  19482. gamma = base.x() - bx + mu * vec.x();
  19483. if (gamma >= 0 && gamma <= rect.width())
  19484. pointVectors.append(QVector2D(bx + gamma, by));
  19485. }
  19486. // check bottom of rect:
  19487. bx = rect.left();
  19488. by = rect.bottom();
  19489. mu = (by - base.y()) / vec.y();
  19490. if (mu >= 0 && mu <= 1) {
  19491. gamma = base.x() - bx + mu * vec.x();
  19492. if (gamma >= 0 && gamma <= rect.width())
  19493. pointVectors.append(QVector2D(bx + gamma, by));
  19494. }
  19495. }
  19496. if (!qFuzzyIsNull(vec.x())) // line is not vertical
  19497. {
  19498. // check left of rect:
  19499. bx = rect.left();
  19500. by = rect.top();
  19501. mu = (bx - base.x()) / vec.x();
  19502. if (mu >= 0 && mu <= 1) {
  19503. gamma = base.y() - by + mu * vec.y();
  19504. if (gamma >= 0 && gamma <= rect.height())
  19505. pointVectors.append(QVector2D(bx, by + gamma));
  19506. }
  19507. // check right of rect:
  19508. bx = rect.right();
  19509. by = rect.top();
  19510. mu = (bx - base.x()) / vec.x();
  19511. if (mu >= 0 && mu <= 1) {
  19512. gamma = base.y() - by + mu * vec.y();
  19513. if (gamma >= 0 && gamma <= rect.height())
  19514. pointVectors.append(QVector2D(bx, by + gamma));
  19515. }
  19516. }
  19517. if (containsStart)
  19518. pointVectors.append(start);
  19519. if (containsEnd)
  19520. pointVectors.append(end);
  19521. // evaluate points:
  19522. if (pointVectors.size() == 2) {
  19523. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  19524. } else if (pointVectors.size() > 2) {
  19525. // line probably goes through corner of rect, and we got two points there. single out the
  19526. // point pair with greatest distance:
  19527. double distSqrMax = 0;
  19528. QVector2D pv1, pv2;
  19529. for (int i = 0; i < pointVectors.size() - 1; ++i) {
  19530. for (int k = i + 1; k < pointVectors.size(); ++k) {
  19531. double distSqr = (pointVectors.at(i) - pointVectors.at(k)).lengthSquared();
  19532. if (distSqr > distSqrMax) {
  19533. pv1 = pointVectors.at(i);
  19534. pv2 = pointVectors.at(k);
  19535. distSqrMax = distSqr;
  19536. }
  19537. }
  19538. }
  19539. result.setPoints(pv1.toPointF(), pv2.toPointF());
  19540. }
  19541. return result;
  19542. }
  19543. /*! \internal
  19544. Returns the pen that should be used for drawing lines. Returns mPen when the
  19545. item is not selected and mSelectedPen when it is.
  19546. */
  19547. QPen QCPItemLine::mainPen() const
  19548. {
  19549. return mSelected ? mSelectedPen : mPen;
  19550. }
  19551. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19552. //////////////////// QCPItemCurve
  19553. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19554. /*! \class QCPItemCurve
  19555. \brief A curved line from one point to another
  19556. \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are
  19557. positions."
  19558. It has four positions, \a start and \a end, which define the end points of the line, and two
  19559. control points which define the direction the line exits from the start and the direction from
  19560. which it approaches the end: \a startDir and \a endDir.
  19561. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an
  19562. arrow.
  19563. Often it is desirable for the control points to stay at fixed relative positions to the start/end
  19564. point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start,
  19565. and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir.
  19566. */
  19567. /*!
  19568. Creates a curve item and sets default values.
  19569. The constructed item can be added to the plot with QCustomPlot::addItem.
  19570. */
  19571. QCPItemCurve::QCPItemCurve(QCustomPlot* parentPlot)
  19572. : QCPAbstractItem(parentPlot)
  19573. , start(createPosition(QLatin1String("start")))
  19574. , startDir(createPosition(QLatin1String("startDir")))
  19575. , endDir(createPosition(QLatin1String("endDir")))
  19576. , end(createPosition(QLatin1String("end")))
  19577. {
  19578. start->setCoords(0, 0);
  19579. startDir->setCoords(0.5, 0);
  19580. endDir->setCoords(0, 0.5);
  19581. end->setCoords(1, 1);
  19582. setPen(QPen(Qt::black));
  19583. setSelectedPen(QPen(Qt::blue, 2));
  19584. }
  19585. QCPItemCurve::~QCPItemCurve()
  19586. {}
  19587. /*!
  19588. Sets the pen that will be used to draw the line
  19589. \see setSelectedPen
  19590. */
  19591. void QCPItemCurve::setPen(const QPen& pen)
  19592. {
  19593. mPen = pen;
  19594. }
  19595. /*!
  19596. Sets the pen that will be used to draw the line when selected
  19597. \see setPen, setSelected
  19598. */
  19599. void QCPItemCurve::setSelectedPen(const QPen& pen)
  19600. {
  19601. mSelectedPen = pen;
  19602. }
  19603. /*!
  19604. Sets the line ending style of the head. The head corresponds to the \a end position.
  19605. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  19606. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  19607. \see setTail
  19608. */
  19609. void QCPItemCurve::setHead(const QCPLineEnding& head)
  19610. {
  19611. mHead = head;
  19612. }
  19613. /*!
  19614. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  19615. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  19616. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  19617. \see setHead
  19618. */
  19619. void QCPItemCurve::setTail(const QCPLineEnding& tail)
  19620. {
  19621. mTail = tail;
  19622. }
  19623. /* inherits documentation from base class */
  19624. double QCPItemCurve::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  19625. {
  19626. Q_UNUSED(details)
  19627. if (onlySelectable && !mSelectable)
  19628. return -1;
  19629. QPointF startVec(start->pixelPoint());
  19630. QPointF startDirVec(startDir->pixelPoint());
  19631. QPointF endDirVec(endDir->pixelPoint());
  19632. QPointF endVec(end->pixelPoint());
  19633. QPainterPath cubicPath(startVec);
  19634. cubicPath.cubicTo(startDirVec, endDirVec, endVec);
  19635. QPolygonF polygon = cubicPath.toSubpathPolygons().first();
  19636. double minDistSqr = std::numeric_limits<double>::max();
  19637. for (int i = 1; i < polygon.size(); ++i) {
  19638. double distSqr = distSqrToLine(polygon.at(i - 1), polygon.at(i), pos);
  19639. if (distSqr < minDistSqr)
  19640. minDistSqr = distSqr;
  19641. }
  19642. return qSqrt(minDistSqr);
  19643. }
  19644. /* inherits documentation from base class */
  19645. void QCPItemCurve::draw(QCPPainter* painter)
  19646. {
  19647. QPointF startVec(start->pixelPoint());
  19648. QPointF startDirVec(startDir->pixelPoint());
  19649. QPointF endDirVec(endDir->pixelPoint());
  19650. QPointF endVec(end->pixelPoint());
  19651. if (QVector2D(endVec - startVec).length() > 1e10f) // too large curves cause crash
  19652. return;
  19653. QPainterPath cubicPath(startVec);
  19654. cubicPath.cubicTo(startDirVec, endDirVec, endVec);
  19655. // paint visible segment, if existent:
  19656. QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(),
  19657. mainPen().widthF());
  19658. QRect cubicRect = cubicPath.controlPointRect().toRect();
  19659. if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position
  19660. cubicRect.adjust(0, 0, 1, 1);
  19661. if (clip.intersects(cubicRect)) {
  19662. painter->setPen(mainPen());
  19663. painter->drawPath(cubicPath);
  19664. painter->setBrush(Qt::SolidPattern);
  19665. if (mTail.style() != QCPLineEnding::esNone)
  19666. mTail.draw(painter, QVector2D(startVec),
  19667. M_PI - cubicPath.angleAtPercent(0) / 180.0 * M_PI);
  19668. if (mHead.style() != QCPLineEnding::esNone)
  19669. mHead.draw(painter, QVector2D(endVec), -cubicPath.angleAtPercent(1) / 180.0 * M_PI);
  19670. }
  19671. }
  19672. /*! \internal
  19673. Returns the pen that should be used for drawing lines. Returns mPen when the
  19674. item is not selected and mSelectedPen when it is.
  19675. */
  19676. QPen QCPItemCurve::mainPen() const
  19677. {
  19678. return mSelected ? mSelectedPen : mPen;
  19679. }
  19680. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19681. //////////////////// QCPItemRect
  19682. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19683. /*! \class QCPItemRect
  19684. \brief A rectangle
  19685. \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs
  19686. are positions."
  19687. It has two positions, \a topLeft and \a bottomRight, which define the rectangle.
  19688. */
  19689. /*!
  19690. Creates a rectangle item and sets default values.
  19691. The constructed item can be added to the plot with QCustomPlot::addItem.
  19692. */
  19693. QCPItemRect::QCPItemRect(QCustomPlot* parentPlot)
  19694. : QCPAbstractItem(parentPlot)
  19695. , topLeft(createPosition(QLatin1String("topLeft")))
  19696. , bottomRight(createPosition(QLatin1String("bottomRight")))
  19697. , top(createAnchor(QLatin1String("top"), aiTop))
  19698. , topRight(createAnchor(QLatin1String("topRight"), aiTopRight))
  19699. , right(createAnchor(QLatin1String("right"), aiRight))
  19700. , bottom(createAnchor(QLatin1String("bottom"), aiBottom))
  19701. , bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft))
  19702. , left(createAnchor(QLatin1String("left"), aiLeft))
  19703. {
  19704. topLeft->setCoords(0, 1);
  19705. bottomRight->setCoords(1, 0);
  19706. setPen(QPen(Qt::black));
  19707. setSelectedPen(QPen(Qt::blue, 2));
  19708. setBrush(Qt::NoBrush);
  19709. setSelectedBrush(Qt::NoBrush);
  19710. }
  19711. QCPItemRect::~QCPItemRect()
  19712. {}
  19713. /*!
  19714. Sets the pen that will be used to draw the line of the rectangle
  19715. \see setSelectedPen, setBrush
  19716. */
  19717. void QCPItemRect::setPen(const QPen& pen)
  19718. {
  19719. mPen = pen;
  19720. }
  19721. /*!
  19722. Sets the pen that will be used to draw the line of the rectangle when selected
  19723. \see setPen, setSelected
  19724. */
  19725. void QCPItemRect::setSelectedPen(const QPen& pen)
  19726. {
  19727. mSelectedPen = pen;
  19728. }
  19729. /*!
  19730. Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to
  19731. Qt::NoBrush.
  19732. \see setSelectedBrush, setPen
  19733. */
  19734. void QCPItemRect::setBrush(const QBrush& brush)
  19735. {
  19736. mBrush = brush;
  19737. }
  19738. /*!
  19739. Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a
  19740. brush to Qt::NoBrush.
  19741. \see setBrush
  19742. */
  19743. void QCPItemRect::setSelectedBrush(const QBrush& brush)
  19744. {
  19745. mSelectedBrush = brush;
  19746. }
  19747. /* inherits documentation from base class */
  19748. double QCPItemRect::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  19749. {
  19750. Q_UNUSED(details)
  19751. if (onlySelectable && !mSelectable)
  19752. return -1;
  19753. QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized();
  19754. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  19755. return rectSelectTest(rect, pos, filledRect);
  19756. }
  19757. /* inherits documentation from base class */
  19758. void QCPItemRect::draw(QCPPainter* painter)
  19759. {
  19760. QPointF p1 = topLeft->pixelPoint();
  19761. QPointF p2 = bottomRight->pixelPoint();
  19762. if (p1.toPoint() == p2.toPoint())
  19763. return;
  19764. QRectF rect = QRectF(p1, p2).normalized();
  19765. double clipPad = mainPen().widthF();
  19766. QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  19767. if (boundingRect.intersects(
  19768. clipRect())) // only draw if bounding rect of rect item is visible in cliprect
  19769. {
  19770. painter->setPen(mainPen());
  19771. painter->setBrush(mainBrush());
  19772. painter->drawRect(rect);
  19773. }
  19774. }
  19775. /* inherits documentation from base class */
  19776. QPointF QCPItemRect::anchorPixelPoint(int anchorId) const
  19777. {
  19778. QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint());
  19779. switch (anchorId) {
  19780. case aiTop:
  19781. return (rect.topLeft() + rect.topRight()) * 0.5;
  19782. case aiTopRight:
  19783. return rect.topRight();
  19784. case aiRight:
  19785. return (rect.topRight() + rect.bottomRight()) * 0.5;
  19786. case aiBottom:
  19787. return (rect.bottomLeft() + rect.bottomRight()) * 0.5;
  19788. case aiBottomLeft:
  19789. return rect.bottomLeft();
  19790. case aiLeft:
  19791. return (rect.topLeft() + rect.bottomLeft()) * 0.5;
  19792. }
  19793. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  19794. return QPointF();
  19795. }
  19796. /*! \internal
  19797. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  19798. and mSelectedPen when it is.
  19799. */
  19800. QPen QCPItemRect::mainPen() const
  19801. {
  19802. return mSelected ? mSelectedPen : mPen;
  19803. }
  19804. /*! \internal
  19805. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  19806. is not selected and mSelectedBrush when it is.
  19807. */
  19808. QBrush QCPItemRect::mainBrush() const
  19809. {
  19810. return mSelected ? mSelectedBrush : mBrush;
  19811. }
  19812. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19813. //////////////////// QCPItemText
  19814. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19815. /*! \class QCPItemText
  19816. \brief A text label
  19817. \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are
  19818. positions."
  19819. Its position is defined by the member \a position and the setting of \ref setPositionAlignment.
  19820. The latter controls which part of the text rect shall be aligned with \a position.
  19821. The text alignment itself (i.e. left, center, right) can be controlled with \ref
  19822. setTextAlignment.
  19823. The text may be rotated around the \a position point with \ref setRotation.
  19824. */
  19825. /*!
  19826. Creates a text item and sets default values.
  19827. The constructed item can be added to the plot with QCustomPlot::addItem.
  19828. */
  19829. QCPItemText::QCPItemText(QCustomPlot* parentPlot)
  19830. : QCPAbstractItem(parentPlot)
  19831. , position(createPosition(QLatin1String("position")))
  19832. , topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft))
  19833. , top(createAnchor(QLatin1String("top"), aiTop))
  19834. , topRight(createAnchor(QLatin1String("topRight"), aiTopRight))
  19835. , right(createAnchor(QLatin1String("right"), aiRight))
  19836. , bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight))
  19837. , bottom(createAnchor(QLatin1String("bottom"), aiBottom))
  19838. , bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft))
  19839. , left(createAnchor(QLatin1String("left"), aiLeft))
  19840. {
  19841. position->setCoords(0, 0);
  19842. setRotation(0);
  19843. setTextAlignment(Qt::AlignTop | Qt::AlignHCenter);
  19844. setPositionAlignment(Qt::AlignCenter);
  19845. setText(QLatin1String("text"));
  19846. setPen(Qt::NoPen);
  19847. setSelectedPen(Qt::NoPen);
  19848. setBrush(Qt::NoBrush);
  19849. setSelectedBrush(Qt::NoBrush);
  19850. setColor(Qt::black);
  19851. setSelectedColor(Qt::blue);
  19852. }
  19853. QCPItemText::~QCPItemText()
  19854. {}
  19855. /*!
  19856. Sets the color of the text.
  19857. */
  19858. void QCPItemText::setColor(const QColor& color)
  19859. {
  19860. mColor = color;
  19861. }
  19862. /*!
  19863. Sets the color of the text that will be used when the item is selected.
  19864. */
  19865. void QCPItemText::setSelectedColor(const QColor& color)
  19866. {
  19867. mSelectedColor = color;
  19868. }
  19869. /*!
  19870. Sets the pen that will be used do draw a rectangular border around the text. To disable the
  19871. border, set \a pen to Qt::NoPen.
  19872. \see setSelectedPen, setBrush, setPadding
  19873. */
  19874. void QCPItemText::setPen(const QPen& pen)
  19875. {
  19876. mPen = pen;
  19877. }
  19878. /*!
  19879. Sets the pen that will be used do draw a rectangular border around the text, when the item is
  19880. selected. To disable the border, set \a pen to Qt::NoPen.
  19881. \see setPen
  19882. */
  19883. void QCPItemText::setSelectedPen(const QPen& pen)
  19884. {
  19885. mSelectedPen = pen;
  19886. }
  19887. /*!
  19888. Sets the brush that will be used do fill the background of the text. To disable the
  19889. background, set \a brush to Qt::NoBrush.
  19890. \see setSelectedBrush, setPen, setPadding
  19891. */
  19892. void QCPItemText::setBrush(const QBrush& brush)
  19893. {
  19894. mBrush = brush;
  19895. }
  19896. /*!
  19897. Sets the brush that will be used do fill the background of the text, when the item is selected. To
  19898. disable the background, set \a brush to Qt::NoBrush.
  19899. \see setBrush
  19900. */
  19901. void QCPItemText::setSelectedBrush(const QBrush& brush)
  19902. {
  19903. mSelectedBrush = brush;
  19904. }
  19905. /*!
  19906. Sets the font of the text.
  19907. \see setSelectedFont, setColor
  19908. */
  19909. void QCPItemText::setFont(const QFont& font)
  19910. {
  19911. mFont = font;
  19912. }
  19913. /*!
  19914. Sets the font of the text that will be used when the item is selected.
  19915. \see setFont
  19916. */
  19917. void QCPItemText::setSelectedFont(const QFont& font)
  19918. {
  19919. mSelectedFont = font;
  19920. }
  19921. /*!
  19922. Sets the text that will be displayed. Multi-line texts are supported by inserting a line break
  19923. character, e.g. '\n'.
  19924. \see setFont, setColor, setTextAlignment
  19925. */
  19926. void QCPItemText::setText(const QString& text)
  19927. {
  19928. mText = text;
  19929. }
  19930. /*!
  19931. Sets which point of the text rect shall be aligned with \a position.
  19932. Examples:
  19933. \li If \a alignment is <tt>Qt::AlignHCenter | Qt::AlignTop</tt>, the text will be positioned such
  19934. that the top of the text rect will be horizontally centered on \a position.
  19935. \li If \a alignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt>, \a position will indicate the
  19936. bottom left corner of the text rect.
  19937. If you want to control the alignment of (multi-lined) text within the text rect, use \ref
  19938. setTextAlignment.
  19939. */
  19940. void QCPItemText::setPositionAlignment(Qt::Alignment alignment)
  19941. {
  19942. mPositionAlignment = alignment;
  19943. }
  19944. /*!
  19945. Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft,
  19946. Qt::AlignCenter or Qt::AlignRight).
  19947. */
  19948. void QCPItemText::setTextAlignment(Qt::Alignment alignment)
  19949. {
  19950. mTextAlignment = alignment;
  19951. }
  19952. /*!
  19953. Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated
  19954. around \a position.
  19955. */
  19956. void QCPItemText::setRotation(double degrees)
  19957. {
  19958. mRotation = degrees;
  19959. }
  19960. /*!
  19961. Sets the distance between the border of the text rectangle and the text. The appearance (and
  19962. visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush.
  19963. */
  19964. void QCPItemText::setPadding(const QMargins& padding)
  19965. {
  19966. mPadding = padding;
  19967. }
  19968. /* inherits documentation from base class */
  19969. double QCPItemText::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  19970. {
  19971. Q_UNUSED(details)
  19972. if (onlySelectable && !mSelectable)
  19973. return -1;
  19974. // The rect may be rotated, so we transform the actual clicked pos to the rotated
  19975. // coordinate system, so we can use the normal rectSelectTest function for non-rotated rects:
  19976. QPointF positionPixels(position->pixelPoint());
  19977. QTransform inputTransform;
  19978. inputTransform.translate(positionPixels.x(), positionPixels.y());
  19979. inputTransform.rotate(-mRotation);
  19980. inputTransform.translate(-positionPixels.x(), -positionPixels.y());
  19981. QPointF rotatedPos = inputTransform.map(pos);
  19982. QFontMetrics fontMetrics(mFont);
  19983. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, mText);
  19984. QRect textBoxRect =
  19985. textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  19986. QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment);
  19987. textBoxRect.moveTopLeft(textPos.toPoint());
  19988. return rectSelectTest(textBoxRect, rotatedPos, true);
  19989. }
  19990. /* inherits documentation from base class */
  19991. void QCPItemText::draw(QCPPainter* painter)
  19992. {
  19993. QPointF pos(position->pixelPoint());
  19994. QTransform transform = painter->transform();
  19995. transform.translate(pos.x(), pos.y());
  19996. if (!qFuzzyIsNull(mRotation))
  19997. transform.rotate(mRotation);
  19998. painter->setFont(mainFont());
  19999. QRect textRect =
  20000. painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, mText);
  20001. QRect textBoxRect =
  20002. textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  20003. QPointF textPos =
  20004. getTextDrawPoint(QPointF(0, 0), textBoxRect,
  20005. mPositionAlignment); // 0, 0 because the transform does the translation
  20006. textRect.moveTopLeft(textPos.toPoint() + QPoint(mPadding.left(), mPadding.top()));
  20007. textBoxRect.moveTopLeft(textPos.toPoint());
  20008. double clipPad = mainPen().widthF();
  20009. QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  20010. if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect()))) {
  20011. painter->setTransform(transform);
  20012. if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0)
  20013. || (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)) {
  20014. painter->setPen(mainPen());
  20015. painter->setBrush(mainBrush());
  20016. painter->drawRect(textBoxRect);
  20017. }
  20018. painter->setBrush(Qt::NoBrush);
  20019. painter->setPen(QPen(mainColor()));
  20020. painter->drawText(textRect, Qt::TextDontClip | mTextAlignment, mText);
  20021. }
  20022. }
  20023. /* inherits documentation from base class */
  20024. QPointF QCPItemText::anchorPixelPoint(int anchorId) const
  20025. {
  20026. // get actual rect points (pretty much copied from draw function):
  20027. QPointF pos(position->pixelPoint());
  20028. QTransform transform;
  20029. transform.translate(pos.x(), pos.y());
  20030. if (!qFuzzyIsNull(mRotation))
  20031. transform.rotate(mRotation);
  20032. QFontMetrics fontMetrics(mainFont());
  20033. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, mText);
  20034. QRectF textBoxRect =
  20035. textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  20036. QPointF textPos =
  20037. getTextDrawPoint(QPointF(0, 0), textBoxRect,
  20038. mPositionAlignment); // 0, 0 because the transform does the translation
  20039. textBoxRect.moveTopLeft(textPos.toPoint());
  20040. QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect));
  20041. switch (anchorId) {
  20042. case aiTopLeft:
  20043. return rectPoly.at(0);
  20044. case aiTop:
  20045. return (rectPoly.at(0) + rectPoly.at(1)) * 0.5;
  20046. case aiTopRight:
  20047. return rectPoly.at(1);
  20048. case aiRight:
  20049. return (rectPoly.at(1) + rectPoly.at(2)) * 0.5;
  20050. case aiBottomRight:
  20051. return rectPoly.at(2);
  20052. case aiBottom:
  20053. return (rectPoly.at(2) + rectPoly.at(3)) * 0.5;
  20054. case aiBottomLeft:
  20055. return rectPoly.at(3);
  20056. case aiLeft:
  20057. return (rectPoly.at(3) + rectPoly.at(0)) * 0.5;
  20058. }
  20059. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  20060. return QPointF();
  20061. }
  20062. /*! \internal
  20063. Returns the point that must be given to the QPainter::drawText function (which expects the top
  20064. left point of the text rect), according to the position \a pos, the text bounding box \a rect and
  20065. the requested \a positionAlignment.
  20066. For example, if \a positionAlignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt> the returned
  20067. point will be shifted upward by the height of \a rect, starting from \a pos. So if the text is
  20068. finally drawn at that point, the lower left corner of the resulting text rect is at \a pos.
  20069. */
  20070. QPointF QCPItemText::getTextDrawPoint(const QPointF& pos, const QRectF& rect,
  20071. Qt::Alignment positionAlignment) const
  20072. {
  20073. if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft | Qt::AlignTop))
  20074. return pos;
  20075. QPointF result = pos; // start at top left
  20076. if (positionAlignment.testFlag(Qt::AlignHCenter))
  20077. result.rx() -= rect.width() / 2.0;
  20078. else if (positionAlignment.testFlag(Qt::AlignRight))
  20079. result.rx() -= rect.width();
  20080. if (positionAlignment.testFlag(Qt::AlignVCenter))
  20081. result.ry() -= rect.height() / 2.0;
  20082. else if (positionAlignment.testFlag(Qt::AlignBottom))
  20083. result.ry() -= rect.height();
  20084. return result;
  20085. }
  20086. /*! \internal
  20087. Returns the font that should be used for drawing text. Returns mFont when the item is not selected
  20088. and mSelectedFont when it is.
  20089. */
  20090. QFont QCPItemText::mainFont() const
  20091. {
  20092. return mSelected ? mSelectedFont : mFont;
  20093. }
  20094. /*! \internal
  20095. Returns the color that should be used for drawing text. Returns mColor when the item is not
  20096. selected and mSelectedColor when it is.
  20097. */
  20098. QColor QCPItemText::mainColor() const
  20099. {
  20100. return mSelected ? mSelectedColor : mColor;
  20101. }
  20102. /*! \internal
  20103. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  20104. and mSelectedPen when it is.
  20105. */
  20106. QPen QCPItemText::mainPen() const
  20107. {
  20108. return mSelected ? mSelectedPen : mPen;
  20109. }
  20110. /*! \internal
  20111. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  20112. is not selected and mSelectedBrush when it is.
  20113. */
  20114. QBrush QCPItemText::mainBrush() const
  20115. {
  20116. return mSelected ? mSelectedBrush : mBrush;
  20117. }
  20118. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20119. //////////////////// QCPItemEllipse
  20120. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20121. /*! \class QCPItemEllipse
  20122. \brief An ellipse
  20123. \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs
  20124. are positions."
  20125. It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be
  20126. drawn in.
  20127. */
  20128. /*!
  20129. Creates an ellipse item and sets default values.
  20130. The constructed item can be added to the plot with QCustomPlot::addItem.
  20131. */
  20132. QCPItemEllipse::QCPItemEllipse(QCustomPlot* parentPlot)
  20133. : QCPAbstractItem(parentPlot)
  20134. , topLeft(createPosition(QLatin1String("topLeft")))
  20135. , bottomRight(createPosition(QLatin1String("bottomRight")))
  20136. , topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim))
  20137. , top(createAnchor(QLatin1String("top"), aiTop))
  20138. , topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim))
  20139. , right(createAnchor(QLatin1String("right"), aiRight))
  20140. , bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim))
  20141. , bottom(createAnchor(QLatin1String("bottom"), aiBottom))
  20142. , bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim))
  20143. , left(createAnchor(QLatin1String("left"), aiLeft))
  20144. , center(createAnchor(QLatin1String("center"), aiCenter))
  20145. {
  20146. topLeft->setCoords(0, 1);
  20147. bottomRight->setCoords(1, 0);
  20148. setPen(QPen(Qt::black));
  20149. setSelectedPen(QPen(Qt::blue, 2));
  20150. setBrush(Qt::NoBrush);
  20151. setSelectedBrush(Qt::NoBrush);
  20152. }
  20153. QCPItemEllipse::~QCPItemEllipse()
  20154. {}
  20155. /*!
  20156. Sets the pen that will be used to draw the line of the ellipse
  20157. \see setSelectedPen, setBrush
  20158. */
  20159. void QCPItemEllipse::setPen(const QPen& pen)
  20160. {
  20161. mPen = pen;
  20162. }
  20163. /*!
  20164. Sets the pen that will be used to draw the line of the ellipse when selected
  20165. \see setPen, setSelected
  20166. */
  20167. void QCPItemEllipse::setSelectedPen(const QPen& pen)
  20168. {
  20169. mSelectedPen = pen;
  20170. }
  20171. /*!
  20172. Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to
  20173. Qt::NoBrush.
  20174. \see setSelectedBrush, setPen
  20175. */
  20176. void QCPItemEllipse::setBrush(const QBrush& brush)
  20177. {
  20178. mBrush = brush;
  20179. }
  20180. /*!
  20181. Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a
  20182. brush to Qt::NoBrush.
  20183. \see setBrush
  20184. */
  20185. void QCPItemEllipse::setSelectedBrush(const QBrush& brush)
  20186. {
  20187. mSelectedBrush = brush;
  20188. }
  20189. /* inherits documentation from base class */
  20190. double QCPItemEllipse::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  20191. {
  20192. Q_UNUSED(details)
  20193. if (onlySelectable && !mSelectable)
  20194. return -1;
  20195. double result = -1;
  20196. QPointF p1 = topLeft->pixelPoint();
  20197. QPointF p2 = bottomRight->pixelPoint();
  20198. QPointF center((p1 + p2) / 2.0);
  20199. double a = qAbs(p1.x() - p2.x()) / 2.0;
  20200. double b = qAbs(p1.y() - p2.y()) / 2.0;
  20201. double x = pos.x() - center.x();
  20202. double y = pos.y() - center.y();
  20203. // distance to border:
  20204. double c = 1.0 / qSqrt(x * x / (a * a) + y * y / (b * b));
  20205. result = qAbs(c - 1) * qSqrt(x * x + y * y);
  20206. // filled ellipse, allow click inside to count as hit:
  20207. if (result > mParentPlot->selectionTolerance() * 0.99 && mBrush.style() != Qt::NoBrush
  20208. && mBrush.color().alpha() != 0) {
  20209. if (x * x / (a * a) + y * y / (b * b) <= 1)
  20210. result = mParentPlot->selectionTolerance() * 0.99;
  20211. }
  20212. return result;
  20213. }
  20214. /* inherits documentation from base class */
  20215. void QCPItemEllipse::draw(QCPPainter* painter)
  20216. {
  20217. QPointF p1 = topLeft->pixelPoint();
  20218. QPointF p2 = bottomRight->pixelPoint();
  20219. if (p1.toPoint() == p2.toPoint())
  20220. return;
  20221. QRectF ellipseRect = QRectF(p1, p2).normalized();
  20222. QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(),
  20223. mainPen().widthF());
  20224. if (ellipseRect.intersects(
  20225. clip)) // only draw if bounding rect of ellipse is visible in cliprect
  20226. {
  20227. painter->setPen(mainPen());
  20228. painter->setBrush(mainBrush());
  20229. #ifdef __EXCEPTIONS
  20230. try // drawEllipse sometimes throws exceptions if ellipse is too big
  20231. {
  20232. #endif
  20233. painter->drawEllipse(ellipseRect);
  20234. #ifdef __EXCEPTIONS
  20235. } catch (...) {
  20236. qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible";
  20237. setVisible(false);
  20238. }
  20239. #endif
  20240. }
  20241. }
  20242. /* inherits documentation from base class */
  20243. QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const
  20244. {
  20245. QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint());
  20246. switch (anchorId) {
  20247. case aiTopLeftRim:
  20248. return rect.center() + (rect.topLeft() - rect.center()) * 1 / qSqrt(2);
  20249. case aiTop:
  20250. return (rect.topLeft() + rect.topRight()) * 0.5;
  20251. case aiTopRightRim:
  20252. return rect.center() + (rect.topRight() - rect.center()) * 1 / qSqrt(2);
  20253. case aiRight:
  20254. return (rect.topRight() + rect.bottomRight()) * 0.5;
  20255. case aiBottomRightRim:
  20256. return rect.center() + (rect.bottomRight() - rect.center()) * 1 / qSqrt(2);
  20257. case aiBottom:
  20258. return (rect.bottomLeft() + rect.bottomRight()) * 0.5;
  20259. case aiBottomLeftRim:
  20260. return rect.center() + (rect.bottomLeft() - rect.center()) * 1 / qSqrt(2);
  20261. case aiLeft:
  20262. return (rect.topLeft() + rect.bottomLeft()) * 0.5;
  20263. case aiCenter:
  20264. return (rect.topLeft() + rect.bottomRight()) * 0.5;
  20265. }
  20266. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  20267. return QPointF();
  20268. }
  20269. /*! \internal
  20270. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  20271. and mSelectedPen when it is.
  20272. */
  20273. QPen QCPItemEllipse::mainPen() const
  20274. {
  20275. return mSelected ? mSelectedPen : mPen;
  20276. }
  20277. /*! \internal
  20278. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  20279. is not selected and mSelectedBrush when it is.
  20280. */
  20281. QBrush QCPItemEllipse::mainBrush() const
  20282. {
  20283. return mSelected ? mSelectedBrush : mBrush;
  20284. }
  20285. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20286. //////////////////// QCPItemPixmap
  20287. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20288. /*! \class QCPItemPixmap
  20289. \brief An arbitrary pixmap
  20290. \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs
  20291. are positions."
  20292. It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will
  20293. be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to
  20294. fit the rectangle or be drawn aligned to the topLeft position.
  20295. If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown
  20296. on the right side of the example image), the pixmap will be flipped in the respective
  20297. orientations.
  20298. */
  20299. /*!
  20300. Creates a rectangle item and sets default values.
  20301. The constructed item can be added to the plot with QCustomPlot::addItem.
  20302. */
  20303. QCPItemPixmap::QCPItemPixmap(QCustomPlot* parentPlot)
  20304. : QCPAbstractItem(parentPlot)
  20305. , topLeft(createPosition(QLatin1String("topLeft")))
  20306. , bottomRight(createPosition(QLatin1String("bottomRight")))
  20307. , top(createAnchor(QLatin1String("top"), aiTop))
  20308. , topRight(createAnchor(QLatin1String("topRight"), aiTopRight))
  20309. , right(createAnchor(QLatin1String("right"), aiRight))
  20310. , bottom(createAnchor(QLatin1String("bottom"), aiBottom))
  20311. , bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft))
  20312. , left(createAnchor(QLatin1String("left"), aiLeft))
  20313. , mScaledPixmapInvalidated(true)
  20314. {
  20315. topLeft->setCoords(0, 1);
  20316. bottomRight->setCoords(1, 0);
  20317. setPen(Qt::NoPen);
  20318. setSelectedPen(QPen(Qt::blue));
  20319. setScaled(false, Qt::KeepAspectRatio, Qt::SmoothTransformation);
  20320. }
  20321. QCPItemPixmap::~QCPItemPixmap()
  20322. {}
  20323. /*!
  20324. Sets the pixmap that will be displayed.
  20325. */
  20326. void QCPItemPixmap::setPixmap(const QPixmap& pixmap)
  20327. {
  20328. mPixmap = pixmap;
  20329. mScaledPixmapInvalidated = true;
  20330. if (mPixmap.isNull())
  20331. qDebug() << Q_FUNC_INFO << "pixmap is null";
  20332. }
  20333. /*!
  20334. Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a
  20335. bottomRight positions.
  20336. */
  20337. void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode,
  20338. Qt::TransformationMode transformationMode)
  20339. {
  20340. mScaled = scaled;
  20341. mAspectRatioMode = aspectRatioMode;
  20342. mTransformationMode = transformationMode;
  20343. mScaledPixmapInvalidated = true;
  20344. }
  20345. /*!
  20346. Sets the pen that will be used to draw a border around the pixmap.
  20347. \see setSelectedPen, setBrush
  20348. */
  20349. void QCPItemPixmap::setPen(const QPen& pen)
  20350. {
  20351. mPen = pen;
  20352. }
  20353. /*!
  20354. Sets the pen that will be used to draw a border around the pixmap when selected
  20355. \see setPen, setSelected
  20356. */
  20357. void QCPItemPixmap::setSelectedPen(const QPen& pen)
  20358. {
  20359. mSelectedPen = pen;
  20360. }
  20361. /* inherits documentation from base class */
  20362. double QCPItemPixmap::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  20363. {
  20364. Q_UNUSED(details)
  20365. if (onlySelectable && !mSelectable)
  20366. return -1;
  20367. return rectSelectTest(getFinalRect(), pos, true);
  20368. }
  20369. /* inherits documentation from base class */
  20370. void QCPItemPixmap::draw(QCPPainter* painter)
  20371. {
  20372. bool flipHorz = false;
  20373. bool flipVert = false;
  20374. QRect rect = getFinalRect(&flipHorz, &flipVert);
  20375. double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF();
  20376. QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  20377. if (boundingRect.intersects(clipRect())) {
  20378. updateScaledPixmap(rect, flipHorz, flipVert);
  20379. painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap);
  20380. QPen pen = mainPen();
  20381. if (pen.style() != Qt::NoPen) {
  20382. painter->setPen(pen);
  20383. painter->setBrush(Qt::NoBrush);
  20384. painter->drawRect(rect);
  20385. }
  20386. }
  20387. }
  20388. /* inherits documentation from base class */
  20389. QPointF QCPItemPixmap::anchorPixelPoint(int anchorId) const
  20390. {
  20391. bool flipHorz;
  20392. bool flipVert;
  20393. QRect rect = getFinalRect(&flipHorz, &flipVert);
  20394. // we actually want denormal rects (negative width/height) here, so restore
  20395. // the flipped state:
  20396. if (flipHorz)
  20397. rect.adjust(rect.width(), 0, -rect.width(), 0);
  20398. if (flipVert)
  20399. rect.adjust(0, rect.height(), 0, -rect.height());
  20400. switch (anchorId) {
  20401. case aiTop:
  20402. return (rect.topLeft() + rect.topRight()) * 0.5;
  20403. case aiTopRight:
  20404. return rect.topRight();
  20405. case aiRight:
  20406. return (rect.topRight() + rect.bottomRight()) * 0.5;
  20407. case aiBottom:
  20408. return (rect.bottomLeft() + rect.bottomRight()) * 0.5;
  20409. case aiBottomLeft:
  20410. return rect.bottomLeft();
  20411. case aiLeft:
  20412. return (rect.topLeft() + rect.bottomLeft()) * 0.5;
  20413. ;
  20414. }
  20415. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  20416. return QPointF();
  20417. }
  20418. /*! \internal
  20419. Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The
  20420. parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped
  20421. horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a
  20422. bottomRight.)
  20423. This function only creates the scaled pixmap when the buffered pixmap has a different size than
  20424. the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does
  20425. not cause expensive rescaling every time.
  20426. If scaling is disabled, sets mScaledPixmap to a null QPixmap.
  20427. */
  20428. void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert)
  20429. {
  20430. if (mPixmap.isNull())
  20431. return;
  20432. if (mScaled) {
  20433. if (finalRect.isNull())
  20434. finalRect = getFinalRect(&flipHorz, &flipVert);
  20435. if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()) {
  20436. mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, mTransformationMode);
  20437. if (flipHorz || flipVert)
  20438. mScaledPixmap =
  20439. QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert));
  20440. }
  20441. } else if (!mScaledPixmap.isNull())
  20442. mScaledPixmap = QPixmap();
  20443. mScaledPixmapInvalidated = false;
  20444. }
  20445. /*! \internal
  20446. Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions
  20447. and scaling settings.
  20448. The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn
  20449. flipped horizontally or vertically in the returned rect. (The returned rect itself is always
  20450. normalized, i.e. the top left corner of the rect is actually further to the top/left than the
  20451. bottom right corner). This is the case when the item position \a topLeft is further to the
  20452. bottom/right than \a bottomRight.
  20453. If scaling is disabled, returns a rect with size of the original pixmap and the top left corner
  20454. aligned with the item position \a topLeft. The position \a bottomRight is ignored.
  20455. */
  20456. QRect QCPItemPixmap::getFinalRect(bool* flippedHorz, bool* flippedVert) const
  20457. {
  20458. QRect result;
  20459. bool flipHorz = false;
  20460. bool flipVert = false;
  20461. QPoint p1 = topLeft->pixelPoint().toPoint();
  20462. QPoint p2 = bottomRight->pixelPoint().toPoint();
  20463. if (p1 == p2)
  20464. return QRect(p1, QSize(0, 0));
  20465. if (mScaled) {
  20466. QSize newSize = QSize(p2.x() - p1.x(), p2.y() - p1.y());
  20467. QPoint topLeft = p1;
  20468. if (newSize.width() < 0) {
  20469. flipHorz = true;
  20470. newSize.rwidth() *= -1;
  20471. topLeft.setX(p2.x());
  20472. }
  20473. if (newSize.height() < 0) {
  20474. flipVert = true;
  20475. newSize.rheight() *= -1;
  20476. topLeft.setY(p2.y());
  20477. }
  20478. QSize scaledSize = mPixmap.size();
  20479. scaledSize.scale(newSize, mAspectRatioMode);
  20480. result = QRect(topLeft, scaledSize);
  20481. } else {
  20482. result = QRect(p1, mPixmap.size());
  20483. }
  20484. if (flippedHorz)
  20485. *flippedHorz = flipHorz;
  20486. if (flippedVert)
  20487. *flippedVert = flipVert;
  20488. return result;
  20489. }
  20490. /*! \internal
  20491. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  20492. and mSelectedPen when it is.
  20493. */
  20494. QPen QCPItemPixmap::mainPen() const
  20495. {
  20496. return mSelected ? mSelectedPen : mPen;
  20497. }
  20498. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20499. //////////////////// QCPItemTracer
  20500. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20501. /*! \class QCPItemTracer
  20502. \brief Item that sticks to QCPGraph data points
  20503. \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs
  20504. are positions."
  20505. The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt
  20506. the coordinate axes of the graph and update its \a position to be on the graph's data. This means
  20507. the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a
  20508. QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a
  20509. position will have no effect because they will be overriden in the next redraw (this is when the
  20510. coordinate update happens).
  20511. If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will
  20512. stay at the corresponding end of the graph.
  20513. With \ref setInterpolating you may specify whether the tracer may only stay exactly on data
  20514. points or whether it interpolates data points linearly, if given a key that lies between two data
  20515. points of the graph.
  20516. The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer
  20517. have no own visual appearance (set the style to \ref tsNone), and just connect other item
  20518. positions to the tracer \a position (used as an anchor) via \ref
  20519. QCPItemPosition::setParentAnchor.
  20520. \note The tracer position is only automatically updated upon redraws. So when the data of the
  20521. graph changes and immediately afterwards (without a redraw) the a position coordinates of the
  20522. tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref
  20523. updatePosition must be called manually, prior to reading the tracer coordinates.
  20524. */
  20525. /*!
  20526. Creates a tracer item and sets default values.
  20527. The constructed item can be added to the plot with QCustomPlot::addItem.
  20528. */
  20529. QCPItemTracer::QCPItemTracer(QCustomPlot* parentPlot)
  20530. : QCPAbstractItem(parentPlot), position(createPosition(QLatin1String("position"))), mGraph(0)
  20531. {
  20532. position->setCoords(0, 0);
  20533. setBrush(Qt::NoBrush);
  20534. setSelectedBrush(Qt::NoBrush);
  20535. setPen(QPen(Qt::black));
  20536. setSelectedPen(QPen(Qt::blue, 2));
  20537. setStyle(tsCrosshair);
  20538. setSize(6);
  20539. setInterpolating(false);
  20540. setGraphKey(0);
  20541. }
  20542. QCPItemTracer::~QCPItemTracer()
  20543. {}
  20544. /*!
  20545. Sets the pen that will be used to draw the line of the tracer
  20546. \see setSelectedPen, setBrush
  20547. */
  20548. void QCPItemTracer::setPen(const QPen& pen)
  20549. {
  20550. mPen = pen;
  20551. }
  20552. /*!
  20553. Sets the pen that will be used to draw the line of the tracer when selected
  20554. \see setPen, setSelected
  20555. */
  20556. void QCPItemTracer::setSelectedPen(const QPen& pen)
  20557. {
  20558. mSelectedPen = pen;
  20559. }
  20560. /*!
  20561. Sets the brush that will be used to draw any fills of the tracer
  20562. \see setSelectedBrush, setPen
  20563. */
  20564. void QCPItemTracer::setBrush(const QBrush& brush)
  20565. {
  20566. mBrush = brush;
  20567. }
  20568. /*!
  20569. Sets the brush that will be used to draw any fills of the tracer, when selected.
  20570. \see setBrush, setSelected
  20571. */
  20572. void QCPItemTracer::setSelectedBrush(const QBrush& brush)
  20573. {
  20574. mSelectedBrush = brush;
  20575. }
  20576. /*!
  20577. Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare
  20578. does, \ref tsCrosshair does not).
  20579. */
  20580. void QCPItemTracer::setSize(double size)
  20581. {
  20582. mSize = size;
  20583. }
  20584. /*!
  20585. Sets the style/visual appearance of the tracer.
  20586. If you only want to use the tracer \a position as an anchor for other items, set \a style to
  20587. \ref tsNone.
  20588. */
  20589. void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style)
  20590. {
  20591. mStyle = style;
  20592. }
  20593. /*!
  20594. Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type
  20595. QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph.
  20596. To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed
  20597. freely like any other item position. This is the state the tracer will assume when its graph gets
  20598. deleted while still attached to it.
  20599. \see setGraphKey
  20600. */
  20601. void QCPItemTracer::setGraph(QCPGraph* graph)
  20602. {
  20603. if (graph) {
  20604. if (graph->parentPlot() == mParentPlot) {
  20605. position->setType(QCPItemPosition::ptPlotCoords);
  20606. position->setAxes(graph->keyAxis(), graph->valueAxis());
  20607. mGraph = graph;
  20608. updatePosition();
  20609. } else
  20610. qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item";
  20611. } else {
  20612. mGraph = 0;
  20613. }
  20614. }
  20615. /*!
  20616. Sets the key of the graph's data point the tracer will be positioned at. This is the only free
  20617. coordinate of a tracer when attached to a graph.
  20618. Depending on \ref setInterpolating, the tracer will be either positioned on the data point
  20619. closest to \a key, or will stay exactly at \a key and interpolate the value linearly.
  20620. \see setGraph, setInterpolating
  20621. */
  20622. void QCPItemTracer::setGraphKey(double key)
  20623. {
  20624. mGraphKey = key;
  20625. }
  20626. /*!
  20627. Sets whether the value of the graph's data points shall be interpolated, when positioning the
  20628. tracer.
  20629. If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on
  20630. the data point of the graph which is closest to the key, but which is not necessarily exactly
  20631. there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and
  20632. the appropriate value will be interpolated from the graph's data points linearly.
  20633. \see setGraph, setGraphKey
  20634. */
  20635. void QCPItemTracer::setInterpolating(bool enabled)
  20636. {
  20637. mInterpolating = enabled;
  20638. }
  20639. /* inherits documentation from base class */
  20640. double QCPItemTracer::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  20641. {
  20642. Q_UNUSED(details)
  20643. if (onlySelectable && !mSelectable)
  20644. return -1;
  20645. QPointF center(position->pixelPoint());
  20646. double w = mSize / 2.0;
  20647. QRect clip = clipRect();
  20648. switch (mStyle) {
  20649. case tsNone:
  20650. return -1;
  20651. case tsPlus: {
  20652. if (clipRect().intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect()))
  20653. return qSqrt(qMin(distSqrToLine(center + QPointF(-w, 0), center + QPointF(w, 0), pos),
  20654. distSqrToLine(center + QPointF(0, -w), center + QPointF(0, w), pos)));
  20655. break;
  20656. }
  20657. case tsCrosshair: {
  20658. return qSqrt(qMin(
  20659. distSqrToLine(QPointF(clip.left(), center.y()), QPointF(clip.right(), center.y()), pos),
  20660. distSqrToLine(QPointF(center.x(), clip.top()), QPointF(center.x(), clip.bottom()),
  20661. pos)));
  20662. }
  20663. case tsCircle: {
  20664. if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) {
  20665. // distance to border:
  20666. double centerDist = QVector2D(center - pos).length();
  20667. double circleLine = w;
  20668. double result = qAbs(centerDist - circleLine);
  20669. // filled ellipse, allow click inside to count as hit:
  20670. if (result > mParentPlot->selectionTolerance() * 0.99 && mBrush.style() != Qt::NoBrush
  20671. && mBrush.color().alpha() != 0) {
  20672. if (centerDist <= circleLine)
  20673. result = mParentPlot->selectionTolerance() * 0.99;
  20674. }
  20675. return result;
  20676. }
  20677. break;
  20678. }
  20679. case tsSquare: {
  20680. if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) {
  20681. QRectF rect = QRectF(center - QPointF(w, w), center + QPointF(w, w));
  20682. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  20683. return rectSelectTest(rect, pos, filledRect);
  20684. }
  20685. break;
  20686. }
  20687. }
  20688. return -1;
  20689. }
  20690. /* inherits documentation from base class */
  20691. void QCPItemTracer::draw(QCPPainter* painter)
  20692. {
  20693. updatePosition();
  20694. if (mStyle == tsNone)
  20695. return;
  20696. painter->setPen(mainPen());
  20697. painter->setBrush(mainBrush());
  20698. QPointF center(position->pixelPoint());
  20699. double w = mSize / 2.0;
  20700. QRect clip = clipRect();
  20701. switch (mStyle) {
  20702. case tsNone:
  20703. return;
  20704. case tsPlus: {
  20705. if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect())) {
  20706. painter->drawLine(QLineF(center + QPointF(-w, 0), center + QPointF(w, 0)));
  20707. painter->drawLine(QLineF(center + QPointF(0, -w), center + QPointF(0, w)));
  20708. }
  20709. break;
  20710. }
  20711. case tsCrosshair: {
  20712. if (center.y() > clip.top() && center.y() < clip.bottom())
  20713. painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y()));
  20714. if (center.x() > clip.left() && center.x() < clip.right())
  20715. painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom()));
  20716. break;
  20717. }
  20718. case tsCircle: {
  20719. if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect()))
  20720. painter->drawEllipse(center, w, w);
  20721. break;
  20722. }
  20723. case tsSquare: {
  20724. if (clip.intersects(QRectF(center - QPointF(w, w), center + QPointF(w, w)).toRect()))
  20725. painter->drawRect(QRectF(center - QPointF(w, w), center + QPointF(w, w)));
  20726. break;
  20727. }
  20728. }
  20729. }
  20730. /*!
  20731. If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a
  20732. position to reside on the graph data, depending on the configured key (\ref setGraphKey).
  20733. It is called automatically on every redraw and normally doesn't need to be called manually. One
  20734. exception is when you want to read the tracer coordinates via \a position and are not sure that
  20735. the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw.
  20736. In that situation, call this function before accessing \a position, to make sure you don't get
  20737. out-of-date coordinates.
  20738. If there is no graph set on this tracer, this function does nothing.
  20739. */
  20740. void QCPItemTracer::updatePosition()
  20741. {
  20742. if (mGraph) {
  20743. if (mParentPlot->hasPlottable(mGraph)) {
  20744. if (mGraph->data()->size() > 1) {
  20745. QCPDataMap::const_iterator first = mGraph->data()->constBegin();
  20746. QCPDataMap::const_iterator last = mGraph->data()->constEnd() - 1;
  20747. if (mGraphKey < first.key())
  20748. position->setCoords(first.key(), first.value().value);
  20749. else if (mGraphKey > last.key())
  20750. position->setCoords(last.key(), last.value().value);
  20751. else {
  20752. QCPDataMap::const_iterator it = mGraph->data()->lowerBound(mGraphKey);
  20753. if (it != first) // mGraphKey is somewhere between iterators
  20754. {
  20755. QCPDataMap::const_iterator prevIt = it - 1;
  20756. if (mInterpolating) {
  20757. // interpolate between iterators around mGraphKey:
  20758. double slope = 0;
  20759. if (!qFuzzyCompare((double)it.key(), (double)prevIt.key()))
  20760. slope = (it.value().value - prevIt.value().value)
  20761. / (it.key() - prevIt.key());
  20762. position->setCoords(mGraphKey, (mGraphKey - prevIt.key()) * slope
  20763. + prevIt.value().value);
  20764. } else {
  20765. // find iterator with key closest to mGraphKey:
  20766. if (mGraphKey < (prevIt.key() + it.key()) * 0.5)
  20767. it = prevIt;
  20768. position->setCoords(it.key(), it.value().value);
  20769. }
  20770. } else // mGraphKey is exactly on first iterator
  20771. position->setCoords(it.key(), it.value().value);
  20772. }
  20773. } else if (mGraph->data()->size() == 1) {
  20774. QCPDataMap::const_iterator it = mGraph->data()->constBegin();
  20775. position->setCoords(it.key(), it.value().value);
  20776. } else
  20777. qDebug() << Q_FUNC_INFO << "graph has no data";
  20778. } else
  20779. qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)";
  20780. }
  20781. }
  20782. /*! \internal
  20783. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  20784. and mSelectedPen when it is.
  20785. */
  20786. QPen QCPItemTracer::mainPen() const
  20787. {
  20788. return mSelected ? mSelectedPen : mPen;
  20789. }
  20790. /*! \internal
  20791. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  20792. is not selected and mSelectedBrush when it is.
  20793. */
  20794. QBrush QCPItemTracer::mainBrush() const
  20795. {
  20796. return mSelected ? mSelectedBrush : mBrush;
  20797. }
  20798. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20799. //////////////////// QCPItemBracket
  20800. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20801. /*! \class QCPItemBracket
  20802. \brief A bracket for referencing/highlighting certain parts in the plot.
  20803. \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs
  20804. are positions."
  20805. It has two positions, \a left and \a right, which define the span of the bracket. If \a left is
  20806. actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the
  20807. example image.
  20808. The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket
  20809. stretches away from the embraced span, can be controlled with \ref setLength.
  20810. \image html QCPItemBracket-length.png
  20811. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  20812. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  20813. It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine
  20814. or QCPItemCurve) or a text label (QCPItemText), to the bracket.
  20815. */
  20816. /*!
  20817. Creates a bracket item and sets default values.
  20818. The constructed item can be added to the plot with QCustomPlot::addItem.
  20819. */
  20820. QCPItemBracket::QCPItemBracket(QCustomPlot* parentPlot)
  20821. : QCPAbstractItem(parentPlot)
  20822. , left(createPosition(QLatin1String("left")))
  20823. , right(createPosition(QLatin1String("right")))
  20824. , center(createAnchor(QLatin1String("center"), aiCenter))
  20825. {
  20826. left->setCoords(0, 0);
  20827. right->setCoords(1, 1);
  20828. setPen(QPen(Qt::black));
  20829. setSelectedPen(QPen(Qt::blue, 2));
  20830. setLength(8);
  20831. setStyle(bsCalligraphic);
  20832. }
  20833. QCPItemBracket::~QCPItemBracket()
  20834. {}
  20835. /*!
  20836. Sets the pen that will be used to draw the bracket.
  20837. Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the
  20838. stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use
  20839. \ref setLength, which has a similar effect.
  20840. \see setSelectedPen
  20841. */
  20842. void QCPItemBracket::setPen(const QPen& pen)
  20843. {
  20844. mPen = pen;
  20845. }
  20846. /*!
  20847. Sets the pen that will be used to draw the bracket when selected
  20848. \see setPen, setSelected
  20849. */
  20850. void QCPItemBracket::setSelectedPen(const QPen& pen)
  20851. {
  20852. mSelectedPen = pen;
  20853. }
  20854. /*!
  20855. Sets the \a length in pixels how far the bracket extends in the direction towards the embraced
  20856. span of the bracket (i.e. perpendicular to the <i>left</i>-<i>right</i>-direction)
  20857. \image html QCPItemBracket-length.png
  20858. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  20859. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  20860. */
  20861. void QCPItemBracket::setLength(double length)
  20862. {
  20863. mLength = length;
  20864. }
  20865. /*!
  20866. Sets the style of the bracket, i.e. the shape/visual appearance.
  20867. \see setPen
  20868. */
  20869. void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style)
  20870. {
  20871. mStyle = style;
  20872. }
  20873. /* inherits documentation from base class */
  20874. double QCPItemBracket::selectTest(const QPointF& pos, bool onlySelectable, QVariant* details) const
  20875. {
  20876. Q_UNUSED(details)
  20877. if (onlySelectable && !mSelectable)
  20878. return -1;
  20879. QVector2D leftVec(left->pixelPoint());
  20880. QVector2D rightVec(right->pixelPoint());
  20881. if (leftVec.toPoint() == rightVec.toPoint())
  20882. return -1;
  20883. QVector2D widthVec = (rightVec - leftVec) * 0.5f;
  20884. QVector2D lengthVec(-widthVec.y(), widthVec.x());
  20885. lengthVec = lengthVec.normalized() * mLength;
  20886. QVector2D centerVec = (rightVec + leftVec) * 0.5f - lengthVec;
  20887. switch (mStyle) {
  20888. case QCPItemBracket::bsSquare:
  20889. case QCPItemBracket::bsRound: {
  20890. double a = distSqrToLine((centerVec - widthVec).toPointF(),
  20891. (centerVec + widthVec).toPointF(), pos);
  20892. double b = distSqrToLine((centerVec - widthVec + lengthVec).toPointF(),
  20893. (centerVec - widthVec).toPointF(), pos);
  20894. double c = distSqrToLine((centerVec + widthVec + lengthVec).toPointF(),
  20895. (centerVec + widthVec).toPointF(), pos);
  20896. return qSqrt(qMin(qMin(a, b), c));
  20897. }
  20898. case QCPItemBracket::bsCurly:
  20899. case QCPItemBracket::bsCalligraphic: {
  20900. double a = distSqrToLine((centerVec - widthVec * 0.75f + lengthVec * 0.15f).toPointF(),
  20901. (centerVec + lengthVec * 0.3f).toPointF(), pos);
  20902. double b =
  20903. distSqrToLine((centerVec - widthVec + lengthVec * 0.7f).toPointF(),
  20904. (centerVec - widthVec * 0.75f + lengthVec * 0.15f).toPointF(), pos);
  20905. double c = distSqrToLine((centerVec + widthVec * 0.75f + lengthVec * 0.15f).toPointF(),
  20906. (centerVec + lengthVec * 0.3f).toPointF(), pos);
  20907. double d =
  20908. distSqrToLine((centerVec + widthVec + lengthVec * 0.7f).toPointF(),
  20909. (centerVec + widthVec * 0.75f + lengthVec * 0.15f).toPointF(), pos);
  20910. return qSqrt(qMin(qMin(a, b), qMin(c, d)));
  20911. }
  20912. }
  20913. return -1;
  20914. }
  20915. /* inherits documentation from base class */
  20916. void QCPItemBracket::draw(QCPPainter* painter)
  20917. {
  20918. QVector2D leftVec(left->pixelPoint());
  20919. QVector2D rightVec(right->pixelPoint());
  20920. if (leftVec.toPoint() == rightVec.toPoint())
  20921. return;
  20922. QVector2D widthVec = (rightVec - leftVec) * 0.5f;
  20923. QVector2D lengthVec(-widthVec.y(), widthVec.x());
  20924. lengthVec = lengthVec.normalized() * mLength;
  20925. QVector2D centerVec = (rightVec + leftVec) * 0.5f - lengthVec;
  20926. QPolygon boundingPoly;
  20927. boundingPoly << leftVec.toPoint() << rightVec.toPoint() << (rightVec - lengthVec).toPoint()
  20928. << (leftVec - lengthVec).toPoint();
  20929. QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(),
  20930. mainPen().widthF());
  20931. if (clip.intersects(boundingPoly.boundingRect())) {
  20932. painter->setPen(mainPen());
  20933. switch (mStyle) {
  20934. case bsSquare: {
  20935. painter->drawLine((centerVec + widthVec).toPointF(), (centerVec - widthVec).toPointF());
  20936. painter->drawLine((centerVec + widthVec).toPointF(),
  20937. (centerVec + widthVec + lengthVec).toPointF());
  20938. painter->drawLine((centerVec - widthVec).toPointF(),
  20939. (centerVec - widthVec + lengthVec).toPointF());
  20940. break;
  20941. }
  20942. case bsRound: {
  20943. painter->setBrush(Qt::NoBrush);
  20944. QPainterPath path;
  20945. path.moveTo((centerVec + widthVec + lengthVec).toPointF());
  20946. path.cubicTo((centerVec + widthVec).toPointF(), (centerVec + widthVec).toPointF(),
  20947. centerVec.toPointF());
  20948. path.cubicTo((centerVec - widthVec).toPointF(), (centerVec - widthVec).toPointF(),
  20949. (centerVec - widthVec + lengthVec).toPointF());
  20950. painter->drawPath(path);
  20951. break;
  20952. }
  20953. case bsCurly: {
  20954. painter->setBrush(Qt::NoBrush);
  20955. QPainterPath path;
  20956. path.moveTo((centerVec + widthVec + lengthVec).toPointF());
  20957. path.cubicTo((centerVec + widthVec - lengthVec * 0.8f).toPointF(),
  20958. (centerVec + 0.4f * widthVec + lengthVec).toPointF(),
  20959. centerVec.toPointF());
  20960. path.cubicTo((centerVec - 0.4f * widthVec + lengthVec).toPointF(),
  20961. (centerVec - widthVec - lengthVec * 0.8f).toPointF(),
  20962. (centerVec - widthVec + lengthVec).toPointF());
  20963. painter->drawPath(path);
  20964. break;
  20965. }
  20966. case bsCalligraphic: {
  20967. painter->setPen(Qt::NoPen);
  20968. painter->setBrush(QBrush(mainPen().color()));
  20969. QPainterPath path;
  20970. path.moveTo((centerVec + widthVec + lengthVec).toPointF());
  20971. path.cubicTo((centerVec + widthVec - lengthVec * 0.8f).toPointF(),
  20972. (centerVec + 0.4f * widthVec + 0.8f * lengthVec).toPointF(),
  20973. centerVec.toPointF());
  20974. path.cubicTo((centerVec - 0.4f * widthVec + 0.8f * lengthVec).toPointF(),
  20975. (centerVec - widthVec - lengthVec * 0.8f).toPointF(),
  20976. (centerVec - widthVec + lengthVec).toPointF());
  20977. path.cubicTo((centerVec - widthVec - lengthVec * 0.5f).toPointF(),
  20978. (centerVec - 0.2f * widthVec + 1.2f * lengthVec).toPointF(),
  20979. (centerVec + lengthVec * 0.2f).toPointF());
  20980. path.cubicTo((centerVec + 0.2f * widthVec + 1.2f * lengthVec).toPointF(),
  20981. (centerVec + widthVec - lengthVec * 0.5f).toPointF(),
  20982. (centerVec + widthVec + lengthVec).toPointF());
  20983. painter->drawPath(path);
  20984. break;
  20985. }
  20986. }
  20987. }
  20988. }
  20989. /* inherits documentation from base class */
  20990. QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const
  20991. {
  20992. QVector2D leftVec(left->pixelPoint());
  20993. QVector2D rightVec(right->pixelPoint());
  20994. if (leftVec.toPoint() == rightVec.toPoint())
  20995. return leftVec.toPointF();
  20996. QVector2D widthVec = (rightVec - leftVec) * 0.5f;
  20997. QVector2D lengthVec(-widthVec.y(), widthVec.x());
  20998. lengthVec = lengthVec.normalized() * mLength;
  20999. QVector2D centerVec = (rightVec + leftVec) * 0.5f - lengthVec;
  21000. switch (anchorId) {
  21001. case aiCenter:
  21002. return centerVec.toPointF();
  21003. }
  21004. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  21005. return QPointF();
  21006. }
  21007. /*! \internal
  21008. Returns the pen that should be used for drawing lines. Returns mPen when the
  21009. item is not selected and mSelectedPen when it is.
  21010. */
  21011. QPen QCPItemBracket::mainPen() const
  21012. {
  21013. return mSelected ? mSelectedPen : mPen;
  21014. }