qcustomplot.cpp 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496
  1. /***************************************************************************
  2. ** **
  3. ** QCustomPlot, an easy to use, modern plotting widget for Qt **
  4. ** Copyright (C) 2011-2021 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: 29.03.21 **
  23. ** Version: 2.1.0 **
  24. ****************************************************************************/
  25. #include "qcustomplot.h"
  26. /* including file 'src/vector2d.cpp' */
  27. /* modified 2021-03-29T02:30:44, size 7973 */
  28. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29. //////////////////// QCPVector2D
  30. ////////////////////////////////////////////////////////////////////////////////////////////////////
  31. /*! \class QCPVector2D
  32. \brief Represents two doubles as a mathematical 2D vector
  33. This class acts as a replacement for QVector2D with the advantage of double precision instead of
  34. single, and some convenience methods tailored for the QCustomPlot library.
  35. */
  36. /* start documentation of inline functions */
  37. /*! \fn void QCPVector2D::setX(double x)
  38. Sets the x coordinate of this vector to \a x.
  39. \see setY
  40. */
  41. /*! \fn void QCPVector2D::setY(double y)
  42. Sets the y coordinate of this vector to \a y.
  43. \see setX
  44. */
  45. /*! \fn double QCPVector2D::length() const
  46. Returns the length of this vector.
  47. \see lengthSquared
  48. */
  49. /*! \fn double QCPVector2D::lengthSquared() const
  50. Returns the squared length of this vector. In some situations, e.g. when just trying to find the
  51. shortest vector of a group, this is faster than calculating \ref length, because it avoids
  52. calculation of a square root.
  53. \see length
  54. */
  55. /*! \fn double QCPVector2D::angle() const
  56. Returns the angle of the vector in radians. The angle is measured between the positive x line and
  57. the vector, counter-clockwise in a mathematical coordinate system (y axis upwards positive). In
  58. screen/widget coordinates where the y axis is inverted, the angle appears clockwise.
  59. */
  60. /*! \fn QPoint QCPVector2D::toPoint() const
  61. Returns a QPoint which has the x and y coordinates of this vector, truncating any floating point
  62. information.
  63. \see toPointF
  64. */
  65. /*! \fn QPointF QCPVector2D::toPointF() const
  66. Returns a QPointF which has the x and y coordinates of this vector.
  67. \see toPoint
  68. */
  69. /*! \fn bool QCPVector2D::isNull() const
  70. Returns whether this vector is null. A vector is null if \c qIsNull returns true for both x and y
  71. coordinates, i.e. if both are binary equal to 0.
  72. */
  73. /*! \fn QCPVector2D QCPVector2D::perpendicular() const
  74. Returns a vector perpendicular to this vector, with the same length.
  75. */
  76. /*! \fn double QCPVector2D::dot() const
  77. Returns the dot/scalar product of this vector with the specified vector \a vec.
  78. */
  79. /* end documentation of inline functions */
  80. /*!
  81. Creates a QCPVector2D object and initializes the x and y coordinates to 0.
  82. */
  83. QCPVector2D::QCPVector2D() :
  84. mX(0),
  85. mY(0)
  86. {
  87. }
  88. /*!
  89. Creates a QCPVector2D object and initializes the \a x and \a y coordinates with the specified
  90. values.
  91. */
  92. QCPVector2D::QCPVector2D(double x, double y) :
  93. mX(x),
  94. mY(y)
  95. {
  96. }
  97. /*!
  98. Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of
  99. the specified \a point.
  100. */
  101. QCPVector2D::QCPVector2D(const QPoint &point) :
  102. mX(point.x()),
  103. mY(point.y())
  104. {
  105. }
  106. /*!
  107. Creates a QCPVector2D object and initializes the x and y coordinates respective coordinates of
  108. the specified \a point.
  109. */
  110. QCPVector2D::QCPVector2D(const QPointF &point) :
  111. mX(point.x()),
  112. mY(point.y())
  113. {
  114. }
  115. /*!
  116. Normalizes this vector. After this operation, the length of the vector is equal to 1.
  117. If the vector has both entries set to zero, this method does nothing.
  118. \see normalized, length, lengthSquared
  119. */
  120. void QCPVector2D::normalize()
  121. {
  122. if (mX == 0.0 && mY == 0.0) return;
  123. const double lenInv = 1.0/length();
  124. mX *= lenInv;
  125. mY *= lenInv;
  126. }
  127. /*!
  128. Returns a normalized version of this vector. The length of the returned vector is equal to 1.
  129. If the vector has both entries set to zero, this method returns the vector unmodified.
  130. \see normalize, length, lengthSquared
  131. */
  132. QCPVector2D QCPVector2D::normalized() const
  133. {
  134. if (mX == 0.0 && mY == 0.0) return *this;
  135. const double lenInv = 1.0/length();
  136. return QCPVector2D(mX*lenInv, mY*lenInv);
  137. }
  138. /*! \overload
  139. Returns the squared shortest distance of this vector (interpreted as a point) to the finite line
  140. segment given by \a start and \a end.
  141. \see distanceToStraightLine
  142. */
  143. double QCPVector2D::distanceSquaredToLine(const QCPVector2D &start, const QCPVector2D &end) const
  144. {
  145. const QCPVector2D v(end-start);
  146. const double vLengthSqr = v.lengthSquared();
  147. if (!qFuzzyIsNull(vLengthSqr))
  148. {
  149. const double mu = v.dot(*this-start)/vLengthSqr;
  150. if (mu < 0)
  151. return (*this-start).lengthSquared();
  152. else if (mu > 1)
  153. return (*this-end).lengthSquared();
  154. else
  155. return ((start + mu*v)-*this).lengthSquared();
  156. } else
  157. return (*this-start).lengthSquared();
  158. }
  159. /*! \overload
  160. Returns the squared shortest distance of this vector (interpreted as a point) to the finite line
  161. segment given by \a line.
  162. \see distanceToStraightLine
  163. */
  164. double QCPVector2D::distanceSquaredToLine(const QLineF &line) const
  165. {
  166. return distanceSquaredToLine(QCPVector2D(line.p1()), QCPVector2D(line.p2()));
  167. }
  168. /*!
  169. Returns the shortest distance of this vector (interpreted as a point) to the infinite straight
  170. line given by a \a base point and a \a direction vector.
  171. \see distanceSquaredToLine
  172. */
  173. double QCPVector2D::distanceToStraightLine(const QCPVector2D &base, const QCPVector2D &direction) const
  174. {
  175. return qAbs((*this-base).dot(direction.perpendicular()))/direction.length();
  176. }
  177. /*!
  178. Scales this vector by the given \a factor, i.e. the x and y components are multiplied by \a
  179. factor.
  180. */
  181. QCPVector2D &QCPVector2D::operator*=(double factor)
  182. {
  183. mX *= factor;
  184. mY *= factor;
  185. return *this;
  186. }
  187. /*!
  188. Scales this vector by the given \a divisor, i.e. the x and y components are divided by \a
  189. divisor.
  190. */
  191. QCPVector2D &QCPVector2D::operator/=(double divisor)
  192. {
  193. mX /= divisor;
  194. mY /= divisor;
  195. return *this;
  196. }
  197. /*!
  198. Adds the given \a vector to this vector component-wise.
  199. */
  200. QCPVector2D &QCPVector2D::operator+=(const QCPVector2D &vector)
  201. {
  202. mX += vector.mX;
  203. mY += vector.mY;
  204. return *this;
  205. }
  206. /*!
  207. subtracts the given \a vector from this vector component-wise.
  208. */
  209. QCPVector2D &QCPVector2D::operator-=(const QCPVector2D &vector)
  210. {
  211. mX -= vector.mX;
  212. mY -= vector.mY;
  213. return *this;
  214. }
  215. /* end of 'src/vector2d.cpp' */
  216. /* including file 'src/painter.cpp' */
  217. /* modified 2021-03-29T02:30:44, size 8656 */
  218. ////////////////////////////////////////////////////////////////////////////////////////////////////
  219. //////////////////// QCPPainter
  220. ////////////////////////////////////////////////////////////////////////////////////////////////////
  221. /*! \class QCPPainter
  222. \brief QPainter subclass used internally
  223. This QPainter subclass is used to provide some extended functionality e.g. for tweaking position
  224. consistency between antialiased and non-antialiased painting. Further it provides workarounds
  225. for QPainter quirks.
  226. \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and
  227. restore. So while it is possible to pass a QCPPainter instance to a function that expects a
  228. QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because
  229. it will call the base class implementations of the functions actually hidden by QCPPainter).
  230. */
  231. /*!
  232. Creates a new QCPPainter instance and sets default values
  233. */
  234. QCPPainter::QCPPainter() :
  235. mModes(pmDefault),
  236. mIsAntialiasing(false)
  237. {
  238. // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and
  239. // a call to begin() will follow
  240. }
  241. /*!
  242. Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just
  243. like the analogous QPainter constructor, begins painting on \a device immediately.
  244. Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5.
  245. */
  246. QCPPainter::QCPPainter(QPaintDevice *device) :
  247. QPainter(device),
  248. mModes(pmDefault),
  249. mIsAntialiasing(false)
  250. {
  251. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions.
  252. if (isActive())
  253. setRenderHint(QPainter::NonCosmeticDefaultPen);
  254. #endif
  255. }
  256. /*!
  257. Sets the pen of the painter and applies certain fixes to it, depending on the mode of this
  258. QCPPainter.
  259. \note this function hides the non-virtual base class implementation.
  260. */
  261. void QCPPainter::setPen(const QPen &pen)
  262. {
  263. QPainter::setPen(pen);
  264. if (mModes.testFlag(pmNonCosmetic))
  265. makeNonCosmetic();
  266. }
  267. /*! \overload
  268. Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of
  269. this QCPPainter.
  270. \note this function hides the non-virtual base class implementation.
  271. */
  272. void QCPPainter::setPen(const QColor &color)
  273. {
  274. QPainter::setPen(color);
  275. if (mModes.testFlag(pmNonCosmetic))
  276. makeNonCosmetic();
  277. }
  278. /*! \overload
  279. Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of
  280. this QCPPainter.
  281. \note this function hides the non-virtual base class implementation.
  282. */
  283. void QCPPainter::setPen(Qt::PenStyle penStyle)
  284. {
  285. QPainter::setPen(penStyle);
  286. if (mModes.testFlag(pmNonCosmetic))
  287. makeNonCosmetic();
  288. }
  289. /*! \overload
  290. Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when
  291. antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to
  292. integer coordinates and then passes it to the original drawLine.
  293. \note this function hides the non-virtual base class implementation.
  294. */
  295. void QCPPainter::drawLine(const QLineF &line)
  296. {
  297. if (mIsAntialiasing || mModes.testFlag(pmVectorized))
  298. QPainter::drawLine(line);
  299. else
  300. QPainter::drawLine(line.toLine());
  301. }
  302. /*!
  303. Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint
  304. with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between
  305. antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for
  306. AA/Non-AA painting).
  307. */
  308. void QCPPainter::setAntialiasing(bool enabled)
  309. {
  310. setRenderHint(QPainter::Antialiasing, enabled);
  311. if (mIsAntialiasing != enabled)
  312. {
  313. mIsAntialiasing = enabled;
  314. if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs
  315. {
  316. if (mIsAntialiasing)
  317. translate(0.5, 0.5);
  318. else
  319. translate(-0.5, -0.5);
  320. }
  321. }
  322. }
  323. /*!
  324. Sets the mode of the painter. This controls whether the painter shall adjust its
  325. fixes/workarounds optimized for certain output devices.
  326. */
  327. void QCPPainter::setModes(QCPPainter::PainterModes modes)
  328. {
  329. mModes = modes;
  330. }
  331. /*!
  332. Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a
  333. device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5,
  334. all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that
  335. behaviour.
  336. The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets
  337. the render hint as appropriate.
  338. \note this function hides the non-virtual base class implementation.
  339. */
  340. bool QCPPainter::begin(QPaintDevice *device)
  341. {
  342. bool result = QPainter::begin(device);
  343. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions.
  344. if (result)
  345. setRenderHint(QPainter::NonCosmeticDefaultPen);
  346. #endif
  347. return result;
  348. }
  349. /*! \overload
  350. Sets the mode of the painter. This controls whether the painter shall adjust its
  351. fixes/workarounds optimized for certain output devices.
  352. */
  353. void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled)
  354. {
  355. if (!enabled && mModes.testFlag(mode))
  356. mModes &= ~mode;
  357. else if (enabled && !mModes.testFlag(mode))
  358. mModes |= mode;
  359. }
  360. /*!
  361. Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to
  362. QPainter, the save/restore functions are reimplemented to also save/restore those members.
  363. \note this function hides the non-virtual base class implementation.
  364. \see restore
  365. */
  366. void QCPPainter::save()
  367. {
  368. mAntialiasingStack.push(mIsAntialiasing);
  369. QPainter::save();
  370. }
  371. /*!
  372. Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to
  373. QPainter, the save/restore functions are reimplemented to also save/restore those members.
  374. \note this function hides the non-virtual base class implementation.
  375. \see save
  376. */
  377. void QCPPainter::restore()
  378. {
  379. if (!mAntialiasingStack.isEmpty())
  380. mIsAntialiasing = mAntialiasingStack.pop();
  381. else
  382. qDebug() << Q_FUNC_INFO << "Unbalanced save/restore";
  383. QPainter::restore();
  384. }
  385. /*!
  386. Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen
  387. overrides when the \ref pmNonCosmetic mode is set.
  388. */
  389. void QCPPainter::makeNonCosmetic()
  390. {
  391. if (qFuzzyIsNull(pen().widthF()))
  392. {
  393. QPen p = pen();
  394. p.setWidth(1);
  395. QPainter::setPen(p);
  396. }
  397. }
  398. /* end of 'src/painter.cpp' */
  399. /* including file 'src/paintbuffer.cpp' */
  400. /* modified 2021-03-29T02:30:44, size 18915 */
  401. ////////////////////////////////////////////////////////////////////////////////////////////////////
  402. //////////////////// QCPAbstractPaintBuffer
  403. ////////////////////////////////////////////////////////////////////////////////////////////////////
  404. /*! \class QCPAbstractPaintBuffer
  405. \brief The abstract base class for paint buffers, which define the rendering backend
  406. This abstract base class defines the basic interface that a paint buffer needs to provide in
  407. order to be usable by QCustomPlot.
  408. A paint buffer manages both a surface to draw onto, and the matching paint device. The size of
  409. the surface can be changed via \ref setSize. External classes (\ref QCustomPlot and \ref
  410. QCPLayer) request a painter via \ref startPainting and then perform the draw calls. Once the
  411. painting is complete, \ref donePainting is called, so the paint buffer implementation can do
  412. clean up if necessary. Before rendering a frame, each paint buffer is usually filled with a color
  413. using \ref clear (usually the color is \c Qt::transparent), to remove the contents of the
  414. previous frame.
  415. The simplest paint buffer implementation is \ref QCPPaintBufferPixmap which allows regular
  416. software rendering via the raster engine. Hardware accelerated rendering via pixel buffers and
  417. frame buffer objects is provided by \ref QCPPaintBufferGlPbuffer and \ref QCPPaintBufferGlFbo.
  418. They are used automatically if \ref QCustomPlot::setOpenGl is enabled.
  419. */
  420. /* start documentation of pure virtual functions */
  421. /*! \fn virtual QCPPainter *QCPAbstractPaintBuffer::startPainting() = 0
  422. Returns a \ref QCPPainter which is ready to draw to this buffer. The ownership and thus the
  423. responsibility to delete the painter after the painting operations are complete is given to the
  424. caller of this method.
  425. Once you are done using the painter, delete the painter and call \ref donePainting.
  426. While a painter generated with this method is active, you must not call \ref setSize, \ref
  427. setDevicePixelRatio or \ref clear.
  428. This method may return 0, if a painter couldn't be activated on the buffer. This usually
  429. indicates a problem with the respective painting backend.
  430. */
  431. /*! \fn virtual void QCPAbstractPaintBuffer::draw(QCPPainter *painter) const = 0
  432. Draws the contents of this buffer with the provided \a painter. This is the method that is used
  433. to finally join all paint buffers and draw them onto the screen.
  434. */
  435. /*! \fn virtual void QCPAbstractPaintBuffer::clear(const QColor &color) = 0
  436. Fills the entire buffer with the provided \a color. To have an empty transparent buffer, use the
  437. named color \c Qt::transparent.
  438. This method must not be called if there is currently a painter (acquired with \ref startPainting)
  439. active.
  440. */
  441. /*! \fn virtual void QCPAbstractPaintBuffer::reallocateBuffer() = 0
  442. Reallocates the internal buffer with the currently configured size (\ref setSize) and device
  443. pixel ratio, if applicable (\ref setDevicePixelRatio). It is called as soon as any of those
  444. properties are changed on this paint buffer.
  445. \note Subclasses of \ref QCPAbstractPaintBuffer must call their reimplementation of this method
  446. in their constructor, to perform the first allocation (this can not be done by the base class
  447. because calling pure virtual methods in base class constructors is not possible).
  448. */
  449. /* end documentation of pure virtual functions */
  450. /* start documentation of inline functions */
  451. /*! \fn virtual void QCPAbstractPaintBuffer::donePainting()
  452. If you have acquired a \ref QCPPainter to paint onto this paint buffer via \ref startPainting,
  453. call this method as soon as you are done with the painting operations and have deleted the
  454. painter.
  455. paint buffer subclasses may use this method to perform any type of cleanup that is necessary. The
  456. default implementation does nothing.
  457. */
  458. /* end documentation of inline functions */
  459. /*!
  460. Creates a paint buffer and initializes it with the provided \a size and \a devicePixelRatio.
  461. Subclasses must call their \ref reallocateBuffer implementation in their respective constructors.
  462. */
  463. QCPAbstractPaintBuffer::QCPAbstractPaintBuffer(const QSize &size, double devicePixelRatio) :
  464. mSize(size),
  465. mDevicePixelRatio(devicePixelRatio),
  466. mInvalidated(true)
  467. {
  468. }
  469. QCPAbstractPaintBuffer::~QCPAbstractPaintBuffer()
  470. {
  471. }
  472. /*!
  473. Sets the paint buffer size.
  474. The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained
  475. by \ref startPainting are invalidated and must not be used after calling this method.
  476. If \a size is already the current buffer size, this method does nothing.
  477. */
  478. void QCPAbstractPaintBuffer::setSize(const QSize &size)
  479. {
  480. if (mSize != size)
  481. {
  482. mSize = size;
  483. reallocateBuffer();
  484. }
  485. }
  486. /*!
  487. Sets the invalidated flag to \a invalidated.
  488. This mechanism is used internally in conjunction with isolated replotting of \ref QCPLayer
  489. instances (in \ref QCPLayer::lmBuffered mode). If \ref QCPLayer::replot is called on a buffered
  490. layer, i.e. an isolated repaint of only that layer (and its dedicated paint buffer) is requested,
  491. QCustomPlot will decide depending on the invalidated flags of other paint buffers whether it also
  492. replots them, instead of only the layer on which the replot was called.
  493. The invalidated flag is set to true when \ref QCPLayer association has changed, i.e. if layers
  494. were added or removed from this buffer, or if they were reordered. It is set to false as soon as
  495. all associated \ref QCPLayer instances are drawn onto the buffer.
  496. Under normal circumstances, it is not necessary to manually call this method.
  497. */
  498. void QCPAbstractPaintBuffer::setInvalidated(bool invalidated)
  499. {
  500. mInvalidated = invalidated;
  501. }
  502. /*!
  503. Sets the device pixel ratio to \a ratio. This is useful to render on high-DPI output devices.
  504. The ratio is automatically set to the device pixel ratio used by the parent QCustomPlot instance.
  505. The buffer is reallocated (by calling \ref reallocateBuffer), so any painters that were obtained
  506. by \ref startPainting are invalidated and must not be used after calling this method.
  507. \note This method is only available for Qt versions 5.4 and higher.
  508. */
  509. void QCPAbstractPaintBuffer::setDevicePixelRatio(double ratio)
  510. {
  511. if (!qFuzzyCompare(ratio, mDevicePixelRatio))
  512. {
  513. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  514. mDevicePixelRatio = ratio;
  515. reallocateBuffer();
  516. #else
  517. qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
  518. mDevicePixelRatio = 1.0;
  519. #endif
  520. }
  521. }
  522. ////////////////////////////////////////////////////////////////////////////////////////////////////
  523. //////////////////// QCPPaintBufferPixmap
  524. ////////////////////////////////////////////////////////////////////////////////////////////////////
  525. /*! \class QCPPaintBufferPixmap
  526. \brief A paint buffer based on QPixmap, using software raster rendering
  527. This paint buffer is the default and fall-back paint buffer which uses software rendering and
  528. QPixmap as internal buffer. It is used if \ref QCustomPlot::setOpenGl is false.
  529. */
  530. /*!
  531. Creates a pixmap paint buffer instancen with the specified \a size and \a devicePixelRatio, if
  532. applicable.
  533. */
  534. QCPPaintBufferPixmap::QCPPaintBufferPixmap(const QSize &size, double devicePixelRatio) :
  535. QCPAbstractPaintBuffer(size, devicePixelRatio)
  536. {
  537. QCPPaintBufferPixmap::reallocateBuffer();
  538. }
  539. QCPPaintBufferPixmap::~QCPPaintBufferPixmap()
  540. {
  541. }
  542. /* inherits documentation from base class */
  543. QCPPainter *QCPPaintBufferPixmap::startPainting()
  544. {
  545. QCPPainter *result = new QCPPainter(&mBuffer);
  546. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  547. result->setRenderHint(QPainter::HighQualityAntialiasing);
  548. #endif
  549. return result;
  550. }
  551. /* inherits documentation from base class */
  552. void QCPPaintBufferPixmap::draw(QCPPainter *painter) const
  553. {
  554. if (painter && painter->isActive())
  555. painter->drawPixmap(0, 0, mBuffer);
  556. else
  557. qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
  558. }
  559. /* inherits documentation from base class */
  560. void QCPPaintBufferPixmap::clear(const QColor &color)
  561. {
  562. mBuffer.fill(color);
  563. }
  564. /* inherits documentation from base class */
  565. void QCPPaintBufferPixmap::reallocateBuffer()
  566. {
  567. setInvalidated();
  568. if (!qFuzzyCompare(1.0, mDevicePixelRatio))
  569. {
  570. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  571. mBuffer = QPixmap(mSize*mDevicePixelRatio);
  572. mBuffer.setDevicePixelRatio(mDevicePixelRatio);
  573. #else
  574. qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
  575. mDevicePixelRatio = 1.0;
  576. mBuffer = QPixmap(mSize);
  577. #endif
  578. } else
  579. {
  580. mBuffer = QPixmap(mSize);
  581. }
  582. }
  583. #ifdef QCP_OPENGL_PBUFFER
  584. ////////////////////////////////////////////////////////////////////////////////////////////////////
  585. //////////////////// QCPPaintBufferGlPbuffer
  586. ////////////////////////////////////////////////////////////////////////////////////////////////////
  587. /*! \class QCPPaintBufferGlPbuffer
  588. \brief A paint buffer based on OpenGL pixel buffers, using hardware accelerated rendering
  589. This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot
  590. rendering. It is based on OpenGL pixel buffers (pbuffer) and is used in Qt versions before 5.0.
  591. (See \ref QCPPaintBufferGlFbo used in newer Qt versions.)
  592. The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are
  593. supported by the system.
  594. */
  595. /*!
  596. Creates a \ref QCPPaintBufferGlPbuffer instance with the specified \a size and \a
  597. devicePixelRatio, if applicable.
  598. The parameter \a multisamples defines how many samples are used per pixel. Higher values thus
  599. result in higher quality antialiasing. If the specified \a multisamples value exceeds the
  600. capability of the graphics hardware, the highest supported multisampling is used.
  601. */
  602. QCPPaintBufferGlPbuffer::QCPPaintBufferGlPbuffer(const QSize &size, double devicePixelRatio, int multisamples) :
  603. QCPAbstractPaintBuffer(size, devicePixelRatio),
  604. mGlPBuffer(0),
  605. mMultisamples(qMax(0, multisamples))
  606. {
  607. QCPPaintBufferGlPbuffer::reallocateBuffer();
  608. }
  609. QCPPaintBufferGlPbuffer::~QCPPaintBufferGlPbuffer()
  610. {
  611. if (mGlPBuffer)
  612. delete mGlPBuffer;
  613. }
  614. /* inherits documentation from base class */
  615. QCPPainter *QCPPaintBufferGlPbuffer::startPainting()
  616. {
  617. if (!mGlPBuffer->isValid())
  618. {
  619. qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
  620. return 0;
  621. }
  622. QCPPainter *result = new QCPPainter(mGlPBuffer);
  623. result->setRenderHint(QPainter::HighQualityAntialiasing);
  624. return result;
  625. }
  626. /* inherits documentation from base class */
  627. void QCPPaintBufferGlPbuffer::draw(QCPPainter *painter) const
  628. {
  629. if (!painter || !painter->isActive())
  630. {
  631. qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
  632. return;
  633. }
  634. if (!mGlPBuffer->isValid())
  635. {
  636. qDebug() << Q_FUNC_INFO << "OpenGL pbuffer isn't valid, reallocateBuffer was not called?";
  637. return;
  638. }
  639. painter->drawImage(0, 0, mGlPBuffer->toImage());
  640. }
  641. /* inherits documentation from base class */
  642. void QCPPaintBufferGlPbuffer::clear(const QColor &color)
  643. {
  644. if (mGlPBuffer->isValid())
  645. {
  646. mGlPBuffer->makeCurrent();
  647. glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
  648. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  649. mGlPBuffer->doneCurrent();
  650. } else
  651. qDebug() << Q_FUNC_INFO << "OpenGL pbuffer invalid or context not current";
  652. }
  653. /* inherits documentation from base class */
  654. void QCPPaintBufferGlPbuffer::reallocateBuffer()
  655. {
  656. if (mGlPBuffer)
  657. delete mGlPBuffer;
  658. QGLFormat format;
  659. format.setAlpha(true);
  660. format.setSamples(mMultisamples);
  661. mGlPBuffer = new QGLPixelBuffer(mSize, format);
  662. }
  663. #endif // QCP_OPENGL_PBUFFER
  664. #ifdef QCP_OPENGL_FBO
  665. ////////////////////////////////////////////////////////////////////////////////////////////////////
  666. //////////////////// QCPPaintBufferGlFbo
  667. ////////////////////////////////////////////////////////////////////////////////////////////////////
  668. /*! \class QCPPaintBufferGlFbo
  669. \brief A paint buffer based on OpenGL frame buffers objects, using hardware accelerated rendering
  670. This paint buffer is one of the OpenGL paint buffers which facilitate hardware accelerated plot
  671. rendering. It is based on OpenGL frame buffer objects (fbo) and is used in Qt versions 5.0 and
  672. higher. (See \ref QCPPaintBufferGlPbuffer used in older Qt versions.)
  673. The OpenGL paint buffers are used if \ref QCustomPlot::setOpenGl is set to true, and if they are
  674. supported by the system.
  675. */
  676. /*!
  677. Creates a \ref QCPPaintBufferGlFbo instance with the specified \a size and \a devicePixelRatio,
  678. if applicable.
  679. All frame buffer objects shall share one OpenGL context and paint device, which need to be set up
  680. externally and passed via \a glContext and \a glPaintDevice. The set-up is done in \ref
  681. QCustomPlot::setupOpenGl and the context and paint device are managed by the parent QCustomPlot
  682. instance.
  683. */
  684. QCPPaintBufferGlFbo::QCPPaintBufferGlFbo(const QSize &size, double devicePixelRatio, QWeakPointer<QOpenGLContext> glContext, QWeakPointer<QOpenGLPaintDevice> glPaintDevice) :
  685. QCPAbstractPaintBuffer(size, devicePixelRatio),
  686. mGlContext(glContext),
  687. mGlPaintDevice(glPaintDevice),
  688. mGlFrameBuffer(0)
  689. {
  690. QCPPaintBufferGlFbo::reallocateBuffer();
  691. }
  692. QCPPaintBufferGlFbo::~QCPPaintBufferGlFbo()
  693. {
  694. if (mGlFrameBuffer)
  695. delete mGlFrameBuffer;
  696. }
  697. /* inherits documentation from base class */
  698. QCPPainter *QCPPaintBufferGlFbo::startPainting()
  699. {
  700. QSharedPointer<QOpenGLPaintDevice> paintDevice = mGlPaintDevice.toStrongRef();
  701. QSharedPointer<QOpenGLContext> context = mGlContext.toStrongRef();
  702. if (!paintDevice)
  703. {
  704. qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist";
  705. return 0;
  706. }
  707. if (!context)
  708. {
  709. qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
  710. return 0;
  711. }
  712. if (!mGlFrameBuffer)
  713. {
  714. qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
  715. return 0;
  716. }
  717. if (QOpenGLContext::currentContext() != context.data())
  718. context->makeCurrent(context->surface());
  719. mGlFrameBuffer->bind();
  720. QCPPainter *result = new QCPPainter(paintDevice.data());
  721. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  722. result->setRenderHint(QPainter::HighQualityAntialiasing);
  723. #endif
  724. return result;
  725. }
  726. /* inherits documentation from base class */
  727. void QCPPaintBufferGlFbo::donePainting()
  728. {
  729. if (mGlFrameBuffer && mGlFrameBuffer->isBound())
  730. mGlFrameBuffer->release();
  731. else
  732. qDebug() << Q_FUNC_INFO << "Either OpenGL frame buffer not valid or was not bound";
  733. }
  734. /* inherits documentation from base class */
  735. void QCPPaintBufferGlFbo::draw(QCPPainter *painter) const
  736. {
  737. if (!painter || !painter->isActive())
  738. {
  739. qDebug() << Q_FUNC_INFO << "invalid or inactive painter passed";
  740. return;
  741. }
  742. if (!mGlFrameBuffer)
  743. {
  744. qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
  745. return;
  746. }
  747. painter->drawImage(0, 0, mGlFrameBuffer->toImage());
  748. }
  749. /* inherits documentation from base class */
  750. void QCPPaintBufferGlFbo::clear(const QColor &color)
  751. {
  752. QSharedPointer<QOpenGLContext> context = mGlContext.toStrongRef();
  753. if (!context)
  754. {
  755. qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
  756. return;
  757. }
  758. if (!mGlFrameBuffer)
  759. {
  760. qDebug() << Q_FUNC_INFO << "OpenGL frame buffer object doesn't exist, reallocateBuffer was not called?";
  761. return;
  762. }
  763. if (QOpenGLContext::currentContext() != context.data())
  764. context->makeCurrent(context->surface());
  765. mGlFrameBuffer->bind();
  766. glClearColor(color.redF(), color.greenF(), color.blueF(), color.alphaF());
  767. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  768. mGlFrameBuffer->release();
  769. }
  770. /* inherits documentation from base class */
  771. void QCPPaintBufferGlFbo::reallocateBuffer()
  772. {
  773. // release and delete possibly existing framebuffer:
  774. if (mGlFrameBuffer)
  775. {
  776. if (mGlFrameBuffer->isBound())
  777. mGlFrameBuffer->release();
  778. delete mGlFrameBuffer;
  779. mGlFrameBuffer = 0;
  780. }
  781. QSharedPointer<QOpenGLPaintDevice> paintDevice = mGlPaintDevice.toStrongRef();
  782. QSharedPointer<QOpenGLContext> context = mGlContext.toStrongRef();
  783. if (!paintDevice)
  784. {
  785. qDebug() << Q_FUNC_INFO << "OpenGL paint device doesn't exist";
  786. return;
  787. }
  788. if (!context)
  789. {
  790. qDebug() << Q_FUNC_INFO << "OpenGL context doesn't exist";
  791. return;
  792. }
  793. // create new fbo with appropriate size:
  794. context->makeCurrent(context->surface());
  795. QOpenGLFramebufferObjectFormat frameBufferFormat;
  796. frameBufferFormat.setSamples(context->format().samples());
  797. frameBufferFormat.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil);
  798. mGlFrameBuffer = new QOpenGLFramebufferObject(mSize*mDevicePixelRatio, frameBufferFormat);
  799. if (paintDevice->size() != mSize*mDevicePixelRatio)
  800. paintDevice->setSize(mSize*mDevicePixelRatio);
  801. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  802. paintDevice->setDevicePixelRatio(mDevicePixelRatio);
  803. #endif
  804. }
  805. #endif // QCP_OPENGL_FBO
  806. /* end of 'src/paintbuffer.cpp' */
  807. /* including file 'src/layer.cpp' */
  808. /* modified 2021-03-29T02:30:44, size 37615 */
  809. ////////////////////////////////////////////////////////////////////////////////////////////////////
  810. //////////////////// QCPLayer
  811. ////////////////////////////////////////////////////////////////////////////////////////////////////
  812. /*! \class QCPLayer
  813. \brief A layer that may contain objects, to control the rendering order
  814. The Layering system of QCustomPlot is the mechanism to control the rendering order of the
  815. elements inside the plot.
  816. It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of
  817. one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer,
  818. QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers
  819. bottom to top and successively draws the layerables of the layers into the paint buffer(s).
  820. A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base
  821. class from which almost all visible objects derive, like axes, grids, graphs, items, etc.
  822. \section qcplayer-defaultlayers Default layers
  823. Initially, QCustomPlot has six layers: "background", "grid", "main", "axes", "legend" and
  824. "overlay" (in that order). On top is the "overlay" layer, which only contains the QCustomPlot's
  825. selection rect (\ref QCustomPlot::selectionRect). The next two layers "axes" and "legend" contain
  826. the default axes and legend, so they will be drawn above plottables. In the middle, there is the
  827. "main" layer. It is initially empty and set as the current layer (see
  828. QCustomPlot::setCurrentLayer). This means, all new plottables, items etc. are created on this
  829. layer by default. Then comes the "grid" layer which contains the QCPGrid instances (which belong
  830. tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background shall be drawn behind
  831. everything else, thus the default QCPAxisRect instance is placed on the "background" layer. Of
  832. course, the layer affiliation of the individual objects can be changed as required (\ref
  833. QCPLayerable::setLayer).
  834. \section qcplayer-ordering Controlling the rendering order via layers
  835. Controlling the ordering of layerables in the plot is easy: Create a new layer in the position
  836. you want the layerable to be in, e.g. above "main", with \ref QCustomPlot::addLayer. Then set the
  837. current layer with \ref QCustomPlot::setCurrentLayer to that new layer and finally create the
  838. objects normally. They will be placed on the new layer automatically, due to the current layer
  839. setting. Alternatively you could have also ignored the current layer setting and just moved the
  840. objects with \ref QCPLayerable::setLayer to the desired layer after creating them.
  841. It is also possible to move whole layers. For example, If you want the grid to be shown in front
  842. of all plottables/items on the "main" layer, just move it above "main" with
  843. QCustomPlot::moveLayer.
  844. The rendering order within one layer is simply by order of creation or insertion. The item
  845. created last (or added last to the layer), is drawn on top of all other objects on that layer.
  846. When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below
  847. the deleted layer, see QCustomPlot::removeLayer.
  848. \section qcplayer-buffering Replotting only a specific layer
  849. If the layer mode (\ref setMode) is set to \ref lmBuffered, you can replot only this specific
  850. layer by calling \ref replot. In certain situations this can provide better replot performance,
  851. compared with a full replot of all layers. Upon creation of a new layer, the layer mode is
  852. initialized to \ref lmLogical. The only layer that is set to \ref lmBuffered in a new \ref
  853. QCustomPlot instance is the "overlay" layer, containing the selection rect.
  854. */
  855. /* start documentation of inline functions */
  856. /*! \fn QList<QCPLayerable*> QCPLayer::children() const
  857. Returns a list of all layerables on this layer. The order corresponds to the rendering order:
  858. layerables with higher indices are drawn above layerables with lower indices.
  859. */
  860. /*! \fn int QCPLayer::index() const
  861. Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be
  862. accessed via \ref QCustomPlot::layer.
  863. Layers with higher indices will be drawn above layers with lower indices.
  864. */
  865. /* end documentation of inline functions */
  866. /*!
  867. Creates a new QCPLayer instance.
  868. Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead.
  869. \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot.
  870. This check is only performed by \ref QCustomPlot::addLayer.
  871. */
  872. QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) :
  873. QObject(parentPlot),
  874. mParentPlot(parentPlot),
  875. mName(layerName),
  876. mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function
  877. mVisible(true),
  878. mMode(lmLogical)
  879. {
  880. // Note: no need to make sure layerName is unique, because layer
  881. // management is done with QCustomPlot functions.
  882. }
  883. QCPLayer::~QCPLayer()
  884. {
  885. // If child layerables are still on this layer, detach them, so they don't try to reach back to this
  886. // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted
  887. // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to
  888. // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.)
  889. while (!mChildren.isEmpty())
  890. mChildren.last()->setLayer(nullptr); // removes itself from mChildren via removeChild()
  891. if (mParentPlot->currentLayer() == this)
  892. qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or nullptr beforehand.";
  893. }
  894. /*!
  895. Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this
  896. layer will be invisible.
  897. This function doesn't change the visibility property of the layerables (\ref
  898. QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the
  899. visibility of the parent layer into account.
  900. */
  901. void QCPLayer::setVisible(bool visible)
  902. {
  903. mVisible = visible;
  904. }
  905. /*!
  906. Sets the rendering mode of this layer.
  907. If \a mode is set to \ref lmBuffered for a layer, it will be given a dedicated paint buffer by
  908. the parent QCustomPlot instance. This means it may be replotted individually by calling \ref
  909. QCPLayer::replot, without needing to replot all other layers.
  910. Layers which are set to \ref lmLogical (the default) are used only to define the rendering order
  911. and can't be replotted individually.
  912. Note that each layer which is set to \ref lmBuffered requires additional paint buffers for the
  913. layers below, above and for the layer itself. This increases the memory consumption and
  914. (slightly) decreases the repainting speed because multiple paint buffers need to be joined. So
  915. you should carefully choose which layers benefit from having their own paint buffer. A typical
  916. example would be a layer which contains certain layerables (e.g. items) that need to be changed
  917. and thus replotted regularly, while all other layerables on other layers stay static. By default,
  918. only the topmost layer called "overlay" is in mode \ref lmBuffered, and contains the selection
  919. rect.
  920. \see replot
  921. */
  922. void QCPLayer::setMode(QCPLayer::LayerMode mode)
  923. {
  924. if (mMode != mode)
  925. {
  926. mMode = mode;
  927. if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
  928. pb->setInvalidated();
  929. }
  930. }
  931. /*! \internal
  932. Draws the contents of this layer with the provided \a painter.
  933. \see replot, drawToPaintBuffer
  934. */
  935. void QCPLayer::draw(QCPPainter *painter)
  936. {
  937. foreach (QCPLayerable *child, mChildren)
  938. {
  939. if (child->realVisibility())
  940. {
  941. painter->save();
  942. painter->setClipRect(child->clipRect().translated(0, -1));
  943. child->applyDefaultAntialiasingHint(painter);
  944. child->draw(painter);
  945. painter->restore();
  946. }
  947. }
  948. }
  949. /*! \internal
  950. Draws the contents of this layer into the paint buffer which is associated with this layer. The
  951. association is established by the parent QCustomPlot, which manages all paint buffers (see \ref
  952. QCustomPlot::setupPaintBuffers).
  953. \see draw
  954. */
  955. void QCPLayer::drawToPaintBuffer()
  956. {
  957. if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
  958. {
  959. if (QCPPainter *painter = pb->startPainting())
  960. {
  961. if (painter->isActive())
  962. draw(painter);
  963. else
  964. qDebug() << Q_FUNC_INFO << "paint buffer returned inactive painter";
  965. delete painter;
  966. pb->donePainting();
  967. } else
  968. qDebug() << Q_FUNC_INFO << "paint buffer returned nullptr painter";
  969. } else
  970. qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer";
  971. }
  972. /*!
  973. If the layer mode (\ref setMode) is set to \ref lmBuffered, this method allows replotting only
  974. the layerables on this specific layer, without the need to replot all other layers (as a call to
  975. \ref QCustomPlot::replot would do).
  976. QCustomPlot also makes sure to replot all layers instead of only this one, if the layer ordering
  977. or any layerable-layer-association has changed since the last full replot and any other paint
  978. buffers were thus invalidated.
  979. If the layer mode is \ref lmLogical however, this method simply calls \ref QCustomPlot::replot on
  980. the parent QCustomPlot instance.
  981. \see draw
  982. */
  983. void QCPLayer::replot()
  984. {
  985. if (mMode == lmBuffered && !mParentPlot->hasInvalidatedPaintBuffers())
  986. {
  987. if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
  988. {
  989. pb->clear(Qt::transparent);
  990. drawToPaintBuffer();
  991. pb->setInvalidated(false); // since layer is lmBuffered, we know only this layer is on buffer and we can reset invalidated flag
  992. mParentPlot->update();
  993. } else
  994. qDebug() << Q_FUNC_INFO << "no valid paint buffer associated with this layer";
  995. } else
  996. mParentPlot->replot();
  997. }
  998. /*! \internal
  999. Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will
  1000. be prepended to the list, i.e. be drawn beneath the other layerables already in the list.
  1001. This function does not change the \a mLayer member of \a layerable to this layer. (Use
  1002. QCPLayerable::setLayer to change the layer of an object, not this function.)
  1003. \see removeChild
  1004. */
  1005. void QCPLayer::addChild(QCPLayerable *layerable, bool prepend)
  1006. {
  1007. if (!mChildren.contains(layerable))
  1008. {
  1009. if (prepend)
  1010. mChildren.prepend(layerable);
  1011. else
  1012. mChildren.append(layerable);
  1013. if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
  1014. pb->setInvalidated();
  1015. } else
  1016. qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast<quintptr>(layerable);
  1017. }
  1018. /*! \internal
  1019. Removes the \a layerable from the list of this layer.
  1020. This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer
  1021. to change the layer of an object, not this function.)
  1022. \see addChild
  1023. */
  1024. void QCPLayer::removeChild(QCPLayerable *layerable)
  1025. {
  1026. if (mChildren.removeOne(layerable))
  1027. {
  1028. if (QSharedPointer<QCPAbstractPaintBuffer> pb = mPaintBuffer.toStrongRef())
  1029. pb->setInvalidated();
  1030. } else
  1031. qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast<quintptr>(layerable);
  1032. }
  1033. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1034. //////////////////// QCPLayerable
  1035. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1036. /*! \class QCPLayerable
  1037. \brief Base class for all drawable objects
  1038. This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid
  1039. etc.
  1040. Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking
  1041. the layers accordingly.
  1042. For details about the layering mechanism, see the QCPLayer documentation.
  1043. */
  1044. /* start documentation of inline functions */
  1045. /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const
  1046. Returns the parent layerable of this layerable. The parent layerable is used to provide
  1047. visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables
  1048. only get drawn if their parent layerables are visible, too.
  1049. Note that a parent layerable is not necessarily also the QObject parent for memory management.
  1050. Further, a layerable doesn't always have a parent layerable, so this function may return \c
  1051. nullptr.
  1052. A parent layerable is set implicitly when placed inside layout elements and doesn't need to be
  1053. set manually by the user.
  1054. */
  1055. /* end documentation of inline functions */
  1056. /* start documentation of pure virtual functions */
  1057. /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0
  1058. \internal
  1059. This function applies the default antialiasing setting to the specified \a painter, using the
  1060. function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when
  1061. \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing
  1062. setting may be specified individually, this function should set the antialiasing state of the
  1063. most prominent entity. In this case however, the \ref draw function usually calls the specialized
  1064. versions of this function before drawing each entity, effectively overriding the setting of the
  1065. default antialiasing hint.
  1066. <b>First example:</b> QCPGraph has multiple entities that have an antialiasing setting: The graph
  1067. line, fills and scatters. Those can be configured via QCPGraph::setAntialiased,
  1068. QCPGraph::setAntialiasedFill and QCPGraph::setAntialiasedScatters. Consequently, there isn't only
  1069. the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's
  1070. antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and
  1071. QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw
  1072. calls the respective specialized applyAntialiasingHint function.
  1073. <b>Second example:</b> QCPItemLine consists only of a line so there is only one antialiasing
  1074. setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by
  1075. all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the
  1076. respective layerable subclass.) Consequently it only has the normal
  1077. QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to
  1078. care about setting any antialiasing states, because the default antialiasing hint is already set
  1079. on the painter when the \ref draw function is called, and that's the state it wants to draw the
  1080. line with.
  1081. */
  1082. /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0
  1083. \internal
  1084. This function draws the layerable with the specified \a painter. It is only called by
  1085. QCustomPlot, if the layerable is visible (\ref setVisible).
  1086. Before this function is called, the painter's antialiasing state is set via \ref
  1087. applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was
  1088. set to \ref clipRect.
  1089. */
  1090. /* end documentation of pure virtual functions */
  1091. /* start documentation of signals */
  1092. /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer);
  1093. This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to
  1094. a different layer.
  1095. \see setLayer
  1096. */
  1097. /* end documentation of signals */
  1098. /*!
  1099. Creates a new QCPLayerable instance.
  1100. Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the
  1101. derived classes.
  1102. If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a
  1103. targetLayer is an empty string, it places itself on the current layer of the plot (see \ref
  1104. QCustomPlot::setCurrentLayer).
  1105. It is possible to provide \c nullptr as \a plot. In that case, you should assign a parent plot at
  1106. a later time with \ref initializeParentPlot.
  1107. The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable
  1108. parents are mainly used to control visibility in a hierarchy of layerables. This means a
  1109. layerable is only drawn, if all its ancestor layerables are also visible. Note that \a
  1110. parentLayerable does not become the QObject-parent (for memory management) of this layerable, \a
  1111. plot does. It is not uncommon to set the QObject-parent to something else in the constructors of
  1112. QCPLayerable subclasses, to guarantee a working destruction hierarchy.
  1113. */
  1114. QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) :
  1115. QObject(plot),
  1116. mVisible(true),
  1117. mParentPlot(plot),
  1118. mParentLayerable(parentLayerable),
  1119. mLayer(nullptr),
  1120. mAntialiased(true)
  1121. {
  1122. if (mParentPlot)
  1123. {
  1124. if (targetLayer.isEmpty())
  1125. setLayer(mParentPlot->currentLayer());
  1126. else if (!setLayer(targetLayer))
  1127. qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed.";
  1128. }
  1129. }
  1130. QCPLayerable::~QCPLayerable()
  1131. {
  1132. if (mLayer)
  1133. {
  1134. mLayer->removeChild(this);
  1135. mLayer = nullptr;
  1136. }
  1137. }
  1138. /*!
  1139. Sets the visibility of this layerable object. If an object is not visible, it will not be drawn
  1140. on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not
  1141. possible.
  1142. */
  1143. void QCPLayerable::setVisible(bool on)
  1144. {
  1145. mVisible = on;
  1146. }
  1147. /*!
  1148. Sets the \a layer of this layerable object. The object will be placed on top of the other objects
  1149. already on \a layer.
  1150. If \a layer is 0, this layerable will not be on any layer and thus not appear in the plot (or
  1151. interact/receive events).
  1152. Returns true if the layer of this layerable was successfully changed to \a layer.
  1153. */
  1154. bool QCPLayerable::setLayer(QCPLayer *layer)
  1155. {
  1156. return moveToLayer(layer, false);
  1157. }
  1158. /*! \overload
  1159. Sets the layer of this layerable object by name
  1160. Returns true on success, i.e. if \a layerName is a valid layer name.
  1161. */
  1162. bool QCPLayerable::setLayer(const QString &layerName)
  1163. {
  1164. if (!mParentPlot)
  1165. {
  1166. qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
  1167. return false;
  1168. }
  1169. if (QCPLayer *layer = mParentPlot->layer(layerName))
  1170. {
  1171. return setLayer(layer);
  1172. } else
  1173. {
  1174. qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName;
  1175. return false;
  1176. }
  1177. }
  1178. /*!
  1179. Sets whether this object will be drawn antialiased or not.
  1180. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
  1181. QCustomPlot::setNotAntialiasedElements.
  1182. */
  1183. void QCPLayerable::setAntialiased(bool enabled)
  1184. {
  1185. mAntialiased = enabled;
  1186. }
  1187. /*!
  1188. Returns whether this layerable is visible, taking the visibility of the layerable parent and the
  1189. visibility of this layerable's layer into account. This is the method that is consulted to decide
  1190. whether a layerable shall be drawn or not.
  1191. If this layerable has a direct layerable parent (usually set via hierarchies implemented in
  1192. subclasses, like in the case of \ref QCPLayoutElement), this function returns true only if this
  1193. layerable has its visibility set to true and the parent layerable's \ref realVisibility returns
  1194. true.
  1195. */
  1196. bool QCPLayerable::realVisibility() const
  1197. {
  1198. return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility());
  1199. }
  1200. /*!
  1201. This function is used to decide whether a click hits a layerable object or not.
  1202. \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the
  1203. shortest pixel distance of this point to the object. If the object is either invisible or the
  1204. distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the
  1205. object is not selectable, -1.0 is returned, too.
  1206. If the object is represented not by single lines but by an area like a \ref QCPItemText or the
  1207. bars of a \ref QCPBars plottable, a click inside the area should also be considered a hit. In
  1208. these cases this function thus returns a constant value greater zero but still below the parent
  1209. plot's selection tolerance. (typically the selectionTolerance multiplied by 0.99).
  1210. Providing a constant value for area objects allows selecting line objects even when they are
  1211. obscured by such area objects, by clicking close to the lines (i.e. closer than
  1212. 0.99*selectionTolerance).
  1213. The actual setting of the selection state is not done by this function. This is handled by the
  1214. parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified
  1215. via the \ref selectEvent/\ref deselectEvent methods.
  1216. \a details is an optional output parameter. Every layerable subclass may place any information
  1217. in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot
  1218. decides on the basis of this selectTest call, that the object was successfully selected. The
  1219. subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part
  1220. objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked
  1221. is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be
  1222. placed in \a details. So in the subsequent \ref selectEvent, the decision which part was
  1223. selected doesn't have to be done a second time for a single selection operation.
  1224. In the case of 1D Plottables (\ref QCPAbstractPlottable1D, like \ref QCPGraph or \ref QCPBars) \a
  1225. details will be set to a \ref QCPDataSelection, describing the closest data point to \a pos.
  1226. You may pass \c nullptr as \a details to indicate that you are not interested in those selection
  1227. details.
  1228. \see selectEvent, deselectEvent, mousePressEvent, wheelEvent, QCustomPlot::setInteractions,
  1229. QCPAbstractPlottable1D::selectTestRect
  1230. */
  1231. double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  1232. {
  1233. Q_UNUSED(pos)
  1234. Q_UNUSED(onlySelectable)
  1235. Q_UNUSED(details)
  1236. return -1.0;
  1237. }
  1238. /*! \internal
  1239. Sets the parent plot of this layerable. Use this function once to set the parent plot if you have
  1240. passed \c nullptr in the constructor. It can not be used to move a layerable from one QCustomPlot
  1241. to another one.
  1242. Note that, unlike when passing a non \c nullptr parent plot in the constructor, this function
  1243. does not make \a parentPlot the QObject-parent of this layerable. If you want this, call
  1244. QObject::setParent(\a parentPlot) in addition to this function.
  1245. Further, you will probably want to set a layer (\ref setLayer) after calling this function, to
  1246. make the layerable appear on the QCustomPlot.
  1247. The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized
  1248. so they can react accordingly (e.g. also initialize the parent plot of child layerables, like
  1249. QCPLayout does).
  1250. */
  1251. void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot)
  1252. {
  1253. if (mParentPlot)
  1254. {
  1255. qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized";
  1256. return;
  1257. }
  1258. if (!parentPlot)
  1259. qDebug() << Q_FUNC_INFO << "called with parentPlot zero";
  1260. mParentPlot = parentPlot;
  1261. parentPlotInitialized(mParentPlot);
  1262. }
  1263. /*! \internal
  1264. Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not
  1265. become the QObject-parent (for memory management) of this layerable.
  1266. The parent layerable has influence on the return value of the \ref realVisibility method. Only
  1267. layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be
  1268. drawn.
  1269. \see realVisibility
  1270. */
  1271. void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable)
  1272. {
  1273. mParentLayerable = parentLayerable;
  1274. }
  1275. /*! \internal
  1276. Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to
  1277. the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is
  1278. false, the object will be appended.
  1279. Returns true on success, i.e. if \a layer is a valid layer.
  1280. */
  1281. bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend)
  1282. {
  1283. if (layer && !mParentPlot)
  1284. {
  1285. qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set";
  1286. return false;
  1287. }
  1288. if (layer && layer->parentPlot() != mParentPlot)
  1289. {
  1290. qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable";
  1291. return false;
  1292. }
  1293. QCPLayer *oldLayer = mLayer;
  1294. if (mLayer)
  1295. mLayer->removeChild(this);
  1296. mLayer = layer;
  1297. if (mLayer)
  1298. mLayer->addChild(this, prepend);
  1299. if (mLayer != oldLayer)
  1300. Q_EMIT layerChanged(mLayer);
  1301. return true;
  1302. }
  1303. /*! \internal
  1304. Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a
  1305. localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref
  1306. QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is
  1307. controlled via \a overrideElement.
  1308. */
  1309. void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const
  1310. {
  1311. if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement))
  1312. painter->setAntialiasing(false);
  1313. else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement))
  1314. painter->setAntialiasing(true);
  1315. else
  1316. painter->setAntialiasing(localAntialiased);
  1317. }
  1318. /*! \internal
  1319. This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting
  1320. of a parent plot. This is the case when \c nullptr was passed as parent plot in the constructor,
  1321. and the parent plot is set at a later time.
  1322. For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any
  1323. QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level
  1324. element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To
  1325. propagate the parent plot to all the children of the hierarchy, the top level element then uses
  1326. this function to pass the parent plot on to its child elements.
  1327. The default implementation does nothing.
  1328. \see initializeParentPlot
  1329. */
  1330. void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot)
  1331. {
  1332. Q_UNUSED(parentPlot)
  1333. }
  1334. /*! \internal
  1335. Returns the selection category this layerable shall belong to. The selection category is used in
  1336. conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and
  1337. which aren't.
  1338. Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref
  1339. QCP::iSelectOther. This is what the default implementation returns.
  1340. \see QCustomPlot::setInteractions
  1341. */
  1342. QCP::Interaction QCPLayerable::selectionCategory() const
  1343. {
  1344. return QCP::iSelectOther;
  1345. }
  1346. /*! \internal
  1347. Returns the clipping rectangle of this layerable object. By default, this is the viewport of the
  1348. parent QCustomPlot. Specific subclasses may reimplement this function to provide different
  1349. clipping rects.
  1350. The returned clipping rect is set on the painter before the draw function of the respective
  1351. object is called.
  1352. */
  1353. QRect QCPLayerable::clipRect() const
  1354. {
  1355. if (mParentPlot)
  1356. return mParentPlot->viewport();
  1357. else
  1358. return {};
  1359. }
  1360. /*! \internal
  1361. This event is called when the layerable shall be selected, as a consequence of a click by the
  1362. user. Subclasses should react to it by setting their selection state appropriately. The default
  1363. implementation does nothing.
  1364. \a event is the mouse event that caused the selection. \a additive indicates, whether the user
  1365. was holding the multi-select-modifier while performing the selection (see \ref
  1366. QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled
  1367. (i.e. become selected when unselected and unselected when selected).
  1368. Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e.
  1369. returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot).
  1370. The \a details data you output from \ref selectTest is fed back via \a details here. You may
  1371. use it to transport any kind of information from the selectTest to the possibly subsequent
  1372. selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable
  1373. that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need
  1374. to do the calculation again to find out which part was actually clicked.
  1375. \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must
  1376. set the value either to true or false, depending on whether the selection state of this layerable
  1377. was actually changed. For layerables that only are selectable as a whole and not in parts, this
  1378. is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the
  1379. selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the
  1380. layerable was previously unselected and now is switched to the selected state.
  1381. \see selectTest, deselectEvent
  1382. */
  1383. void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  1384. {
  1385. Q_UNUSED(event)
  1386. Q_UNUSED(additive)
  1387. Q_UNUSED(details)
  1388. Q_UNUSED(selectionStateChanged)
  1389. }
  1390. /*! \internal
  1391. This event is called when the layerable shall be deselected, either as consequence of a user
  1392. interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by
  1393. unsetting their selection appropriately.
  1394. just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must
  1395. return true or false when the selection state of this layerable has changed or not changed,
  1396. respectively.
  1397. \see selectTest, selectEvent
  1398. */
  1399. void QCPLayerable::deselectEvent(bool *selectionStateChanged)
  1400. {
  1401. Q_UNUSED(selectionStateChanged)
  1402. }
  1403. /*!
  1404. This event gets called when the user presses a mouse button while the cursor is over the
  1405. layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref
  1406. selectTest.
  1407. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1408. event->pos(). The parameter \a details contains layerable-specific details about the hit, which
  1409. were generated in the previous call to \ref selectTest. For example, One-dimensional plottables
  1410. like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as
  1411. \ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c
  1412. SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes).
  1413. QCustomPlot uses an event propagation system that works the same as Qt's system. If your
  1414. layerable doesn't reimplement the \ref mousePressEvent or explicitly calls \c event->ignore() in
  1415. its reimplementation, the event will be propagated to the next layerable in the stacking order.
  1416. Once a layerable has accepted the \ref mousePressEvent, it is considered the mouse grabber and
  1417. will receive all following calls to \ref mouseMoveEvent or \ref mouseReleaseEvent for this mouse
  1418. interaction (a "mouse interaction" in this context ends with the release).
  1419. The default implementation does nothing except explicitly ignoring the event with \c
  1420. event->ignore().
  1421. \see mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent
  1422. */
  1423. void QCPLayerable::mousePressEvent(QMouseEvent *event, const QVariant &details)
  1424. {
  1425. Q_UNUSED(details)
  1426. event->ignore();
  1427. }
  1428. /*!
  1429. This event gets called when the user moves the mouse while holding a mouse button, after this
  1430. layerable has become the mouse grabber by accepting the preceding \ref mousePressEvent.
  1431. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1432. event->pos(). The parameter \a startPos indicates the position where the initial \ref
  1433. mousePressEvent occurred, that started the mouse interaction.
  1434. The default implementation does nothing.
  1435. \see mousePressEvent, mouseReleaseEvent, mouseDoubleClickEvent, wheelEvent
  1436. */
  1437. void QCPLayerable::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  1438. {
  1439. Q_UNUSED(startPos)
  1440. event->ignore();
  1441. }
  1442. /*!
  1443. This event gets called when the user releases the mouse button, after this layerable has become
  1444. the mouse grabber by accepting the preceding \ref mousePressEvent.
  1445. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1446. event->pos(). The parameter \a startPos indicates the position where the initial \ref
  1447. mousePressEvent occurred, that started the mouse interaction.
  1448. The default implementation does nothing.
  1449. \see mousePressEvent, mouseMoveEvent, mouseDoubleClickEvent, wheelEvent
  1450. */
  1451. void QCPLayerable::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  1452. {
  1453. Q_UNUSED(startPos)
  1454. event->ignore();
  1455. }
  1456. /*!
  1457. This event gets called when the user presses the mouse button a second time in a double-click,
  1458. while the cursor is over the layerable. Whether a cursor is over the layerable is decided by a
  1459. preceding call to \ref selectTest.
  1460. The \ref mouseDoubleClickEvent is called instead of the second \ref mousePressEvent. So in the
  1461. case of a double-click, the event succession is
  1462. <i>pressEvent &ndash; releaseEvent &ndash; doubleClickEvent &ndash; releaseEvent</i>.
  1463. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1464. event->pos(). The parameter \a details contains layerable-specific details about the hit, which
  1465. were generated in the previous call to \ref selectTest. For example, One-dimensional plottables
  1466. like \ref QCPGraph or \ref QCPBars convey the clicked data point in the \a details parameter, as
  1467. \ref QCPDataSelection packed as QVariant. Multi-part objects convey the specific \c
  1468. SelectablePart that was hit (e.g. \ref QCPAxis::SelectablePart in the case of axes).
  1469. Similarly to \ref mousePressEvent, once a layerable has accepted the \ref mouseDoubleClickEvent,
  1470. it is considered the mouse grabber and will receive all following calls to \ref mouseMoveEvent
  1471. and \ref mouseReleaseEvent for this mouse interaction (a "mouse interaction" in this context ends
  1472. with the release).
  1473. The default implementation does nothing except explicitly ignoring the event with \c
  1474. event->ignore().
  1475. \see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, wheelEvent
  1476. */
  1477. void QCPLayerable::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
  1478. {
  1479. Q_UNUSED(details)
  1480. event->ignore();
  1481. }
  1482. /*!
  1483. This event gets called when the user turns the mouse scroll wheel while the cursor is over the
  1484. layerable. Whether a cursor is over the layerable is decided by a preceding call to \ref
  1485. selectTest.
  1486. The current pixel position of the cursor on the QCustomPlot widget is accessible via \c
  1487. event->pos().
  1488. The \c event->angleDelta() indicates how far the mouse wheel was turned, which is usually +/- 120
  1489. for single rotation steps. However, if the mouse wheel is turned rapidly, multiple steps may
  1490. accumulate to one event, making the delta larger. On the other hand, if the wheel has very smooth
  1491. steps or none at all, the delta may be smaller.
  1492. The default implementation does nothing.
  1493. \see mousePressEvent, mouseMoveEvent, mouseReleaseEvent, mouseDoubleClickEvent
  1494. */
  1495. void QCPLayerable::wheelEvent(QWheelEvent *event)
  1496. {
  1497. event->ignore();
  1498. }
  1499. /* end of 'src/layer.cpp' */
  1500. /* including file 'src/axis/range.cpp' */
  1501. /* modified 2021-03-29T02:30:44, size 12221 */
  1502. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1503. //////////////////// QCPRange
  1504. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1505. /*! \class QCPRange
  1506. \brief Represents the range an axis is encompassing.
  1507. contains a \a lower and \a upper double value and provides convenience input, output and
  1508. modification functions.
  1509. \see QCPAxis::setRange
  1510. */
  1511. /* start of documentation of inline functions */
  1512. /*! \fn double QCPRange::size() const
  1513. Returns the size of the range, i.e. \a upper-\a lower
  1514. */
  1515. /*! \fn double QCPRange::center() const
  1516. Returns the center of the range, i.e. (\a upper+\a lower)*0.5
  1517. */
  1518. /*! \fn void QCPRange::normalize()
  1519. Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values are
  1520. swapped.
  1521. */
  1522. /*! \fn bool QCPRange::contains(double value) const
  1523. Returns true when \a value lies within or exactly on the borders of the range.
  1524. */
  1525. /*! \fn QCPRange &QCPRange::operator+=(const double& value)
  1526. Adds \a value to both boundaries of the range.
  1527. */
  1528. /*! \fn QCPRange &QCPRange::operator-=(const double& value)
  1529. Subtracts \a value from both boundaries of the range.
  1530. */
  1531. /*! \fn QCPRange &QCPRange::operator*=(const double& value)
  1532. Multiplies both boundaries of the range by \a value.
  1533. */
  1534. /*! \fn QCPRange &QCPRange::operator/=(const double& value)
  1535. Divides both boundaries of the range by \a value.
  1536. */
  1537. /* end of documentation of inline functions */
  1538. /*!
  1539. Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller
  1540. intervals would cause errors due to the 11-bit exponent of double precision numbers,
  1541. corresponding to a minimum magnitude of roughly 1e-308.
  1542. \warning Do not use this constant to indicate "arbitrarily small" values in plotting logic (as
  1543. values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to
  1544. prevent axis ranges from obtaining underflowing ranges.
  1545. \see validRange, maxRange
  1546. */
  1547. const double QCPRange::minRange = 1e-280;
  1548. /*!
  1549. Maximum values (negative and positive) the range will accept in range-changing functions.
  1550. Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers,
  1551. corresponding to a maximum magnitude of roughly 1e308.
  1552. \warning Do not use this constant to indicate "arbitrarily large" values in plotting logic (as
  1553. values that will appear in the plot)! It is intended only as a bound to compare against, e.g. to
  1554. prevent axis ranges from obtaining overflowing ranges.
  1555. \see validRange, minRange
  1556. */
  1557. const double QCPRange::maxRange = 1e250;
  1558. /*!
  1559. Constructs a range with \a lower and \a upper set to zero.
  1560. */
  1561. QCPRange::QCPRange() :
  1562. lower(0),
  1563. upper(0)
  1564. {
  1565. }
  1566. /*! \overload
  1567. Constructs a range with the specified \a lower and \a upper values.
  1568. The resulting range will be normalized (see \ref normalize), so if \a lower is not numerically
  1569. smaller than \a upper, they will be swapped.
  1570. */
  1571. QCPRange::QCPRange(double lower, double upper) :
  1572. lower(lower),
  1573. upper(upper)
  1574. {
  1575. normalize();
  1576. }
  1577. /*! \overload
  1578. Expands this range such that \a otherRange is contained in the new range. It is assumed that both
  1579. this range and \a otherRange are normalized (see \ref normalize).
  1580. If this range contains NaN as lower or upper bound, it will be replaced by the respective bound
  1581. of \a otherRange.
  1582. If \a otherRange is already inside the current range, this function does nothing.
  1583. \see expanded
  1584. */
  1585. void QCPRange::expand(const QCPRange &otherRange)
  1586. {
  1587. if (lower > otherRange.lower || qIsNaN(lower))
  1588. lower = otherRange.lower;
  1589. if (upper < otherRange.upper || qIsNaN(upper))
  1590. upper = otherRange.upper;
  1591. }
  1592. /*! \overload
  1593. Expands this range such that \a includeCoord is contained in the new range. It is assumed that
  1594. this range is normalized (see \ref normalize).
  1595. If this range contains NaN as lower or upper bound, the respective bound will be set to \a
  1596. includeCoord.
  1597. If \a includeCoord is already inside the current range, this function does nothing.
  1598. \see expand
  1599. */
  1600. void QCPRange::expand(double includeCoord)
  1601. {
  1602. if (lower > includeCoord || qIsNaN(lower))
  1603. lower = includeCoord;
  1604. if (upper < includeCoord || qIsNaN(upper))
  1605. upper = includeCoord;
  1606. }
  1607. /*! \overload
  1608. Returns an expanded range that contains this and \a otherRange. It is assumed that both this
  1609. range and \a otherRange are normalized (see \ref normalize).
  1610. If this range contains NaN as lower or upper bound, the returned range's bound will be taken from
  1611. \a otherRange.
  1612. \see expand
  1613. */
  1614. QCPRange QCPRange::expanded(const QCPRange &otherRange) const
  1615. {
  1616. QCPRange result = *this;
  1617. result.expand(otherRange);
  1618. return result;
  1619. }
  1620. /*! \overload
  1621. Returns an expanded range that includes the specified \a includeCoord. It is assumed that this
  1622. range is normalized (see \ref normalize).
  1623. If this range contains NaN as lower or upper bound, the returned range's bound will be set to \a
  1624. includeCoord.
  1625. \see expand
  1626. */
  1627. QCPRange QCPRange::expanded(double includeCoord) const
  1628. {
  1629. QCPRange result = *this;
  1630. result.expand(includeCoord);
  1631. return result;
  1632. }
  1633. /*!
  1634. Returns this range, possibly modified to not exceed the bounds provided as \a lowerBound and \a
  1635. upperBound. If possible, the size of the current range is preserved in the process.
  1636. If the range shall only be bounded at the lower side, you can set \a upperBound to \ref
  1637. QCPRange::maxRange. If it shall only be bounded at the upper side, set \a lowerBound to -\ref
  1638. QCPRange::maxRange.
  1639. */
  1640. QCPRange QCPRange::bounded(double lowerBound, double upperBound) const
  1641. {
  1642. if (lowerBound > upperBound)
  1643. qSwap(lowerBound, upperBound);
  1644. QCPRange result(lower, upper);
  1645. if (result.lower < lowerBound)
  1646. {
  1647. result.lower = lowerBound;
  1648. result.upper = lowerBound + size();
  1649. if (result.upper > upperBound || qFuzzyCompare(size(), upperBound-lowerBound))
  1650. result.upper = upperBound;
  1651. } else if (result.upper > upperBound)
  1652. {
  1653. result.upper = upperBound;
  1654. result.lower = upperBound - size();
  1655. if (result.lower < lowerBound || qFuzzyCompare(size(), upperBound-lowerBound))
  1656. result.lower = lowerBound;
  1657. }
  1658. return result;
  1659. }
  1660. /*!
  1661. Returns a sanitized version of the range. Sanitized means for logarithmic scales, that
  1662. the range won't span the positive and negative sign domain, i.e. contain zero. Further
  1663. \a lower will always be numerically smaller (or equal) to \a upper.
  1664. If the original range does span positive and negative sign domains or contains zero,
  1665. the returned range will try to approximate the original range as good as possible.
  1666. If the positive interval of the original range is wider than the negative interval, the
  1667. returned range will only contain the positive interval, with lower bound set to \a rangeFac or
  1668. \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval
  1669. is wider than the positive interval, this time by changing the \a upper bound.
  1670. */
  1671. QCPRange QCPRange::sanitizedForLogScale() const
  1672. {
  1673. double rangeFac = 1e-3;
  1674. QCPRange sanitizedRange(lower, upper);
  1675. sanitizedRange.normalize();
  1676. // can't have range spanning negative and positive values in log plot, so change range to fix it
  1677. //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1))
  1678. if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0)
  1679. {
  1680. // case lower is 0
  1681. if (rangeFac < sanitizedRange.upper*rangeFac)
  1682. sanitizedRange.lower = rangeFac;
  1683. else
  1684. sanitizedRange.lower = sanitizedRange.upper*rangeFac;
  1685. } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1))
  1686. else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0)
  1687. {
  1688. // case upper is 0
  1689. if (-rangeFac > sanitizedRange.lower*rangeFac)
  1690. sanitizedRange.upper = -rangeFac;
  1691. else
  1692. sanitizedRange.upper = sanitizedRange.lower*rangeFac;
  1693. } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0)
  1694. {
  1695. // find out whether negative or positive interval is wider to decide which sign domain will be chosen
  1696. if (-sanitizedRange.lower > sanitizedRange.upper)
  1697. {
  1698. // negative is wider, do same as in case upper is 0
  1699. if (-rangeFac > sanitizedRange.lower*rangeFac)
  1700. sanitizedRange.upper = -rangeFac;
  1701. else
  1702. sanitizedRange.upper = sanitizedRange.lower*rangeFac;
  1703. } else
  1704. {
  1705. // positive is wider, do same as in case lower is 0
  1706. if (rangeFac < sanitizedRange.upper*rangeFac)
  1707. sanitizedRange.lower = rangeFac;
  1708. else
  1709. sanitizedRange.lower = sanitizedRange.upper*rangeFac;
  1710. }
  1711. }
  1712. // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper<lower
  1713. return sanitizedRange;
  1714. }
  1715. /*!
  1716. Returns a sanitized version of the range. Sanitized means for linear scales, that
  1717. \a lower will always be numerically smaller (or equal) to \a upper.
  1718. */
  1719. QCPRange QCPRange::sanitizedForLinScale() const
  1720. {
  1721. QCPRange sanitizedRange(lower, upper);
  1722. sanitizedRange.normalize();
  1723. return sanitizedRange;
  1724. }
  1725. /*!
  1726. Checks, whether the specified range is within valid bounds, which are defined
  1727. as QCPRange::maxRange and QCPRange::minRange.
  1728. A valid range means:
  1729. \li range bounds within -maxRange and maxRange
  1730. \li range size above minRange
  1731. \li range size below maxRange
  1732. */
  1733. bool QCPRange::validRange(double lower, double upper)
  1734. {
  1735. return (lower > -maxRange &&
  1736. upper < maxRange &&
  1737. qAbs(lower-upper) > minRange &&
  1738. qAbs(lower-upper) < maxRange &&
  1739. !(lower > 0 && qIsInf(upper/lower)) &&
  1740. !(upper < 0 && qIsInf(lower/upper)));
  1741. }
  1742. /*!
  1743. \overload
  1744. Checks, whether the specified range is within valid bounds, which are defined
  1745. as QCPRange::maxRange and QCPRange::minRange.
  1746. A valid range means:
  1747. \li range bounds within -maxRange and maxRange
  1748. \li range size above minRange
  1749. \li range size below maxRange
  1750. */
  1751. bool QCPRange::validRange(const QCPRange &range)
  1752. {
  1753. return (range.lower > -maxRange &&
  1754. range.upper < maxRange &&
  1755. qAbs(range.lower-range.upper) > minRange &&
  1756. qAbs(range.lower-range.upper) < maxRange &&
  1757. !(range.lower > 0 && qIsInf(range.upper/range.lower)) &&
  1758. !(range.upper < 0 && qIsInf(range.lower/range.upper)));
  1759. }
  1760. /* end of 'src/axis/range.cpp' */
  1761. /* including file 'src/selection.cpp' */
  1762. /* modified 2021-03-29T02:30:44, size 21837 */
  1763. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1764. //////////////////// QCPDataRange
  1765. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1766. /*! \class QCPDataRange
  1767. \brief Describes a data range given by begin and end index
  1768. QCPDataRange holds two integers describing the begin (\ref setBegin) and end (\ref setEnd) index
  1769. of a contiguous set of data points. The \a end index corresponds to the data point just after the
  1770. last data point of the data range, like in standard iterators.
  1771. Data Ranges are not bound to a certain plottable, thus they can be freely exchanged, created and
  1772. modified. If a non-contiguous data set shall be described, the class \ref QCPDataSelection is
  1773. used, which holds and manages multiple instances of \ref QCPDataRange. In most situations, \ref
  1774. QCPDataSelection is thus used.
  1775. Both \ref QCPDataRange and \ref QCPDataSelection offer convenience methods to work with them,
  1776. e.g. \ref bounded, \ref expanded, \ref intersects, \ref intersection, \ref adjusted, \ref
  1777. contains. Further, addition and subtraction operators (defined in \ref QCPDataSelection) can be
  1778. used to join/subtract data ranges and data selections (or mixtures), to retrieve a corresponding
  1779. \ref QCPDataSelection.
  1780. %QCustomPlot's \ref dataselection "data selection mechanism" is based on \ref QCPDataSelection and
  1781. QCPDataRange.
  1782. \note Do not confuse \ref QCPDataRange with \ref QCPRange. A \ref QCPRange describes an interval
  1783. in floating point plot coordinates, e.g. the current axis range.
  1784. */
  1785. /* start documentation of inline functions */
  1786. /*! \fn int QCPDataRange::size() const
  1787. Returns the number of data points described by this data range. This is equal to the end index
  1788. minus the begin index.
  1789. \see length
  1790. */
  1791. /*! \fn int QCPDataRange::length() const
  1792. Returns the number of data points described by this data range. Equivalent to \ref size.
  1793. */
  1794. /*! \fn void QCPDataRange::setBegin(int begin)
  1795. Sets the begin of this data range. The \a begin index points to the first data point that is part
  1796. of the data range.
  1797. No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
  1798. \see setEnd
  1799. */
  1800. /*! \fn void QCPDataRange::setEnd(int end)
  1801. Sets the end of this data range. The \a end index points to the data point just after the last
  1802. data point that is part of the data range.
  1803. No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
  1804. \see setBegin
  1805. */
  1806. /*! \fn bool QCPDataRange::isValid() const
  1807. Returns whether this range is valid. A valid range has a begin index greater or equal to 0, and
  1808. an end index greater or equal to the begin index.
  1809. \note Invalid ranges should be avoided and are never the result of any of QCustomPlot's methods
  1810. (unless they are themselves fed with invalid ranges). Do not pass invalid ranges to QCustomPlot's
  1811. methods. The invalid range is not inherently prevented in QCPDataRange, to allow temporary
  1812. invalid begin/end values while manipulating the range. An invalid range is not necessarily empty
  1813. (\ref isEmpty), since its \ref length can be negative and thus non-zero.
  1814. */
  1815. /*! \fn bool QCPDataRange::isEmpty() const
  1816. Returns whether this range is empty, i.e. whether its begin index equals its end index.
  1817. \see size, length
  1818. */
  1819. /*! \fn QCPDataRange QCPDataRange::adjusted(int changeBegin, int changeEnd) const
  1820. Returns a data range where \a changeBegin and \a changeEnd were added to the begin and end
  1821. indices, respectively.
  1822. */
  1823. /* end documentation of inline functions */
  1824. /*!
  1825. Creates an empty QCPDataRange, with begin and end set to 0.
  1826. */
  1827. QCPDataRange::QCPDataRange() :
  1828. mBegin(0),
  1829. mEnd(0)
  1830. {
  1831. }
  1832. /*!
  1833. Creates a QCPDataRange, initialized with the specified \a begin and \a end.
  1834. No checks or corrections are made to ensure the resulting range is valid (\ref isValid).
  1835. */
  1836. QCPDataRange::QCPDataRange(int begin, int end) :
  1837. mBegin(begin),
  1838. mEnd(end)
  1839. {
  1840. }
  1841. /*!
  1842. Returns a data range that matches this data range, except that parts exceeding \a other are
  1843. excluded.
  1844. This method is very similar to \ref intersection, with one distinction: If this range and the \a
  1845. other range share no intersection, the returned data range will be empty with begin and end set
  1846. to the respective boundary side of \a other, at which this range is residing. (\ref intersection
  1847. would just return a range with begin and end set to 0.)
  1848. */
  1849. QCPDataRange QCPDataRange::bounded(const QCPDataRange &other) const
  1850. {
  1851. QCPDataRange result(intersection(other));
  1852. if (result.isEmpty()) // no intersection, preserve respective bounding side of otherRange as both begin and end of return value
  1853. {
  1854. if (mEnd <= other.mBegin)
  1855. result = QCPDataRange(other.mBegin, other.mBegin);
  1856. else
  1857. result = QCPDataRange(other.mEnd, other.mEnd);
  1858. }
  1859. return result;
  1860. }
  1861. /*!
  1862. Returns a data range that contains both this data range as well as \a other.
  1863. */
  1864. QCPDataRange QCPDataRange::expanded(const QCPDataRange &other) const
  1865. {
  1866. return {qMin(mBegin, other.mBegin), qMax(mEnd, other.mEnd)};
  1867. }
  1868. /*!
  1869. Returns the data range which is contained in both this data range and \a other.
  1870. This method is very similar to \ref bounded, with one distinction: If this range and the \a other
  1871. range share no intersection, the returned data range will be empty with begin and end set to 0.
  1872. (\ref bounded would return a range with begin and end set to one of the boundaries of \a other,
  1873. depending on which side this range is on.)
  1874. \see QCPDataSelection::intersection
  1875. */
  1876. QCPDataRange QCPDataRange::intersection(const QCPDataRange &other) const
  1877. {
  1878. QCPDataRange result(qMax(mBegin, other.mBegin), qMin(mEnd, other.mEnd));
  1879. if (result.isValid())
  1880. return result;
  1881. else
  1882. return {};
  1883. }
  1884. /*!
  1885. Returns whether this data range and \a other share common data points.
  1886. \see intersection, contains
  1887. */
  1888. bool QCPDataRange::intersects(const QCPDataRange &other) const
  1889. {
  1890. return !( (mBegin > other.mBegin && mBegin >= other.mEnd) ||
  1891. (mEnd <= other.mBegin && mEnd < other.mEnd) );
  1892. }
  1893. /*!
  1894. Returns whether all data points of \a other are also contained inside this data range.
  1895. \see intersects
  1896. */
  1897. bool QCPDataRange::contains(const QCPDataRange &other) const
  1898. {
  1899. return mBegin <= other.mBegin && mEnd >= other.mEnd;
  1900. }
  1901. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1902. //////////////////// QCPDataSelection
  1903. ////////////////////////////////////////////////////////////////////////////////////////////////////
  1904. /*! \class QCPDataSelection
  1905. \brief Describes a data set by holding multiple QCPDataRange instances
  1906. QCPDataSelection manages multiple instances of QCPDataRange in order to represent any (possibly
  1907. disjoint) set of data selection.
  1908. The data selection can be modified with addition and subtraction operators which take
  1909. QCPDataSelection and QCPDataRange instances, as well as methods such as \ref addDataRange and
  1910. \ref clear. Read access is provided by \ref dataRange, \ref dataRanges, \ref dataRangeCount, etc.
  1911. The method \ref simplify is used to join directly adjacent or even overlapping QCPDataRange
  1912. instances. QCPDataSelection automatically simplifies when using the addition/subtraction
  1913. operators. The only case when \ref simplify is left to the user, is when calling \ref
  1914. addDataRange, with the parameter \a simplify explicitly set to false. This is useful if many data
  1915. ranges will be added to the selection successively and the overhead for simplifying after each
  1916. iteration shall be avoided. In this case, you should make sure to call \ref simplify after
  1917. completing the operation.
  1918. Use \ref enforceType to bring the data selection into a state complying with the constraints for
  1919. selections defined in \ref QCP::SelectionType.
  1920. %QCustomPlot's \ref dataselection "data selection mechanism" is based on QCPDataSelection and
  1921. QCPDataRange.
  1922. \section qcpdataselection-iterating Iterating over a data selection
  1923. As an example, the following code snippet calculates the average value of a graph's data
  1924. \ref QCPAbstractPlottable::selection "selection":
  1925. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpdataselection-iterating-1
  1926. */
  1927. /* start documentation of inline functions */
  1928. /*! \fn int QCPDataSelection::dataRangeCount() const
  1929. Returns the number of ranges that make up the data selection. The ranges can be accessed by \ref
  1930. dataRange via their index.
  1931. \see dataRange, dataPointCount
  1932. */
  1933. /*! \fn QList<QCPDataRange> QCPDataSelection::dataRanges() const
  1934. Returns all data ranges that make up the data selection. If the data selection is simplified (the
  1935. usual state of the selection, see \ref simplify), the ranges are sorted by ascending data point
  1936. index.
  1937. \see dataRange
  1938. */
  1939. /*! \fn bool QCPDataSelection::isEmpty() const
  1940. Returns true if there are no data ranges, and thus no data points, in this QCPDataSelection
  1941. instance.
  1942. \see dataRangeCount
  1943. */
  1944. /* end documentation of inline functions */
  1945. /*!
  1946. Creates an empty QCPDataSelection.
  1947. */
  1948. QCPDataSelection::QCPDataSelection()
  1949. {
  1950. }
  1951. /*!
  1952. Creates a QCPDataSelection containing the provided \a range.
  1953. */
  1954. QCPDataSelection::QCPDataSelection(const QCPDataRange &range)
  1955. {
  1956. mDataRanges.append(range);
  1957. }
  1958. /*!
  1959. Returns true if this selection is identical (contains the same data ranges with the same begin
  1960. and end indices) to \a other.
  1961. Note that both data selections must be in simplified state (the usual state of the selection, see
  1962. \ref simplify) for this operator to return correct results.
  1963. */
  1964. bool QCPDataSelection::operator==(const QCPDataSelection &other) const
  1965. {
  1966. if (mDataRanges.size() != other.mDataRanges.size())
  1967. return false;
  1968. for (int i=0; i<mDataRanges.size(); ++i)
  1969. {
  1970. if (mDataRanges.at(i) != other.mDataRanges.at(i))
  1971. return false;
  1972. }
  1973. return true;
  1974. }
  1975. /*!
  1976. Adds the data selection of \a other to this data selection, and then simplifies this data
  1977. selection (see \ref simplify).
  1978. */
  1979. QCPDataSelection &QCPDataSelection::operator+=(const QCPDataSelection &other)
  1980. {
  1981. mDataRanges << other.mDataRanges;
  1982. simplify();
  1983. return *this;
  1984. }
  1985. /*!
  1986. Adds the data range \a other to this data selection, and then simplifies this data selection (see
  1987. \ref simplify).
  1988. */
  1989. QCPDataSelection &QCPDataSelection::operator+=(const QCPDataRange &other)
  1990. {
  1991. addDataRange(other);
  1992. return *this;
  1993. }
  1994. /*!
  1995. Removes all data point indices that are described by \a other from this data selection.
  1996. */
  1997. QCPDataSelection &QCPDataSelection::operator-=(const QCPDataSelection &other)
  1998. {
  1999. for (int i=0; i<other.dataRangeCount(); ++i)
  2000. *this -= other.dataRange(i);
  2001. return *this;
  2002. }
  2003. /*!
  2004. Removes all data point indices that are described by \a other from this data selection.
  2005. */
  2006. QCPDataSelection &QCPDataSelection::operator-=(const QCPDataRange &other)
  2007. {
  2008. if (other.isEmpty() || isEmpty())
  2009. return *this;
  2010. simplify();
  2011. int i=0;
  2012. while (i < mDataRanges.size())
  2013. {
  2014. const int thisBegin = mDataRanges.at(i).begin();
  2015. const int thisEnd = mDataRanges.at(i).end();
  2016. if (thisBegin >= other.end())
  2017. break; // since data ranges are sorted after the simplify() call, no ranges which contain other will come after this
  2018. if (thisEnd > other.begin()) // ranges which don't fulfill this are entirely before other and can be ignored
  2019. {
  2020. if (thisBegin >= other.begin()) // range leading segment is encompassed
  2021. {
  2022. if (thisEnd <= other.end()) // range fully encompassed, remove completely
  2023. {
  2024. mDataRanges.removeAt(i);
  2025. continue;
  2026. } else // only leading segment is encompassed, trim accordingly
  2027. mDataRanges[i].setBegin(other.end());
  2028. } else // leading segment is not encompassed
  2029. {
  2030. if (thisEnd <= other.end()) // only trailing segment is encompassed, trim accordingly
  2031. {
  2032. mDataRanges[i].setEnd(other.begin());
  2033. } else // other lies inside this range, so split range
  2034. {
  2035. mDataRanges[i].setEnd(other.begin());
  2036. mDataRanges.insert(i+1, QCPDataRange(other.end(), thisEnd));
  2037. break; // since data ranges are sorted (and don't overlap) after simplify() call, we're done here
  2038. }
  2039. }
  2040. }
  2041. ++i;
  2042. }
  2043. return *this;
  2044. }
  2045. /*!
  2046. Returns the total number of data points contained in all data ranges that make up this data
  2047. selection.
  2048. */
  2049. int QCPDataSelection::dataPointCount() const
  2050. {
  2051. int result = 0;
  2052. foreach (QCPDataRange dataRange, mDataRanges)
  2053. result += dataRange.length();
  2054. return result;
  2055. }
  2056. /*!
  2057. Returns the data range with the specified \a index.
  2058. If the data selection is simplified (the usual state of the selection, see \ref simplify), the
  2059. ranges are sorted by ascending data point index.
  2060. \see dataRangeCount
  2061. */
  2062. QCPDataRange QCPDataSelection::dataRange(int index) const
  2063. {
  2064. if (index >= 0 && index < mDataRanges.size())
  2065. {
  2066. return mDataRanges.at(index);
  2067. } else
  2068. {
  2069. qDebug() << Q_FUNC_INFO << "index out of range:" << index;
  2070. return {};
  2071. }
  2072. }
  2073. /*!
  2074. Returns a \ref QCPDataRange which spans the entire data selection, including possible
  2075. intermediate segments which are not part of the original data selection.
  2076. */
  2077. QCPDataRange QCPDataSelection::span() const
  2078. {
  2079. if (isEmpty())
  2080. return {};
  2081. else
  2082. return {mDataRanges.first().begin(), mDataRanges.last().end()};
  2083. }
  2084. /*!
  2085. Adds the given \a dataRange to this data selection. This is equivalent to the += operator but
  2086. allows disabling immediate simplification by setting \a simplify to false. This can improve
  2087. performance if adding a very large amount of data ranges successively. In this case, make sure to
  2088. call \ref simplify manually, after the operation.
  2089. */
  2090. void QCPDataSelection::addDataRange(const QCPDataRange &dataRange, bool simplify)
  2091. {
  2092. mDataRanges.append(dataRange);
  2093. if (simplify)
  2094. this->simplify();
  2095. }
  2096. /*!
  2097. Removes all data ranges. The data selection then contains no data points.
  2098. \ref isEmpty
  2099. */
  2100. void QCPDataSelection::clear()
  2101. {
  2102. mDataRanges.clear();
  2103. }
  2104. /*!
  2105. Sorts all data ranges by range begin index in ascending order, and then joins directly adjacent
  2106. or overlapping ranges. This can reduce the number of individual data ranges in the selection, and
  2107. prevents possible double-counting when iterating over the data points held by the data ranges.
  2108. This method is automatically called when using the addition/subtraction operators. The only case
  2109. when \ref simplify is left to the user, is when calling \ref addDataRange, with the parameter \a
  2110. simplify explicitly set to false.
  2111. */
  2112. void QCPDataSelection::simplify()
  2113. {
  2114. // remove any empty ranges:
  2115. for (int i=mDataRanges.size()-1; i>=0; --i)
  2116. {
  2117. if (mDataRanges.at(i).isEmpty())
  2118. mDataRanges.removeAt(i);
  2119. }
  2120. if (mDataRanges.isEmpty())
  2121. return;
  2122. // sort ranges by starting value, ascending:
  2123. std::sort(mDataRanges.begin(), mDataRanges.end(), lessThanDataRangeBegin);
  2124. // join overlapping/contiguous ranges:
  2125. int i = 1;
  2126. while (i < mDataRanges.size())
  2127. {
  2128. if (mDataRanges.at(i-1).end() >= mDataRanges.at(i).begin()) // range i overlaps/joins with i-1, so expand range i-1 appropriately and remove range i from list
  2129. {
  2130. mDataRanges[i-1].setEnd(qMax(mDataRanges.at(i-1).end(), mDataRanges.at(i).end()));
  2131. mDataRanges.removeAt(i);
  2132. } else
  2133. ++i;
  2134. }
  2135. }
  2136. /*!
  2137. Makes sure this data selection conforms to the specified \a type selection type. Before the type
  2138. is enforced, \ref simplify is called.
  2139. Depending on \a type, enforcing means adding new data points that were previously not part of the
  2140. selection, or removing data points from the selection. If the current selection already conforms
  2141. to \a type, the data selection is not changed.
  2142. \see QCP::SelectionType
  2143. */
  2144. void QCPDataSelection::enforceType(QCP::SelectionType type)
  2145. {
  2146. simplify();
  2147. switch (type)
  2148. {
  2149. case QCP::stNone:
  2150. {
  2151. mDataRanges.clear();
  2152. break;
  2153. }
  2154. case QCP::stWhole:
  2155. {
  2156. // whole selection isn't defined by data range, so don't change anything (is handled in plottable methods)
  2157. break;
  2158. }
  2159. case QCP::stSingleData:
  2160. {
  2161. // reduce all data ranges to the single first data point:
  2162. if (!mDataRanges.isEmpty())
  2163. {
  2164. if (mDataRanges.size() > 1)
  2165. mDataRanges = QList<QCPDataRange>() << mDataRanges.first();
  2166. if (mDataRanges.first().length() > 1)
  2167. mDataRanges.first().setEnd(mDataRanges.first().begin()+1);
  2168. }
  2169. break;
  2170. }
  2171. case QCP::stDataRange:
  2172. {
  2173. if (!isEmpty())
  2174. mDataRanges = QList<QCPDataRange>() << span();
  2175. break;
  2176. }
  2177. case QCP::stMultipleDataRanges:
  2178. {
  2179. // this is the selection type that allows all concievable combinations of ranges, so do nothing
  2180. break;
  2181. }
  2182. }
  2183. }
  2184. /*!
  2185. Returns true if the data selection \a other is contained entirely in this data selection, i.e.
  2186. all data point indices that are in \a other are also in this data selection.
  2187. \see QCPDataRange::contains
  2188. */
  2189. bool QCPDataSelection::contains(const QCPDataSelection &other) const
  2190. {
  2191. if (other.isEmpty()) return false;
  2192. int otherIndex = 0;
  2193. int thisIndex = 0;
  2194. while (thisIndex < mDataRanges.size() && otherIndex < other.mDataRanges.size())
  2195. {
  2196. if (mDataRanges.at(thisIndex).contains(other.mDataRanges.at(otherIndex)))
  2197. ++otherIndex;
  2198. else
  2199. ++thisIndex;
  2200. }
  2201. return thisIndex < mDataRanges.size(); // if thisIndex ran all the way to the end to find a containing range for the current otherIndex, other is not contained in this
  2202. }
  2203. /*!
  2204. Returns a data selection containing the points which are both in this data selection and in the
  2205. data range \a other.
  2206. A common use case is to limit an unknown data selection to the valid range of a data container,
  2207. using \ref QCPDataContainer::dataRange as \a other. One can then safely iterate over the returned
  2208. data selection without exceeding the data container's bounds.
  2209. */
  2210. QCPDataSelection QCPDataSelection::intersection(const QCPDataRange &other) const
  2211. {
  2212. QCPDataSelection result;
  2213. foreach (QCPDataRange dataRange, mDataRanges)
  2214. result.addDataRange(dataRange.intersection(other), false);
  2215. result.simplify();
  2216. return result;
  2217. }
  2218. /*!
  2219. Returns a data selection containing the points which are both in this data selection and in the
  2220. data selection \a other.
  2221. */
  2222. QCPDataSelection QCPDataSelection::intersection(const QCPDataSelection &other) const
  2223. {
  2224. QCPDataSelection result;
  2225. for (int i=0; i<other.dataRangeCount(); ++i)
  2226. result += intersection(other.dataRange(i));
  2227. result.simplify();
  2228. return result;
  2229. }
  2230. /*!
  2231. Returns a data selection which is the exact inverse of this data selection, with \a outerRange
  2232. defining the base range on which to invert. If \a outerRange is smaller than the \ref span of
  2233. this data selection, it is expanded accordingly.
  2234. For example, this method can be used to retrieve all unselected segments by setting \a outerRange
  2235. to the full data range of the plottable, and calling this method on a data selection holding the
  2236. selected segments.
  2237. */
  2238. QCPDataSelection QCPDataSelection::inverse(const QCPDataRange &outerRange) const
  2239. {
  2240. if (isEmpty())
  2241. return QCPDataSelection(outerRange);
  2242. QCPDataRange fullRange = outerRange.expanded(span());
  2243. QCPDataSelection result;
  2244. // first unselected segment:
  2245. if (mDataRanges.first().begin() != fullRange.begin())
  2246. result.addDataRange(QCPDataRange(fullRange.begin(), mDataRanges.first().begin()), false);
  2247. // intermediate unselected segments:
  2248. for (int i=1; i<mDataRanges.size(); ++i)
  2249. result.addDataRange(QCPDataRange(mDataRanges.at(i-1).end(), mDataRanges.at(i).begin()), false);
  2250. // last unselected segment:
  2251. if (mDataRanges.last().end() != fullRange.end())
  2252. result.addDataRange(QCPDataRange(mDataRanges.last().end(), fullRange.end()), false);
  2253. result.simplify();
  2254. return result;
  2255. }
  2256. /* end of 'src/selection.cpp' */
  2257. /* including file 'src/selectionrect.cpp' */
  2258. /* modified 2021-03-29T02:30:44, size 9215 */
  2259. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2260. //////////////////// QCPSelectionRect
  2261. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2262. /*! \class QCPSelectionRect
  2263. \brief Provides rect/rubber-band data selection and range zoom interaction
  2264. QCPSelectionRect is used by QCustomPlot when the \ref QCustomPlot::setSelectionRectMode is not
  2265. \ref QCP::srmNone. When the user drags the mouse across the plot, the current selection rect
  2266. instance (\ref QCustomPlot::setSelectionRect) is forwarded these events and makes sure an
  2267. according rect shape is drawn. At the begin, during, and after completion of the interaction, it
  2268. Q_EMITs the corresponding signals \ref started, \ref changed, \ref canceled, and \ref accepted.
  2269. The QCustomPlot instance connects own slots to the current selection rect instance, in order to
  2270. react to an accepted selection rect interaction accordingly.
  2271. \ref isActive can be used to check whether the selection rect is currently active. An ongoing
  2272. selection interaction can be cancelled programmatically via calling \ref cancel at any time.
  2273. The appearance of the selection rect can be controlled via \ref setPen and \ref setBrush.
  2274. If you wish to provide custom behaviour, e.g. a different visual representation of the selection
  2275. rect (\ref QCPSelectionRect::draw), you can subclass QCPSelectionRect and pass an instance of
  2276. your subclass to \ref QCustomPlot::setSelectionRect.
  2277. */
  2278. /* start of documentation of inline functions */
  2279. /*! \fn bool QCPSelectionRect::isActive() const
  2280. Returns true if there is currently a selection going on, i.e. the user has started dragging a
  2281. selection rect, but hasn't released the mouse button yet.
  2282. \see cancel
  2283. */
  2284. /* end of documentation of inline functions */
  2285. /* start documentation of signals */
  2286. /*! \fn void QCPSelectionRect::started(QMouseEvent *event);
  2287. This signal is emitted when a selection rect interaction was initiated, i.e. the user just
  2288. started dragging the selection rect with the mouse.
  2289. */
  2290. /*! \fn void QCPSelectionRect::changed(const QRect &rect, QMouseEvent *event);
  2291. This signal is emitted while the selection rect interaction is ongoing and the \a rect has
  2292. changed its size due to the user moving the mouse.
  2293. Note that \a rect may have a negative width or height, if the selection is being dragged to the
  2294. upper or left side of the selection rect origin.
  2295. */
  2296. /*! \fn void QCPSelectionRect::canceled(const QRect &rect, QInputEvent *event);
  2297. This signal is emitted when the selection interaction was cancelled. Note that \a event is \c
  2298. nullptr if the selection interaction was cancelled programmatically, by a call to \ref cancel.
  2299. The user may cancel the selection interaction by pressing the escape key. In this case, \a event
  2300. holds the respective input event.
  2301. Note that \a rect may have a negative width or height, if the selection is being dragged to the
  2302. upper or left side of the selection rect origin.
  2303. */
  2304. /*! \fn void QCPSelectionRect::accepted(const QRect &rect, QMouseEvent *event);
  2305. This signal is emitted when the selection interaction was completed by the user releasing the
  2306. mouse button.
  2307. Note that \a rect may have a negative width or height, if the selection is being dragged to the
  2308. upper or left side of the selection rect origin.
  2309. */
  2310. /* end documentation of signals */
  2311. /*!
  2312. Creates a new QCPSelectionRect instance. To make QCustomPlot use the selection rect instance,
  2313. pass it to \ref QCustomPlot::setSelectionRect. \a parentPlot should be set to the same
  2314. QCustomPlot widget.
  2315. */
  2316. QCPSelectionRect::QCPSelectionRect(QCustomPlot *parentPlot) :
  2317. QCPLayerable(parentPlot),
  2318. mPen(QBrush(Qt::gray), 0, Qt::DashLine),
  2319. mBrush(Qt::NoBrush),
  2320. mActive(false)
  2321. {
  2322. }
  2323. QCPSelectionRect::~QCPSelectionRect()
  2324. {
  2325. cancel();
  2326. }
  2327. /*!
  2328. A convenience function which returns the coordinate range of the provided \a axis, that this
  2329. selection rect currently encompasses.
  2330. */
  2331. QCPRange QCPSelectionRect::range(const QCPAxis *axis) const
  2332. {
  2333. if (axis)
  2334. {
  2335. if (axis->orientation() == Qt::Horizontal)
  2336. return {axis->pixelToCoord(mRect.left()), axis->pixelToCoord(mRect.left()+mRect.width())};
  2337. else
  2338. return {axis->pixelToCoord(mRect.top()+mRect.height()), axis->pixelToCoord(mRect.top())};
  2339. } else
  2340. {
  2341. qDebug() << Q_FUNC_INFO << "called with axis zero";
  2342. return {};
  2343. }
  2344. }
  2345. /*!
  2346. Sets the pen that will be used to draw the selection rect outline.
  2347. \see setBrush
  2348. */
  2349. void QCPSelectionRect::setPen(const QPen &pen)
  2350. {
  2351. mPen = pen;
  2352. }
  2353. /*!
  2354. Sets the brush that will be used to fill the selection rect. By default the selection rect is not
  2355. filled, i.e. \a brush is <tt>Qt::NoBrush</tt>.
  2356. \see setPen
  2357. */
  2358. void QCPSelectionRect::setBrush(const QBrush &brush)
  2359. {
  2360. mBrush = brush;
  2361. }
  2362. /*!
  2363. If there is currently a selection interaction going on (\ref isActive), the interaction is
  2364. canceled. The selection rect will emit the \ref canceled signal.
  2365. */
  2366. void QCPSelectionRect::cancel()
  2367. {
  2368. if (mActive)
  2369. {
  2370. mActive = false;
  2371. Q_EMIT canceled(mRect, nullptr);
  2372. }
  2373. }
  2374. /*! \internal
  2375. This method is called by QCustomPlot to indicate that a selection rect interaction was initiated.
  2376. The default implementation sets the selection rect to active, initializes the selection rect
  2377. geometry and emits the \ref started signal.
  2378. */
  2379. void QCPSelectionRect::startSelection(QMouseEvent *event)
  2380. {
  2381. mActive = true;
  2382. mRect = QRect(event->pos(), event->pos());
  2383. Q_EMIT started(event);
  2384. }
  2385. /*! \internal
  2386. This method is called by QCustomPlot to indicate that an ongoing selection rect interaction needs
  2387. to update its geometry. The default implementation updates the rect and emits the \ref changed
  2388. signal.
  2389. */
  2390. void QCPSelectionRect::moveSelection(QMouseEvent *event)
  2391. {
  2392. mRect.setBottomRight(event->pos());
  2393. Q_EMIT changed(mRect, event);
  2394. layer()->replot();
  2395. }
  2396. /*! \internal
  2397. This method is called by QCustomPlot to indicate that an ongoing selection rect interaction has
  2398. finished by the user releasing the mouse button. The default implementation deactivates the
  2399. selection rect and emits the \ref accepted signal.
  2400. */
  2401. void QCPSelectionRect::endSelection(QMouseEvent *event)
  2402. {
  2403. mRect.setBottomRight(event->pos());
  2404. mActive = false;
  2405. Q_EMIT accepted(mRect, event);
  2406. }
  2407. /*! \internal
  2408. This method is called by QCustomPlot when a key has been pressed by the user while the selection
  2409. rect interaction is active. The default implementation allows to \ref cancel the interaction by
  2410. hitting the escape key.
  2411. */
  2412. void QCPSelectionRect::keyPressEvent(QKeyEvent *event)
  2413. {
  2414. if (event->key() == Qt::Key_Escape && mActive)
  2415. {
  2416. mActive = false;
  2417. Q_EMIT canceled(mRect, event);
  2418. }
  2419. }
  2420. /* inherits documentation from base class */
  2421. void QCPSelectionRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
  2422. {
  2423. applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
  2424. }
  2425. /*! \internal
  2426. If the selection rect is active (\ref isActive), draws the selection rect defined by \a mRect.
  2427. \seebaseclassmethod
  2428. */
  2429. void QCPSelectionRect::draw(QCPPainter *painter)
  2430. {
  2431. if (mActive)
  2432. {
  2433. painter->setPen(mPen);
  2434. painter->setBrush(mBrush);
  2435. painter->drawRect(mRect);
  2436. }
  2437. }
  2438. /* end of 'src/selectionrect.cpp' */
  2439. /* including file 'src/layout.cpp' */
  2440. /* modified 2021-03-29T02:30:44, size 78863 */
  2441. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2442. //////////////////// QCPMarginGroup
  2443. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2444. /*! \class QCPMarginGroup
  2445. \brief A margin group allows synchronization of margin sides if working with multiple layout elements.
  2446. QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that
  2447. they will all have the same size, based on the largest required margin in the group.
  2448. \n
  2449. \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup"
  2450. \n
  2451. In certain situations it is desirable that margins at specific sides are synchronized across
  2452. layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will
  2453. provide a cleaner look to the user if the left and right margins of the two axis rects are of the
  2454. same size. The left axis of the top axis rect will then be at the same horizontal position as the
  2455. left axis of the lower axis rect, making them appear aligned. The same applies for the right
  2456. axes. This is what QCPMarginGroup makes possible.
  2457. To add/remove a specific side of a layout element to/from a margin group, use the \ref
  2458. QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call
  2459. \ref clear, or just delete the margin group.
  2460. \section QCPMarginGroup-example Example
  2461. First create a margin group:
  2462. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-1
  2463. Then set this group on the layout element sides:
  2464. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpmargingroup-creation-2
  2465. Here, we've used the first two axis rects of the plot and synchronized their left margins with
  2466. each other and their right margins with each other.
  2467. */
  2468. /* start documentation of inline functions */
  2469. /*! \fn QList<QCPLayoutElement*> QCPMarginGroup::elements(QCP::MarginSide side) const
  2470. Returns a list of all layout elements that have their margin \a side associated with this margin
  2471. group.
  2472. */
  2473. /* end documentation of inline functions */
  2474. /*!
  2475. Creates a new QCPMarginGroup instance in \a parentPlot.
  2476. */
  2477. QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) :
  2478. QObject(parentPlot),
  2479. mParentPlot(parentPlot)
  2480. {
  2481. mChildren.insert(QCP::msLeft, QList<QCPLayoutElement*>());
  2482. mChildren.insert(QCP::msRight, QList<QCPLayoutElement*>());
  2483. mChildren.insert(QCP::msTop, QList<QCPLayoutElement*>());
  2484. mChildren.insert(QCP::msBottom, QList<QCPLayoutElement*>());
  2485. }
  2486. QCPMarginGroup::~QCPMarginGroup()
  2487. {
  2488. clear();
  2489. }
  2490. /*!
  2491. Returns whether this margin group is empty. If this function returns true, no layout elements use
  2492. this margin group to synchronize margin sides.
  2493. */
  2494. bool QCPMarginGroup::isEmpty() const
  2495. {
  2496. QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
  2497. while (it.hasNext())
  2498. {
  2499. it.next();
  2500. if (!it.value().isEmpty())
  2501. return false;
  2502. }
  2503. return true;
  2504. }
  2505. /*!
  2506. Clears this margin group. The synchronization of the margin sides that use this margin group is
  2507. lifted and they will use their individual margin sizes again.
  2508. */
  2509. void QCPMarginGroup::clear()
  2510. {
  2511. // make all children remove themselves from this margin group:
  2512. QHashIterator<QCP::MarginSide, QList<QCPLayoutElement*> > it(mChildren);
  2513. while (it.hasNext())
  2514. {
  2515. it.next();
  2516. const QList<QCPLayoutElement*> elements = it.value();
  2517. for (int i=elements.size()-1; i>=0; --i)
  2518. elements.at(i)->setMarginGroup(it.key(), nullptr); // removes itself from mChildren via removeChild
  2519. }
  2520. }
  2521. /*! \internal
  2522. Returns the synchronized common margin for \a side. This is the margin value that will be used by
  2523. the layout element on the respective side, if it is part of this margin group.
  2524. The common margin is calculated by requesting the automatic margin (\ref
  2525. QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin
  2526. group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into
  2527. account, too.)
  2528. */
  2529. int QCPMarginGroup::commonMargin(QCP::MarginSide side) const
  2530. {
  2531. // query all automatic margins of the layout elements in this margin group side and find maximum:
  2532. int result = 0;
  2533. foreach (QCPLayoutElement *el, mChildren.value(side))
  2534. {
  2535. if (!el->autoMargins().testFlag(side))
  2536. continue;
  2537. int m = qMax(el->calculateAutoMargin(side), QCP::getMarginValue(el->minimumMargins(), side));
  2538. if (m > result)
  2539. result = m;
  2540. }
  2541. return result;
  2542. }
  2543. /*! \internal
  2544. Adds \a element to the internal list of child elements, for the margin \a side.
  2545. This function does not modify the margin group property of \a element.
  2546. */
  2547. void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element)
  2548. {
  2549. if (!mChildren[side].contains(element))
  2550. mChildren[side].append(element);
  2551. else
  2552. qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast<quintptr>(element);
  2553. }
  2554. /*! \internal
  2555. Removes \a element from the internal list of child elements, for the margin \a side.
  2556. This function does not modify the margin group property of \a element.
  2557. */
  2558. void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element)
  2559. {
  2560. if (!mChildren[side].removeOne(element))
  2561. qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast<quintptr>(element);
  2562. }
  2563. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2564. //////////////////// QCPLayoutElement
  2565. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2566. /*! \class QCPLayoutElement
  2567. \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system".
  2568. This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses.
  2569. A Layout element is a rectangular object which can be placed in layouts. It has an outer rect
  2570. (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference
  2571. between outer and inner rect is called its margin. The margin can either be set to automatic or
  2572. manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be
  2573. set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic,
  2574. the layout element subclass will control the value itself (via \ref calculateAutoMargin).
  2575. Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level
  2576. layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref
  2577. QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested.
  2578. Thus in QCustomPlot one can divide layout elements into two categories: The ones that are
  2579. invisible by themselves, because they don't draw anything. Their only purpose is to manage the
  2580. position and size of other layout elements. This category of layout elements usually use
  2581. QCPLayout as base class. Then there is the category of layout elements which actually draw
  2582. something. For example, QCPAxisRect, QCPLegend and QCPTextElement are of this category. This does
  2583. not necessarily mean that the latter category can't have child layout elements. QCPLegend for
  2584. instance, actually derives from QCPLayoutGrid and the individual legend items are child layout
  2585. elements in the grid layout.
  2586. */
  2587. /* start documentation of inline functions */
  2588. /*! \fn QCPLayout *QCPLayoutElement::layout() const
  2589. Returns the parent layout of this layout element.
  2590. */
  2591. /*! \fn QRect QCPLayoutElement::rect() const
  2592. Returns the inner rect of this layout element. The inner rect is the outer rect (\ref outerRect, \ref
  2593. setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins).
  2594. In some cases, the area between outer and inner rect is left blank. In other cases the margin
  2595. area is used to display peripheral graphics while the main content is in the inner rect. This is
  2596. where automatic margin calculation becomes interesting because it allows the layout element to
  2597. adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect
  2598. draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if
  2599. \ref setAutoMargins is enabled) according to the space required by the labels of the axes.
  2600. \see outerRect
  2601. */
  2602. /*! \fn QRect QCPLayoutElement::outerRect() const
  2603. Returns the outer rect of this layout element. The outer rect is the inner rect expanded by the
  2604. margins (\ref setMargins, \ref setAutoMargins). The outer rect is used (and set via \ref
  2605. setOuterRect) by the parent \ref QCPLayout to control the size of this layout element.
  2606. \see rect
  2607. */
  2608. /* end documentation of inline functions */
  2609. /*!
  2610. Creates an instance of QCPLayoutElement and sets default values.
  2611. */
  2612. QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) :
  2613. QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout)
  2614. mParentLayout(nullptr),
  2615. mMinimumSize(),
  2616. mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX),
  2617. mSizeConstraintRect(scrInnerRect),
  2618. mRect(0, 0, 0, 0),
  2619. mOuterRect(0, 0, 0, 0),
  2620. mMargins(0, 0, 0, 0),
  2621. mMinimumMargins(0, 0, 0, 0),
  2622. mAutoMargins(QCP::msAll)
  2623. {
  2624. }
  2625. QCPLayoutElement::~QCPLayoutElement()
  2626. {
  2627. setMarginGroup(QCP::msAll, nullptr); // unregister at margin groups, if there are any
  2628. // unregister at layout:
  2629. if (qobject_cast<QCPLayout*>(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor
  2630. mParentLayout->take(this);
  2631. }
  2632. /*!
  2633. Sets the outer rect of this layout element. If the layout element is inside a layout, the layout
  2634. sets the position and size of this layout element using this function.
  2635. Calling this function externally has no effect, since the layout will overwrite any changes to
  2636. the outer rect upon the next replot.
  2637. The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect.
  2638. \see rect
  2639. */
  2640. void QCPLayoutElement::setOuterRect(const QRect &rect)
  2641. {
  2642. if (mOuterRect != rect)
  2643. {
  2644. mOuterRect = rect;
  2645. mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
  2646. }
  2647. }
  2648. /*!
  2649. Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all
  2650. sides, this function is used to manually set the margin on those sides. Sides that are still set
  2651. to be handled automatically are ignored and may have any value in \a margins.
  2652. The margin is the distance between the outer rect (controlled by the parent layout via \ref
  2653. setOuterRect) and the inner \ref rect (which usually contains the main content of this layout
  2654. element).
  2655. \see setAutoMargins
  2656. */
  2657. void QCPLayoutElement::setMargins(const QMargins &margins)
  2658. {
  2659. if (mMargins != margins)
  2660. {
  2661. mMargins = margins;
  2662. mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom());
  2663. }
  2664. }
  2665. /*!
  2666. If \ref setAutoMargins is enabled on some or all margins, this function is used to provide
  2667. minimum values for those margins.
  2668. The minimum values are not enforced on margin sides that were set to be under manual control via
  2669. \ref setAutoMargins.
  2670. \see setAutoMargins
  2671. */
  2672. void QCPLayoutElement::setMinimumMargins(const QMargins &margins)
  2673. {
  2674. if (mMinimumMargins != margins)
  2675. {
  2676. mMinimumMargins = margins;
  2677. }
  2678. }
  2679. /*!
  2680. Sets on which sides the margin shall be calculated automatically. If a side is calculated
  2681. automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is
  2682. set to be controlled manually, the value may be specified with \ref setMargins.
  2683. Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref
  2684. setMarginGroup), to synchronize (align) it with other layout elements in the plot.
  2685. \see setMinimumMargins, setMargins, QCP::MarginSide
  2686. */
  2687. void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides)
  2688. {
  2689. mAutoMargins = sides;
  2690. }
  2691. /*!
  2692. Sets the minimum size of this layout element. A parent layout tries to respect the \a size here
  2693. by changing row/column sizes in the layout accordingly.
  2694. If the parent layout size is not sufficient to satisfy all minimum size constraints of its child
  2695. layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot
  2696. propagates the layout's size constraints to the outside by setting its own minimum QWidget size
  2697. accordingly, so violations of \a size should be exceptions.
  2698. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2699. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2700. */
  2701. void QCPLayoutElement::setMinimumSize(const QSize &size)
  2702. {
  2703. if (mMinimumSize != size)
  2704. {
  2705. mMinimumSize = size;
  2706. if (mParentLayout)
  2707. mParentLayout->sizeConstraintsChanged();
  2708. }
  2709. }
  2710. /*! \overload
  2711. Sets the minimum size of this layout element.
  2712. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2713. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2714. */
  2715. void QCPLayoutElement::setMinimumSize(int width, int height)
  2716. {
  2717. setMinimumSize(QSize(width, height));
  2718. }
  2719. /*!
  2720. Sets the maximum size of this layout element. A parent layout tries to respect the \a size here
  2721. by changing row/column sizes in the layout accordingly.
  2722. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2723. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2724. */
  2725. void QCPLayoutElement::setMaximumSize(const QSize &size)
  2726. {
  2727. if (mMaximumSize != size)
  2728. {
  2729. mMaximumSize = size;
  2730. if (mParentLayout)
  2731. mParentLayout->sizeConstraintsChanged();
  2732. }
  2733. }
  2734. /*! \overload
  2735. Sets the maximum size of this layout element.
  2736. Whether this constraint applies to the inner or the outer rect can be specified with \ref
  2737. setSizeConstraintRect (see \ref rect and \ref outerRect).
  2738. */
  2739. void QCPLayoutElement::setMaximumSize(int width, int height)
  2740. {
  2741. setMaximumSize(QSize(width, height));
  2742. }
  2743. /*!
  2744. Sets to which rect of a layout element the size constraints apply. Size constraints can be set
  2745. via \ref setMinimumSize and \ref setMaximumSize.
  2746. The outer rect (\ref outerRect) includes the margins (e.g. in the case of a QCPAxisRect the axis
  2747. labels), whereas the inner rect (\ref rect) does not.
  2748. \see setMinimumSize, setMaximumSize
  2749. */
  2750. void QCPLayoutElement::setSizeConstraintRect(SizeConstraintRect constraintRect)
  2751. {
  2752. if (mSizeConstraintRect != constraintRect)
  2753. {
  2754. mSizeConstraintRect = constraintRect;
  2755. if (mParentLayout)
  2756. mParentLayout->sizeConstraintsChanged();
  2757. }
  2758. }
  2759. /*!
  2760. Sets the margin \a group of the specified margin \a sides.
  2761. Margin groups allow synchronizing specified margins across layout elements, see the documentation
  2762. of \ref QCPMarginGroup.
  2763. To unset the margin group of \a sides, set \a group to \c nullptr.
  2764. Note that margin groups only work for margin sides that are set to automatic (\ref
  2765. setAutoMargins).
  2766. \see QCP::MarginSide
  2767. */
  2768. void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group)
  2769. {
  2770. QVector<QCP::MarginSide> sideVector;
  2771. if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft);
  2772. if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight);
  2773. if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop);
  2774. if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom);
  2775. foreach (QCP::MarginSide side, sideVector)
  2776. {
  2777. if (marginGroup(side) != group)
  2778. {
  2779. QCPMarginGroup *oldGroup = marginGroup(side);
  2780. if (oldGroup) // unregister at old group
  2781. oldGroup->removeChild(side, this);
  2782. if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there
  2783. {
  2784. mMarginGroups.remove(side);
  2785. } else // setting to a new group
  2786. {
  2787. mMarginGroups[side] = group;
  2788. group->addChild(side, this);
  2789. }
  2790. }
  2791. }
  2792. }
  2793. /*!
  2794. Updates the layout element and sub-elements. This function is automatically called before every
  2795. replot by the parent layout element. It is called multiple times, once for every \ref
  2796. UpdatePhase. The phases are run through in the order of the enum values. For details about what
  2797. happens at the different phases, see the documentation of \ref UpdatePhase.
  2798. Layout elements that have child elements should call the \ref update method of their child
  2799. elements, and pass the current \a phase unchanged.
  2800. The default implementation executes the automatic margin mechanism in the \ref upMargins phase.
  2801. Subclasses should make sure to call the base class implementation.
  2802. */
  2803. void QCPLayoutElement::update(UpdatePhase phase)
  2804. {
  2805. if (phase == upMargins)
  2806. {
  2807. if (mAutoMargins != QCP::msNone)
  2808. {
  2809. // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group:
  2810. QMargins newMargins = mMargins;
  2811. const QList<QCP::MarginSide> allMarginSides = QList<QCP::MarginSide>() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom;
  2812. foreach (QCP::MarginSide side, allMarginSides)
  2813. {
  2814. if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically
  2815. {
  2816. if (mMarginGroups.contains(side))
  2817. QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group
  2818. else
  2819. QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly
  2820. // apply minimum margin restrictions:
  2821. if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side))
  2822. QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side));
  2823. }
  2824. }
  2825. setMargins(newMargins);
  2826. }
  2827. }
  2828. }
  2829. /*!
  2830. Returns the suggested minimum size this layout element (the \ref outerRect) may be compressed to,
  2831. if no manual minimum size is set.
  2832. if a minimum size (\ref setMinimumSize) was not set manually, parent layouts use the returned size
  2833. (usually indirectly through \ref QCPLayout::getFinalMinimumOuterSize) to determine the minimum
  2834. allowed size of this layout element.
  2835. A manual minimum size is considered set if it is non-zero.
  2836. The default implementation simply returns the sum of the horizontal margins for the width and the
  2837. sum of the vertical margins for the height. Reimplementations may use their detailed knowledge
  2838. about the layout element's content to provide size hints.
  2839. */
  2840. QSize QCPLayoutElement::minimumOuterSizeHint() const
  2841. {
  2842. return {mMargins.left()+mMargins.right(), mMargins.top()+mMargins.bottom()};
  2843. }
  2844. /*!
  2845. Returns the suggested maximum size this layout element (the \ref outerRect) may be expanded to,
  2846. if no manual maximum size is set.
  2847. if a maximum size (\ref setMaximumSize) was not set manually, parent layouts use the returned
  2848. size (usually indirectly through \ref QCPLayout::getFinalMaximumOuterSize) to determine the
  2849. maximum allowed size of this layout element.
  2850. A manual maximum size is considered set if it is smaller than Qt's \c QWIDGETSIZE_MAX.
  2851. The default implementation simply returns \c QWIDGETSIZE_MAX for both width and height, implying
  2852. no suggested maximum size. Reimplementations may use their detailed knowledge about the layout
  2853. element's content to provide size hints.
  2854. */
  2855. QSize QCPLayoutElement::maximumOuterSizeHint() const
  2856. {
  2857. return {QWIDGETSIZE_MAX, QWIDGETSIZE_MAX};
  2858. }
  2859. /*!
  2860. Returns a list of all child elements in this layout element. If \a recursive is true, all
  2861. sub-child elements are included in the list, too.
  2862. \warning There may be \c nullptr entries in the returned list. For example, QCPLayoutGrid may
  2863. have empty cells which yield \c nullptr at the respective index.
  2864. */
  2865. QList<QCPLayoutElement*> QCPLayoutElement::elements(bool recursive) const
  2866. {
  2867. Q_UNUSED(recursive)
  2868. return QList<QCPLayoutElement*>();
  2869. }
  2870. /*!
  2871. Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer
  2872. rect, this method returns a value corresponding to 0.99 times the parent plot's selection
  2873. tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is
  2874. true, -1.0 is returned.
  2875. See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
  2876. QCPLayoutElement subclasses may reimplement this method to provide more specific selection test
  2877. behaviour.
  2878. */
  2879. double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  2880. {
  2881. Q_UNUSED(details)
  2882. if (onlySelectable)
  2883. return -1;
  2884. if (QRectF(mOuterRect).contains(pos))
  2885. {
  2886. if (mParentPlot)
  2887. return mParentPlot->selectionTolerance()*0.99;
  2888. else
  2889. {
  2890. qDebug() << Q_FUNC_INFO << "parent plot not defined";
  2891. return -1;
  2892. }
  2893. } else
  2894. return -1;
  2895. }
  2896. /*! \internal
  2897. propagates the parent plot initialization to all child elements, by calling \ref
  2898. QCPLayerable::initializeParentPlot on them.
  2899. */
  2900. void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot)
  2901. {
  2902. foreach (QCPLayoutElement *el, elements(false))
  2903. {
  2904. if (!el->parentPlot())
  2905. el->initializeParentPlot(parentPlot);
  2906. }
  2907. }
  2908. /*! \internal
  2909. Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a
  2910. side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the
  2911. returned value will not be smaller than the specified minimum margin.
  2912. The default implementation just returns the respective manual margin (\ref setMargins) or the
  2913. minimum margin, whichever is larger.
  2914. */
  2915. int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side)
  2916. {
  2917. return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side));
  2918. }
  2919. /*! \internal
  2920. This virtual method is called when this layout element was moved to a different QCPLayout, or
  2921. when this layout element has changed its logical position (e.g. row and/or column) within the
  2922. same QCPLayout. Subclasses may use this to react accordingly.
  2923. Since this method is called after the completion of the move, you can access the new parent
  2924. layout via \ref layout().
  2925. The default implementation does nothing.
  2926. */
  2927. void QCPLayoutElement::layoutChanged()
  2928. {
  2929. }
  2930. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2931. //////////////////// QCPLayout
  2932. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2933. /*! \class QCPLayout
  2934. \brief The abstract base class for layouts
  2935. This is an abstract base class for layout elements whose main purpose is to define the position
  2936. and size of other child layout elements. In most cases, layouts don't draw anything themselves
  2937. (but there are exceptions to this, e.g. QCPLegend).
  2938. QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts.
  2939. QCPLayout introduces a common interface for accessing and manipulating the child elements. Those
  2940. functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref
  2941. simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions
  2942. to this interface which are more specialized to the form of the layout. For example, \ref
  2943. QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid
  2944. more conveniently.
  2945. Since this is an abstract base class, you can't instantiate it directly. Rather use one of its
  2946. subclasses like QCPLayoutGrid or QCPLayoutInset.
  2947. For a general introduction to the layout system, see the dedicated documentation page \ref
  2948. thelayoutsystem "The Layout System".
  2949. */
  2950. /* start documentation of pure virtual functions */
  2951. /*! \fn virtual int QCPLayout::elementCount() const = 0
  2952. Returns the number of elements/cells in the layout.
  2953. \see elements, elementAt
  2954. */
  2955. /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0
  2956. Returns the element in the cell with the given \a index. If \a index is invalid, returns \c
  2957. nullptr.
  2958. Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g.
  2959. QCPLayoutGrid), so this function may return \c nullptr in those cases. You may use this function
  2960. to check whether a cell is empty or not.
  2961. \see elements, elementCount, takeAt
  2962. */
  2963. /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0
  2964. Removes the element with the given \a index from the layout and returns it.
  2965. If the \a index is invalid or the cell with that index is empty, returns \c nullptr.
  2966. Note that some layouts don't remove the respective cell right away but leave an empty cell after
  2967. successful removal of the layout element. To collapse empty cells, use \ref simplify.
  2968. \see elementAt, take
  2969. */
  2970. /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0
  2971. Removes the specified \a element from the layout and returns true on success.
  2972. If the \a element isn't in this layout, returns false.
  2973. Note that some layouts don't remove the respective cell right away but leave an empty cell after
  2974. successful removal of the layout element. To collapse empty cells, use \ref simplify.
  2975. \see takeAt
  2976. */
  2977. /* end documentation of pure virtual functions */
  2978. /*!
  2979. Creates an instance of QCPLayout and sets default values. Note that since QCPLayout
  2980. is an abstract base class, it can't be instantiated directly.
  2981. */
  2982. QCPLayout::QCPLayout()
  2983. {
  2984. }
  2985. /*!
  2986. If \a phase is \ref upLayout, calls \ref updateLayout, which subclasses may reimplement to
  2987. reposition and resize their cells.
  2988. Finally, the call is propagated down to all child \ref QCPLayoutElement "QCPLayoutElements".
  2989. For details about this method and the update phases, see the documentation of \ref
  2990. QCPLayoutElement::update.
  2991. */
  2992. void QCPLayout::update(UpdatePhase phase)
  2993. {
  2994. QCPLayoutElement::update(phase);
  2995. // set child element rects according to layout:
  2996. if (phase == upLayout)
  2997. updateLayout();
  2998. // propagate update call to child elements:
  2999. const int elCount = elementCount();
  3000. for (int i=0; i<elCount; ++i)
  3001. {
  3002. if (QCPLayoutElement *el = elementAt(i))
  3003. el->update(phase);
  3004. }
  3005. }
  3006. /* inherits documentation from base class */
  3007. QList<QCPLayoutElement*> QCPLayout::elements(bool recursive) const
  3008. {
  3009. const int c = elementCount();
  3010. QList<QCPLayoutElement*> result;
  3011. #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
  3012. result.reserve(c);
  3013. #endif
  3014. for (int i=0; i<c; ++i)
  3015. result.append(elementAt(i));
  3016. if (recursive)
  3017. {
  3018. for (int i=0; i<c; ++i)
  3019. {
  3020. if (result.at(i))
  3021. result << result.at(i)->elements(recursive);
  3022. }
  3023. }
  3024. return result;
  3025. }
  3026. /*!
  3027. Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the
  3028. default implementation does nothing.
  3029. Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit
  3030. simplification while QCPLayoutGrid does.
  3031. */
  3032. void QCPLayout::simplify()
  3033. {
  3034. }
  3035. /*!
  3036. Removes and deletes the element at the provided \a index. Returns true on success. If \a index is
  3037. invalid or points to an empty cell, returns false.
  3038. This function internally uses \ref takeAt to remove the element from the layout and then deletes
  3039. the returned element. Note that some layouts don't remove the respective cell right away but leave an
  3040. empty cell after successful removal of the layout element. To collapse empty cells, use \ref
  3041. simplify.
  3042. \see remove, takeAt
  3043. */
  3044. bool QCPLayout::removeAt(int index)
  3045. {
  3046. if (QCPLayoutElement *el = takeAt(index))
  3047. {
  3048. delete el;
  3049. return true;
  3050. } else
  3051. return false;
  3052. }
  3053. /*!
  3054. Removes and deletes the provided \a element. Returns true on success. If \a element is not in the
  3055. layout, returns false.
  3056. This function internally uses \ref takeAt to remove the element from the layout and then deletes
  3057. the element. Note that some layouts don't remove the respective cell right away but leave an
  3058. empty cell after successful removal of the layout element. To collapse empty cells, use \ref
  3059. simplify.
  3060. \see removeAt, take
  3061. */
  3062. bool QCPLayout::remove(QCPLayoutElement *element)
  3063. {
  3064. if (take(element))
  3065. {
  3066. delete element;
  3067. return true;
  3068. } else
  3069. return false;
  3070. }
  3071. /*!
  3072. Removes and deletes all layout elements in this layout. Finally calls \ref simplify to make sure
  3073. all empty cells are collapsed.
  3074. \see remove, removeAt
  3075. */
  3076. void QCPLayout::clear()
  3077. {
  3078. for (int i=elementCount()-1; i>=0; --i)
  3079. {
  3080. if (elementAt(i))
  3081. removeAt(i);
  3082. }
  3083. simplify();
  3084. }
  3085. /*!
  3086. Subclasses call this method to report changed (minimum/maximum) size constraints.
  3087. If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref
  3088. sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of
  3089. QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout,
  3090. it may update itself and resize cells accordingly.
  3091. */
  3092. void QCPLayout::sizeConstraintsChanged() const
  3093. {
  3094. if (QWidget *w = qobject_cast<QWidget*>(parent()))
  3095. w->updateGeometry();
  3096. else if (QCPLayout *l = qobject_cast<QCPLayout*>(parent()))
  3097. l->sizeConstraintsChanged();
  3098. }
  3099. /*! \internal
  3100. Subclasses reimplement this method to update the position and sizes of the child elements/cells
  3101. via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing.
  3102. The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay
  3103. within that rect.
  3104. \ref getSectionSizes may help with the reimplementation of this function.
  3105. \see update
  3106. */
  3107. void QCPLayout::updateLayout()
  3108. {
  3109. }
  3110. /*! \internal
  3111. Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the
  3112. \ref QCPLayerable::parentLayerable and the QObject parent to this layout.
  3113. Further, if \a el didn't previously have a parent plot, calls \ref
  3114. QCPLayerable::initializeParentPlot on \a el to set the paret plot.
  3115. This method is used by subclass specific methods that add elements to the layout. Note that this
  3116. method only changes properties in \a el. The removal from the old layout and the insertion into
  3117. the new layout must be done additionally.
  3118. */
  3119. void QCPLayout::adoptElement(QCPLayoutElement *el)
  3120. {
  3121. if (el)
  3122. {
  3123. el->mParentLayout = this;
  3124. el->setParentLayerable(this);
  3125. el->setParent(this);
  3126. if (!el->parentPlot())
  3127. el->initializeParentPlot(mParentPlot);
  3128. el->layoutChanged();
  3129. } else
  3130. qDebug() << Q_FUNC_INFO << "Null element passed";
  3131. }
  3132. /*! \internal
  3133. Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout
  3134. and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent
  3135. QCustomPlot.
  3136. This method is used by subclass specific methods that remove elements from the layout (e.g. \ref
  3137. take or \ref takeAt). Note that this method only changes properties in \a el. The removal from
  3138. the old layout must be done additionally.
  3139. */
  3140. void QCPLayout::releaseElement(QCPLayoutElement *el)
  3141. {
  3142. if (el)
  3143. {
  3144. el->mParentLayout = nullptr;
  3145. el->setParentLayerable(nullptr);
  3146. el->setParent(mParentPlot);
  3147. // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot
  3148. } else
  3149. qDebug() << Q_FUNC_INFO << "Null element passed";
  3150. }
  3151. /*! \internal
  3152. This is a helper function for the implementation of \ref updateLayout in subclasses.
  3153. It calculates the sizes of one-dimensional sections with provided constraints on maximum section
  3154. sizes, minimum section sizes, relative stretch factors and the final total size of all sections.
  3155. The QVector entries refer to the sections. Thus all QVectors must have the same size.
  3156. \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size
  3157. imposed, set all vector values to Qt's QWIDGETSIZE_MAX.
  3158. \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size
  3159. imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than
  3160. \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words,
  3161. not exceeding the allowed total size is taken to be more important than not going below minimum
  3162. section sizes.)
  3163. \a stretchFactors give the relative proportions of the sections to each other. If all sections
  3164. shall be scaled equally, set all values equal. If the first section shall be double the size of
  3165. each individual other section, set the first number of \a stretchFactors to double the value of
  3166. the other individual values (e.g. {2, 1, 1, 1}).
  3167. \a totalSize is the value that the final section sizes will add up to. Due to rounding, the
  3168. actual sum may differ slightly. If you want the section sizes to sum up to exactly that value,
  3169. you could distribute the remaining difference on the sections.
  3170. The return value is a QVector containing the section sizes.
  3171. */
  3172. QVector<int> QCPLayout::getSectionSizes(QVector<int> maxSizes, QVector<int> minSizes, QVector<double> stretchFactors, int totalSize) const
  3173. {
  3174. if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size())
  3175. {
  3176. qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors;
  3177. return QVector<int>();
  3178. }
  3179. if (stretchFactors.isEmpty())
  3180. return QVector<int>();
  3181. int sectionCount = stretchFactors.size();
  3182. QVector<double> sectionSizes(sectionCount);
  3183. // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections):
  3184. int minSizeSum = 0;
  3185. for (int i=0; i<sectionCount; ++i)
  3186. minSizeSum += minSizes.at(i);
  3187. if (totalSize < minSizeSum)
  3188. {
  3189. // new stretch factors are minimum sizes and minimum sizes are set to zero:
  3190. for (int i=0; i<sectionCount; ++i)
  3191. {
  3192. stretchFactors[i] = minSizes.at(i);
  3193. minSizes[i] = 0;
  3194. }
  3195. }
  3196. QList<int> minimumLockedSections;
  3197. QList<int> unfinishedSections;
  3198. for (int i=0; i<sectionCount; ++i)
  3199. unfinishedSections.append(i);
  3200. double freeSize = totalSize;
  3201. int outerIterations = 0;
  3202. while (!unfinishedSections.isEmpty() && outerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
  3203. {
  3204. ++outerIterations;
  3205. int innerIterations = 0;
  3206. while (!unfinishedSections.isEmpty() && innerIterations < sectionCount*2) // the iteration check ist just a failsafe in case something really strange happens
  3207. {
  3208. ++innerIterations;
  3209. // find section that hits its maximum next:
  3210. int nextId = -1;
  3211. double nextMax = 1e12;
  3212. foreach (int secId, unfinishedSections)
  3213. {
  3214. double hitsMaxAt = (maxSizes.at(secId)-sectionSizes.at(secId))/stretchFactors.at(secId);
  3215. if (hitsMaxAt < nextMax)
  3216. {
  3217. nextMax = hitsMaxAt;
  3218. nextId = secId;
  3219. }
  3220. }
  3221. // check if that maximum is actually within the bounds of the total size (i.e. can we stretch all remaining sections so far that the found section
  3222. // actually hits its maximum, without exceeding the total size when we add up all sections)
  3223. double stretchFactorSum = 0;
  3224. foreach (int secId, unfinishedSections)
  3225. stretchFactorSum += stretchFactors.at(secId);
  3226. double nextMaxLimit = freeSize/stretchFactorSum;
  3227. if (nextMax < nextMaxLimit) // next maximum is actually hit, move forward to that point and fix the size of that section
  3228. {
  3229. foreach (int secId, unfinishedSections)
  3230. {
  3231. sectionSizes[secId] += nextMax*stretchFactors.at(secId); // increment all sections
  3232. freeSize -= nextMax*stretchFactors.at(secId);
  3233. }
  3234. unfinishedSections.removeOne(nextId); // exclude the section that is now at maximum from further changes
  3235. } else // next maximum isn't hit, just distribute rest of free space on remaining sections
  3236. {
  3237. foreach (int secId, unfinishedSections)
  3238. sectionSizes[secId] += nextMaxLimit*stretchFactors.at(secId); // increment all sections
  3239. unfinishedSections.clear();
  3240. }
  3241. }
  3242. if (innerIterations == sectionCount*2)
  3243. qDebug() << Q_FUNC_INFO << "Exceeded maximum expected inner iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
  3244. // now check whether the resulting section sizes violate minimum restrictions:
  3245. bool foundMinimumViolation = false;
  3246. for (int i=0; i<sectionSizes.size(); ++i)
  3247. {
  3248. if (minimumLockedSections.contains(i))
  3249. continue;
  3250. if (sectionSizes.at(i) < minSizes.at(i)) // section violates minimum
  3251. {
  3252. sectionSizes[i] = minSizes.at(i); // set it to minimum
  3253. foundMinimumViolation = true; // make sure we repeat the whole optimization process
  3254. minimumLockedSections.append(i);
  3255. }
  3256. }
  3257. if (foundMinimumViolation)
  3258. {
  3259. freeSize = totalSize;
  3260. for (int i=0; i<sectionCount; ++i)
  3261. {
  3262. if (!minimumLockedSections.contains(i)) // only put sections that haven't hit their minimum back into the pool
  3263. unfinishedSections.append(i);
  3264. else
  3265. freeSize -= sectionSizes.at(i); // remove size of minimum locked sections from available space in next round
  3266. }
  3267. // reset all section sizes to zero that are in unfinished sections (all others have been set to their minimum):
  3268. foreach (int secId, unfinishedSections)
  3269. sectionSizes[secId] = 0;
  3270. }
  3271. }
  3272. if (outerIterations == sectionCount*2)
  3273. qDebug() << Q_FUNC_INFO << "Exceeded maximum expected outer iteration count, layouting aborted. Input was:" << maxSizes << minSizes << stretchFactors << totalSize;
  3274. QVector<int> result(sectionCount);
  3275. for (int i=0; i<sectionCount; ++i)
  3276. result[i] = qRound(sectionSizes.at(i));
  3277. return result;
  3278. }
  3279. /*! \internal
  3280. This is a helper function for the implementation of subclasses.
  3281. It returns the minimum size that should finally be used for the outer rect of the passed layout
  3282. element \a el.
  3283. It takes into account whether a manual minimum size is set (\ref
  3284. QCPLayoutElement::setMinimumSize), which size constraint is set (\ref
  3285. QCPLayoutElement::setSizeConstraintRect), as well as the minimum size hint, if no manual minimum
  3286. size was set (\ref QCPLayoutElement::minimumOuterSizeHint).
  3287. */
  3288. QSize QCPLayout::getFinalMinimumOuterSize(const QCPLayoutElement *el)
  3289. {
  3290. QSize minOuterHint = el->minimumOuterSizeHint();
  3291. QSize minOuter = el->minimumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset minimum of 0)
  3292. if (minOuter.width() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3293. minOuter.rwidth() += el->margins().left() + el->margins().right();
  3294. if (minOuter.height() > 0 && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3295. minOuter.rheight() += el->margins().top() + el->margins().bottom();
  3296. return {minOuter.width() > 0 ? minOuter.width() : minOuterHint.width(),
  3297. minOuter.height() > 0 ? minOuter.height() : minOuterHint.height()};
  3298. }
  3299. /*! \internal
  3300. This is a helper function for the implementation of subclasses.
  3301. It returns the maximum size that should finally be used for the outer rect of the passed layout
  3302. element \a el.
  3303. It takes into account whether a manual maximum size is set (\ref
  3304. QCPLayoutElement::setMaximumSize), which size constraint is set (\ref
  3305. QCPLayoutElement::setSizeConstraintRect), as well as the maximum size hint, if no manual maximum
  3306. size was set (\ref QCPLayoutElement::maximumOuterSizeHint).
  3307. */
  3308. QSize QCPLayout::getFinalMaximumOuterSize(const QCPLayoutElement *el)
  3309. {
  3310. QSize maxOuterHint = el->maximumOuterSizeHint();
  3311. QSize maxOuter = el->maximumSize(); // depending on sizeConstraitRect this might be with respect to inner rect, so possibly add margins in next four lines (preserving unset maximum of QWIDGETSIZE_MAX)
  3312. if (maxOuter.width() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3313. maxOuter.rwidth() += el->margins().left() + el->margins().right();
  3314. if (maxOuter.height() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::scrInnerRect)
  3315. maxOuter.rheight() += el->margins().top() + el->margins().bottom();
  3316. return {maxOuter.width() < QWIDGETSIZE_MAX ? maxOuter.width() : maxOuterHint.width(),
  3317. maxOuter.height() < QWIDGETSIZE_MAX ? maxOuter.height() : maxOuterHint.height()};
  3318. }
  3319. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3320. //////////////////// QCPLayoutGrid
  3321. ////////////////////////////////////////////////////////////////////////////////////////////////////
  3322. /*! \class QCPLayoutGrid
  3323. \brief A layout that arranges child elements in a grid
  3324. Elements are laid out in a grid with configurable stretch factors (\ref setColumnStretchFactor,
  3325. \ref setRowStretchFactor) and spacing (\ref setColumnSpacing, \ref setRowSpacing).
  3326. Elements can be added to cells via \ref addElement. The grid is expanded if the specified row or
  3327. column doesn't exist yet. Whether a cell contains a valid layout element can be checked with \ref
  3328. hasElement, that element can be retrieved with \ref element. If rows and columns that only have
  3329. empty cells shall be removed, call \ref simplify. Removal of elements is either done by just
  3330. adding the element to a different layout or by using the QCPLayout interface \ref take or \ref
  3331. remove.
  3332. If you use \ref addElement(QCPLayoutElement*) without explicit parameters for \a row and \a
  3333. column, the grid layout will choose the position according to the current \ref setFillOrder and
  3334. the wrapping (\ref setWrap).
  3335. Row and column insertion can be performed with \ref insertRow and \ref insertColumn.
  3336. */
  3337. /* start documentation of inline functions */
  3338. /*! \fn int QCPLayoutGrid::rowCount() const
  3339. Returns the number of rows in the layout.
  3340. \see columnCount
  3341. */
  3342. /*! \fn int QCPLayoutGrid::columnCount() const
  3343. Returns the number of columns in the layout.
  3344. \see rowCount
  3345. */
  3346. /* end documentation of inline functions */
  3347. /*!
  3348. Creates an instance of QCPLayoutGrid and sets default values.
  3349. */
  3350. QCPLayoutGrid::QCPLayoutGrid() :
  3351. mColumnSpacing(5),
  3352. mRowSpacing(5),
  3353. mWrap(0),
  3354. mFillOrder(foColumnsFirst)
  3355. {
  3356. }
  3357. QCPLayoutGrid::~QCPLayoutGrid()
  3358. {
  3359. // clear all child layout elements. This is important because only the specific layouts know how
  3360. // to handle removing elements (clear calls virtual removeAt method to do that).
  3361. clear();
  3362. }
  3363. /*!
  3364. Returns the element in the cell in \a row and \a column.
  3365. Returns \c nullptr if either the row/column is invalid or if the cell is empty. In those cases, a
  3366. qDebug message is printed. To check whether a cell exists and isn't empty, use \ref hasElement.
  3367. \see addElement, hasElement
  3368. */
  3369. QCPLayoutElement *QCPLayoutGrid::element(int row, int column) const
  3370. {
  3371. if (row >= 0 && row < mElements.size())
  3372. {
  3373. if (column >= 0 && column < mElements.first().size())
  3374. {
  3375. if (QCPLayoutElement *result = mElements.at(row).at(column))
  3376. return result;
  3377. else
  3378. qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column;
  3379. } else
  3380. qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column;
  3381. } else
  3382. qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column;
  3383. return nullptr;
  3384. }
  3385. /*! \overload
  3386. Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it
  3387. is first removed from there. If \a row or \a column don't exist yet, the layout is expanded
  3388. accordingly.
  3389. Returns true if the element was added successfully, i.e. if the cell at \a row and \a column
  3390. didn't already have an element.
  3391. Use the overload of this method without explicit row/column index to place the element according
  3392. to the configured fill order and wrapping settings.
  3393. \see element, hasElement, take, remove
  3394. */
  3395. bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element)
  3396. {
  3397. if (!hasElement(row, column))
  3398. {
  3399. if (element && element->layout()) // remove from old layout first
  3400. element->layout()->take(element);
  3401. expandTo(row+1, column+1);
  3402. mElements[row][column] = element;
  3403. if (element)
  3404. adoptElement(element);
  3405. return true;
  3406. } else
  3407. qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column;
  3408. return false;
  3409. }
  3410. /*! \overload
  3411. Adds the \a element to the next empty cell according to the current fill order (\ref
  3412. setFillOrder) and wrapping (\ref setWrap). If \a element is already in a layout, it is first
  3413. removed from there. If necessary, the layout is expanded to hold the new element.
  3414. Returns true if the element was added successfully.
  3415. \see setFillOrder, setWrap, element, hasElement, take, remove
  3416. */
  3417. bool QCPLayoutGrid::addElement(QCPLayoutElement *element)
  3418. {
  3419. int rowIndex = 0;
  3420. int colIndex = 0;
  3421. if (mFillOrder == foColumnsFirst)
  3422. {
  3423. while (hasElement(rowIndex, colIndex))
  3424. {
  3425. ++colIndex;
  3426. if (colIndex >= mWrap && mWrap > 0)
  3427. {
  3428. colIndex = 0;
  3429. ++rowIndex;
  3430. }
  3431. }
  3432. } else
  3433. {
  3434. while (hasElement(rowIndex, colIndex))
  3435. {
  3436. ++rowIndex;
  3437. if (rowIndex >= mWrap && mWrap > 0)
  3438. {
  3439. rowIndex = 0;
  3440. ++colIndex;
  3441. }
  3442. }
  3443. }
  3444. return addElement(rowIndex, colIndex, element);
  3445. }
  3446. /*!
  3447. Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't
  3448. empty.
  3449. \see element
  3450. */
  3451. bool QCPLayoutGrid::hasElement(int row, int column)
  3452. {
  3453. if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount())
  3454. return mElements.at(row).at(column);
  3455. else
  3456. return false;
  3457. }
  3458. /*!
  3459. Sets the stretch \a factor of \a column.
  3460. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3461. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3462. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3463. QCPLayoutElement::setSizeConstraintRect.)
  3464. The default stretch factor of newly created rows/columns is 1.
  3465. \see setColumnStretchFactors, setRowStretchFactor
  3466. */
  3467. void QCPLayoutGrid::setColumnStretchFactor(int column, double factor)
  3468. {
  3469. if (column >= 0 && column < columnCount())
  3470. {
  3471. if (factor > 0)
  3472. mColumnStretchFactors[column] = factor;
  3473. else
  3474. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
  3475. } else
  3476. qDebug() << Q_FUNC_INFO << "Invalid column:" << column;
  3477. }
  3478. /*!
  3479. Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount.
  3480. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3481. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3482. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3483. QCPLayoutElement::setSizeConstraintRect.)
  3484. The default stretch factor of newly created rows/columns is 1.
  3485. \see setColumnStretchFactor, setRowStretchFactors
  3486. */
  3487. void QCPLayoutGrid::setColumnStretchFactors(const QList<double> &factors)
  3488. {
  3489. if (factors.size() == mColumnStretchFactors.size())
  3490. {
  3491. mColumnStretchFactors = factors;
  3492. for (int i=0; i<mColumnStretchFactors.size(); ++i)
  3493. {
  3494. if (mColumnStretchFactors.at(i) <= 0)
  3495. {
  3496. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mColumnStretchFactors.at(i);
  3497. mColumnStretchFactors[i] = 1;
  3498. }
  3499. }
  3500. } else
  3501. qDebug() << Q_FUNC_INFO << "Column count not equal to passed stretch factor count:" << factors;
  3502. }
  3503. /*!
  3504. Sets the stretch \a factor of \a row.
  3505. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3506. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3507. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3508. QCPLayoutElement::setSizeConstraintRect.)
  3509. The default stretch factor of newly created rows/columns is 1.
  3510. \see setColumnStretchFactors, setRowStretchFactor
  3511. */
  3512. void QCPLayoutGrid::setRowStretchFactor(int row, double factor)
  3513. {
  3514. if (row >= 0 && row < rowCount())
  3515. {
  3516. if (factor > 0)
  3517. mRowStretchFactors[row] = factor;
  3518. else
  3519. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor;
  3520. } else
  3521. qDebug() << Q_FUNC_INFO << "Invalid row:" << row;
  3522. }
  3523. /*!
  3524. Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount.
  3525. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond
  3526. their minimum and maximum widths/heights, regardless of the stretch factor. (see \ref
  3527. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize, \ref
  3528. QCPLayoutElement::setSizeConstraintRect.)
  3529. The default stretch factor of newly created rows/columns is 1.
  3530. \see setRowStretchFactor, setColumnStretchFactors
  3531. */
  3532. void QCPLayoutGrid::setRowStretchFactors(const QList<double> &factors)
  3533. {
  3534. if (factors.size() == mRowStretchFactors.size())
  3535. {
  3536. mRowStretchFactors = factors;
  3537. for (int i=0; i<mRowStretchFactors.size(); ++i)
  3538. {
  3539. if (mRowStretchFactors.at(i) <= 0)
  3540. {
  3541. qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << mRowStretchFactors.at(i);
  3542. mRowStretchFactors[i] = 1;
  3543. }
  3544. }
  3545. } else
  3546. qDebug() << Q_FUNC_INFO << "Row count not equal to passed stretch factor count:" << factors;
  3547. }
  3548. /*!
  3549. Sets the gap that is left blank between columns to \a pixels.
  3550. \see setRowSpacing
  3551. */
  3552. void QCPLayoutGrid::setColumnSpacing(int pixels)
  3553. {
  3554. mColumnSpacing = pixels;
  3555. }
  3556. /*!
  3557. Sets the gap that is left blank between rows to \a pixels.
  3558. \see setColumnSpacing
  3559. */
  3560. void QCPLayoutGrid::setRowSpacing(int pixels)
  3561. {
  3562. mRowSpacing = pixels;
  3563. }
  3564. /*!
  3565. Sets the maximum number of columns or rows that are used, before new elements added with \ref
  3566. addElement(QCPLayoutElement*) will start to fill the next row or column, respectively. It depends
  3567. on \ref setFillOrder, whether rows or columns are wrapped.
  3568. If \a count is set to zero, no wrapping will ever occur.
  3569. If you wish to re-wrap the elements currently in the layout, call \ref setFillOrder with \a
  3570. rearrange set to true (the actual fill order doesn't need to be changed for the rearranging to be
  3571. done).
  3572. Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
  3573. explicitly stated row and column is not subject to wrapping and can place elements even beyond
  3574. the specified wrapping point.
  3575. \see setFillOrder
  3576. */
  3577. void QCPLayoutGrid::setWrap(int count)
  3578. {
  3579. mWrap = qMax(0, count);
  3580. }
  3581. /*!
  3582. Sets the filling order and wrapping behaviour that is used when adding new elements with the
  3583. method \ref addElement(QCPLayoutElement*).
  3584. The specified \a order defines whether rows or columns are filled first. Using \ref setWrap, you
  3585. can control at which row/column count wrapping into the next column/row will occur. If you set it
  3586. to zero, no wrapping will ever occur. Changing the fill order also changes the meaning of the
  3587. linear index used e.g. in \ref elementAt and \ref takeAt. The default fill order for \ref
  3588. QCPLayoutGrid is \ref foColumnsFirst.
  3589. If you want to have all current elements arranged in the new order, set \a rearrange to true. The
  3590. elements will be rearranged in a way that tries to preserve their linear index. However, empty
  3591. cells are skipped during build-up of the new cell order, which shifts the succeeding element's
  3592. index. The rearranging is performed even if the specified \a order is already the current fill
  3593. order. Thus this method can be used to re-wrap the current elements.
  3594. If \a rearrange is false, the current element arrangement is not changed, which means the
  3595. linear indexes change (because the linear index is dependent on the fill order).
  3596. Note that the method \ref addElement(int row, int column, QCPLayoutElement *element) with
  3597. explicitly stated row and column is not subject to wrapping and can place elements even beyond
  3598. the specified wrapping point.
  3599. \see setWrap, addElement(QCPLayoutElement*)
  3600. */
  3601. void QCPLayoutGrid::setFillOrder(FillOrder order, bool rearrange)
  3602. {
  3603. // if rearranging, take all elements via linear index of old fill order:
  3604. const int elCount = elementCount();
  3605. QVector<QCPLayoutElement*> tempElements;
  3606. if (rearrange)
  3607. {
  3608. tempElements.reserve(elCount);
  3609. for (int i=0; i<elCount; ++i)
  3610. {
  3611. if (elementAt(i))
  3612. tempElements.append(takeAt(i));
  3613. }
  3614. simplify();
  3615. }
  3616. // change fill order as requested:
  3617. mFillOrder = order;
  3618. // if rearranging, re-insert via linear index according to new fill order:
  3619. if (rearrange)
  3620. {
  3621. foreach (QCPLayoutElement *tempElement, tempElements)
  3622. addElement(tempElement);
  3623. }
  3624. }
  3625. /*!
  3626. Expands the layout to have \a newRowCount rows and \a newColumnCount columns. So the last valid
  3627. row index will be \a newRowCount-1, the last valid column index will be \a newColumnCount-1.
  3628. If the current column/row count is already larger or equal to \a newColumnCount/\a newRowCount,
  3629. this function does nothing in that dimension.
  3630. Newly created cells are empty, new rows and columns have the stretch factor 1.
  3631. Note that upon a call to \ref addElement, the layout is expanded automatically to contain the
  3632. specified row and column, using this function.
  3633. \see simplify
  3634. */
  3635. void QCPLayoutGrid::expandTo(int newRowCount, int newColumnCount)
  3636. {
  3637. // add rows as necessary:
  3638. while (rowCount() < newRowCount)
  3639. {
  3640. mElements.append(QList<QCPLayoutElement*>());
  3641. mRowStretchFactors.append(1);
  3642. }
  3643. // go through rows and expand columns as necessary:
  3644. int newColCount = qMax(columnCount(), newColumnCount);
  3645. for (int i=0; i<rowCount(); ++i)
  3646. {
  3647. while (mElements.at(i).size() < newColCount)
  3648. mElements[i].append(nullptr);
  3649. }
  3650. while (mColumnStretchFactors.size() < newColCount)
  3651. mColumnStretchFactors.append(1);
  3652. }
  3653. /*!
  3654. Inserts a new row with empty cells at the row index \a newIndex. Valid values for \a newIndex
  3655. range from 0 (inserts a row at the top) to \a rowCount (appends a row at the bottom).
  3656. \see insertColumn
  3657. */
  3658. void QCPLayoutGrid::insertRow(int newIndex)
  3659. {
  3660. if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
  3661. {
  3662. expandTo(1, 1);
  3663. return;
  3664. }
  3665. if (newIndex < 0)
  3666. newIndex = 0;
  3667. if (newIndex > rowCount())
  3668. newIndex = rowCount();
  3669. mRowStretchFactors.insert(newIndex, 1);
  3670. QList<QCPLayoutElement*> newRow;
  3671. for (int col=0; col<columnCount(); ++col)
  3672. newRow.append(nullptr);
  3673. mElements.insert(newIndex, newRow);
  3674. }
  3675. /*!
  3676. Inserts a new column with empty cells at the column index \a newIndex. Valid values for \a
  3677. newIndex range from 0 (inserts a column at the left) to \a columnCount (appends a column at the
  3678. right).
  3679. \see insertRow
  3680. */
  3681. void QCPLayoutGrid::insertColumn(int newIndex)
  3682. {
  3683. if (mElements.isEmpty() || mElements.first().isEmpty()) // if grid is completely empty, add first cell
  3684. {
  3685. expandTo(1, 1);
  3686. return;
  3687. }
  3688. if (newIndex < 0)
  3689. newIndex = 0;
  3690. if (newIndex > columnCount())
  3691. newIndex = columnCount();
  3692. mColumnStretchFactors.insert(newIndex, 1);
  3693. for (int row=0; row<rowCount(); ++row)
  3694. mElements[row].insert(newIndex, nullptr);
  3695. }
  3696. /*!
  3697. Converts the given \a row and \a column to the linear index used by some methods of \ref
  3698. QCPLayoutGrid and \ref QCPLayout.
  3699. The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
  3700. indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
  3701. increase top to bottom and then left to right.
  3702. For the returned index to be valid, \a row and \a column must be valid indices themselves, i.e.
  3703. greater or equal to zero and smaller than the current \ref rowCount/\ref columnCount.
  3704. \see indexToRowCol
  3705. */
  3706. int QCPLayoutGrid::rowColToIndex(int row, int column) const
  3707. {
  3708. if (row >= 0 && row < rowCount())
  3709. {
  3710. if (column >= 0 && column < columnCount())
  3711. {
  3712. switch (mFillOrder)
  3713. {
  3714. case foRowsFirst: return column*rowCount() + row;
  3715. case foColumnsFirst: return row*columnCount() + column;
  3716. }
  3717. } else
  3718. qDebug() << Q_FUNC_INFO << "row index out of bounds:" << row;
  3719. } else
  3720. qDebug() << Q_FUNC_INFO << "column index out of bounds:" << column;
  3721. return 0;
  3722. }
  3723. /*!
  3724. Converts the linear index to row and column indices and writes the result to \a row and \a
  3725. column.
  3726. The way the cells are indexed depends on \ref setFillOrder. If it is \ref foRowsFirst, the
  3727. indices increase left to right and then top to bottom. If it is \ref foColumnsFirst, the indices
  3728. increase top to bottom and then left to right.
  3729. If there are no cells (i.e. column or row count is zero), sets \a row and \a column to -1.
  3730. For the retrieved \a row and \a column to be valid, the passed \a index must be valid itself,
  3731. i.e. greater or equal to zero and smaller than the current \ref elementCount.
  3732. \see rowColToIndex
  3733. */
  3734. void QCPLayoutGrid::indexToRowCol(int index, int &row, int &column) const
  3735. {
  3736. row = -1;
  3737. column = -1;
  3738. const int nCols = columnCount();
  3739. const int nRows = rowCount();
  3740. if (nCols == 0 || nRows == 0)
  3741. return;
  3742. if (index < 0 || index >= elementCount())
  3743. {
  3744. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  3745. return;
  3746. }
  3747. switch (mFillOrder)
  3748. {
  3749. case foRowsFirst:
  3750. {
  3751. column = index / nRows;
  3752. row = index % nRows;
  3753. break;
  3754. }
  3755. case foColumnsFirst:
  3756. {
  3757. row = index / nCols;
  3758. column = index % nCols;
  3759. break;
  3760. }
  3761. }
  3762. }
  3763. /* inherits documentation from base class */
  3764. void QCPLayoutGrid::updateLayout()
  3765. {
  3766. QVector<int> minColWidths, minRowHeights, maxColWidths, maxRowHeights;
  3767. getMinimumRowColSizes(&minColWidths, &minRowHeights);
  3768. getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
  3769. int totalRowSpacing = (rowCount()-1) * mRowSpacing;
  3770. int totalColSpacing = (columnCount()-1) * mColumnSpacing;
  3771. QVector<int> colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing);
  3772. QVector<int> rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing);
  3773. // go through cells and set rects accordingly:
  3774. int yOffset = mRect.top();
  3775. for (int row=0; row<rowCount(); ++row)
  3776. {
  3777. if (row > 0)
  3778. yOffset += rowHeights.at(row-1)+mRowSpacing;
  3779. int xOffset = mRect.left();
  3780. for (int col=0; col<columnCount(); ++col)
  3781. {
  3782. if (col > 0)
  3783. xOffset += colWidths.at(col-1)+mColumnSpacing;
  3784. if (mElements.at(row).at(col))
  3785. mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row)));
  3786. }
  3787. }
  3788. }
  3789. /*!
  3790. \seebaseclassmethod
  3791. Note that the association of the linear \a index to the row/column based cells depends on the
  3792. current setting of \ref setFillOrder.
  3793. \see rowColToIndex
  3794. */
  3795. QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const
  3796. {
  3797. if (index >= 0 && index < elementCount())
  3798. {
  3799. int row, col;
  3800. indexToRowCol(index, row, col);
  3801. return mElements.at(row).at(col);
  3802. } else
  3803. return nullptr;
  3804. }
  3805. /*!
  3806. \seebaseclassmethod
  3807. Note that the association of the linear \a index to the row/column based cells depends on the
  3808. current setting of \ref setFillOrder.
  3809. \see rowColToIndex
  3810. */
  3811. QCPLayoutElement *QCPLayoutGrid::takeAt(int index)
  3812. {
  3813. if (QCPLayoutElement *el = elementAt(index))
  3814. {
  3815. releaseElement(el);
  3816. int row, col;
  3817. indexToRowCol(index, row, col);
  3818. mElements[row][col] = nullptr;
  3819. return el;
  3820. } else
  3821. {
  3822. qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
  3823. return nullptr;
  3824. }
  3825. }
  3826. /* inherits documentation from base class */
  3827. bool QCPLayoutGrid::take(QCPLayoutElement *element)
  3828. {
  3829. if (element)
  3830. {
  3831. for (int i=0; i<elementCount(); ++i)
  3832. {
  3833. if (elementAt(i) == element)
  3834. {
  3835. takeAt(i);
  3836. return true;
  3837. }
  3838. }
  3839. qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
  3840. } else
  3841. qDebug() << Q_FUNC_INFO << "Can't take nullptr element";
  3842. return false;
  3843. }
  3844. /* inherits documentation from base class */
  3845. QList<QCPLayoutElement*> QCPLayoutGrid::elements(bool recursive) const
  3846. {
  3847. QList<QCPLayoutElement*> result;
  3848. const int elCount = elementCount();
  3849. #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0)
  3850. result.reserve(elCount);
  3851. #endif
  3852. for (int i=0; i<elCount; ++i)
  3853. result.append(elementAt(i));
  3854. if (recursive)
  3855. {
  3856. for (int i=0; i<elCount; ++i)
  3857. {
  3858. if (result.at(i))
  3859. result << result.at(i)->elements(recursive);
  3860. }
  3861. }
  3862. return result;
  3863. }
  3864. /*!
  3865. Simplifies the layout by collapsing rows and columns which only contain empty cells.
  3866. */
  3867. void QCPLayoutGrid::simplify()
  3868. {
  3869. // remove rows with only empty cells:
  3870. for (int row=rowCount()-1; row>=0; --row)
  3871. {
  3872. bool hasElements = false;
  3873. for (int col=0; col<columnCount(); ++col)
  3874. {
  3875. if (mElements.at(row).at(col))
  3876. {
  3877. hasElements = true;
  3878. break;
  3879. }
  3880. }
  3881. if (!hasElements)
  3882. {
  3883. mRowStretchFactors.removeAt(row);
  3884. mElements.removeAt(row);
  3885. if (mElements.isEmpty()) // removed last element, also remove stretch factor (wouldn't happen below because also columnCount changed to 0 now)
  3886. mColumnStretchFactors.clear();
  3887. }
  3888. }
  3889. // remove columns with only empty cells:
  3890. for (int col=columnCount()-1; col>=0; --col)
  3891. {
  3892. bool hasElements = false;
  3893. for (int row=0; row<rowCount(); ++row)
  3894. {
  3895. if (mElements.at(row).at(col))
  3896. {
  3897. hasElements = true;
  3898. break;
  3899. }
  3900. }
  3901. if (!hasElements)
  3902. {
  3903. mColumnStretchFactors.removeAt(col);
  3904. for (int row=0; row<rowCount(); ++row)
  3905. mElements[row].removeAt(col);
  3906. }
  3907. }
  3908. }
  3909. /* inherits documentation from base class */
  3910. QSize QCPLayoutGrid::minimumOuterSizeHint() const
  3911. {
  3912. QVector<int> minColWidths, minRowHeights;
  3913. getMinimumRowColSizes(&minColWidths, &minRowHeights);
  3914. QSize result(0, 0);
  3915. foreach (int w, minColWidths)
  3916. result.rwidth() += w;
  3917. foreach (int h, minRowHeights)
  3918. result.rheight() += h;
  3919. result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing;
  3920. result.rheight() += qMax(0, rowCount()-1) * mRowSpacing;
  3921. result.rwidth() += mMargins.left()+mMargins.right();
  3922. result.rheight() += mMargins.top()+mMargins.bottom();
  3923. return result;
  3924. }
  3925. /* inherits documentation from base class */
  3926. QSize QCPLayoutGrid::maximumOuterSizeHint() const
  3927. {
  3928. QVector<int> maxColWidths, maxRowHeights;
  3929. getMaximumRowColSizes(&maxColWidths, &maxRowHeights);
  3930. QSize result(0, 0);
  3931. foreach (int w, maxColWidths)
  3932. result.setWidth(qMin(result.width()+w, QWIDGETSIZE_MAX));
  3933. foreach (int h, maxRowHeights)
  3934. result.setHeight(qMin(result.height()+h, QWIDGETSIZE_MAX));
  3935. result.rwidth() += qMax(0, columnCount()-1) * mColumnSpacing;
  3936. result.rheight() += qMax(0, rowCount()-1) * mRowSpacing;
  3937. result.rwidth() += mMargins.left()+mMargins.right();
  3938. result.rheight() += mMargins.top()+mMargins.bottom();
  3939. if (result.height() > QWIDGETSIZE_MAX)
  3940. result.setHeight(QWIDGETSIZE_MAX);
  3941. if (result.width() > QWIDGETSIZE_MAX)
  3942. result.setWidth(QWIDGETSIZE_MAX);
  3943. return result;
  3944. }
  3945. /*! \internal
  3946. Places the minimum column widths and row heights into \a minColWidths and \a minRowHeights
  3947. respectively.
  3948. The minimum height of a row is the largest minimum height of any element's outer rect in that
  3949. row. The minimum width of a column is the largest minimum width of any element's outer rect in
  3950. that column.
  3951. This is a helper function for \ref updateLayout.
  3952. \see getMaximumRowColSizes
  3953. */
  3954. void QCPLayoutGrid::getMinimumRowColSizes(QVector<int> *minColWidths, QVector<int> *minRowHeights) const
  3955. {
  3956. *minColWidths = QVector<int>(columnCount(), 0);
  3957. *minRowHeights = QVector<int>(rowCount(), 0);
  3958. for (int row=0; row<rowCount(); ++row)
  3959. {
  3960. for (int col=0; col<columnCount(); ++col)
  3961. {
  3962. if (QCPLayoutElement *el = mElements.at(row).at(col))
  3963. {
  3964. QSize minSize = getFinalMinimumOuterSize(el);
  3965. if (minColWidths->at(col) < minSize.width())
  3966. (*minColWidths)[col] = minSize.width();
  3967. if (minRowHeights->at(row) < minSize.height())
  3968. (*minRowHeights)[row] = minSize.height();
  3969. }
  3970. }
  3971. }
  3972. }
  3973. /*! \internal
  3974. Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights
  3975. respectively.
  3976. The maximum height of a row is the smallest maximum height of any element's outer rect in that
  3977. row. The maximum width of a column is the smallest maximum width of any element's outer rect in
  3978. that column.
  3979. This is a helper function for \ref updateLayout.
  3980. \see getMinimumRowColSizes
  3981. */
  3982. void QCPLayoutGrid::getMaximumRowColSizes(QVector<int> *maxColWidths, QVector<int> *maxRowHeights) const
  3983. {
  3984. *maxColWidths = QVector<int>(columnCount(), QWIDGETSIZE_MAX);
  3985. *maxRowHeights = QVector<int>(rowCount(), QWIDGETSIZE_MAX);
  3986. for (int row=0; row<rowCount(); ++row)
  3987. {
  3988. for (int col=0; col<columnCount(); ++col)
  3989. {
  3990. if (QCPLayoutElement *el = mElements.at(row).at(col))
  3991. {
  3992. QSize maxSize = getFinalMaximumOuterSize(el);
  3993. if (maxColWidths->at(col) > maxSize.width())
  3994. (*maxColWidths)[col] = maxSize.width();
  3995. if (maxRowHeights->at(row) > maxSize.height())
  3996. (*maxRowHeights)[row] = maxSize.height();
  3997. }
  3998. }
  3999. }
  4000. }
  4001. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4002. //////////////////// QCPLayoutInset
  4003. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4004. /*! \class QCPLayoutInset
  4005. \brief A layout that places child elements aligned to the border or arbitrarily positioned
  4006. Elements are placed either aligned to the border or at arbitrary position in the area of the
  4007. layout. Which placement applies is controlled with the \ref InsetPlacement (\ref
  4008. setInsetPlacement).
  4009. Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or
  4010. addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset
  4011. placement will default to \ref ipBorderAligned and the element will be aligned according to the
  4012. \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at
  4013. arbitrary position and size, defined by \a rect.
  4014. The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively.
  4015. This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout.
  4016. */
  4017. /* start documentation of inline functions */
  4018. /*! \fn virtual void QCPLayoutInset::simplify()
  4019. The QCPInsetLayout does not need simplification since it can never have empty cells due to its
  4020. linear index structure. This method does nothing.
  4021. */
  4022. /* end documentation of inline functions */
  4023. /*!
  4024. Creates an instance of QCPLayoutInset and sets default values.
  4025. */
  4026. QCPLayoutInset::QCPLayoutInset()
  4027. {
  4028. }
  4029. QCPLayoutInset::~QCPLayoutInset()
  4030. {
  4031. // clear all child layout elements. This is important because only the specific layouts know how
  4032. // to handle removing elements (clear calls virtual removeAt method to do that).
  4033. clear();
  4034. }
  4035. /*!
  4036. Returns the placement type of the element with the specified \a index.
  4037. */
  4038. QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const
  4039. {
  4040. if (elementAt(index))
  4041. return mInsetPlacement.at(index);
  4042. else
  4043. {
  4044. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4045. return ipFree;
  4046. }
  4047. }
  4048. /*!
  4049. Returns the alignment of the element with the specified \a index. The alignment only has a
  4050. meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned.
  4051. */
  4052. Qt::Alignment QCPLayoutInset::insetAlignment(int index) const
  4053. {
  4054. if (elementAt(index))
  4055. return mInsetAlignment.at(index);
  4056. else
  4057. {
  4058. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4059. #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
  4060. return nullptr;
  4061. #else
  4062. return {};
  4063. #endif
  4064. }
  4065. }
  4066. /*!
  4067. Returns the rect of the element with the specified \a index. The rect only has a
  4068. meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree.
  4069. */
  4070. QRectF QCPLayoutInset::insetRect(int index) const
  4071. {
  4072. if (elementAt(index))
  4073. return mInsetRect.at(index);
  4074. else
  4075. {
  4076. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4077. return {};
  4078. }
  4079. }
  4080. /*!
  4081. Sets the inset placement type of the element with the specified \a index to \a placement.
  4082. \see InsetPlacement
  4083. */
  4084. void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement)
  4085. {
  4086. if (elementAt(index))
  4087. mInsetPlacement[index] = placement;
  4088. else
  4089. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4090. }
  4091. /*!
  4092. If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function
  4093. is used to set the alignment of the element with the specified \a index to \a alignment.
  4094. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
  4095. Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
  4096. alignment flags will be ignored.
  4097. */
  4098. void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment)
  4099. {
  4100. if (elementAt(index))
  4101. mInsetAlignment[index] = alignment;
  4102. else
  4103. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4104. }
  4105. /*!
  4106. If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the
  4107. position and size of the element with the specified \a index to \a rect.
  4108. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
  4109. will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
  4110. corner of the layout, with 35% width and height of the parent layout.
  4111. Note that the minimum and maximum sizes of the embedded element (\ref
  4112. QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced.
  4113. */
  4114. void QCPLayoutInset::setInsetRect(int index, const QRectF &rect)
  4115. {
  4116. if (elementAt(index))
  4117. mInsetRect[index] = rect;
  4118. else
  4119. qDebug() << Q_FUNC_INFO << "Invalid element index:" << index;
  4120. }
  4121. /* inherits documentation from base class */
  4122. void QCPLayoutInset::updateLayout()
  4123. {
  4124. for (int i=0; i<mElements.size(); ++i)
  4125. {
  4126. QCPLayoutElement *el = mElements.at(i);
  4127. QRect insetRect;
  4128. QSize finalMinSize = getFinalMinimumOuterSize(el);
  4129. QSize finalMaxSize = getFinalMaximumOuterSize(el);
  4130. if (mInsetPlacement.at(i) == ipFree)
  4131. {
  4132. insetRect = QRect(int( rect().x()+rect().width()*mInsetRect.at(i).x() ),
  4133. int( rect().y()+rect().height()*mInsetRect.at(i).y() ),
  4134. int( rect().width()*mInsetRect.at(i).width() ),
  4135. int( rect().height()*mInsetRect.at(i).height() ));
  4136. if (insetRect.size().width() < finalMinSize.width())
  4137. insetRect.setWidth(finalMinSize.width());
  4138. if (insetRect.size().height() < finalMinSize.height())
  4139. insetRect.setHeight(finalMinSize.height());
  4140. if (insetRect.size().width() > finalMaxSize.width())
  4141. insetRect.setWidth(finalMaxSize.width());
  4142. if (insetRect.size().height() > finalMaxSize.height())
  4143. insetRect.setHeight(finalMaxSize.height());
  4144. } else if (mInsetPlacement.at(i) == ipBorderAligned)
  4145. {
  4146. insetRect.setSize(finalMinSize);
  4147. Qt::Alignment al = mInsetAlignment.at(i);
  4148. if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x());
  4149. else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width());
  4150. else insetRect.moveLeft(int( rect().x()+rect().width()*0.5-finalMinSize.width()*0.5 )); // default to Qt::AlignHCenter
  4151. if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y());
  4152. else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height());
  4153. else insetRect.moveTop(int( rect().y()+rect().height()*0.5-finalMinSize.height()*0.5 )); // default to Qt::AlignVCenter
  4154. }
  4155. mElements.at(i)->setOuterRect(insetRect);
  4156. }
  4157. }
  4158. /* inherits documentation from base class */
  4159. int QCPLayoutInset::elementCount() const
  4160. {
  4161. return mElements.size();
  4162. }
  4163. /* inherits documentation from base class */
  4164. QCPLayoutElement *QCPLayoutInset::elementAt(int index) const
  4165. {
  4166. if (index >= 0 && index < mElements.size())
  4167. return mElements.at(index);
  4168. else
  4169. return nullptr;
  4170. }
  4171. /* inherits documentation from base class */
  4172. QCPLayoutElement *QCPLayoutInset::takeAt(int index)
  4173. {
  4174. if (QCPLayoutElement *el = elementAt(index))
  4175. {
  4176. releaseElement(el);
  4177. mElements.removeAt(index);
  4178. mInsetPlacement.removeAt(index);
  4179. mInsetAlignment.removeAt(index);
  4180. mInsetRect.removeAt(index);
  4181. return el;
  4182. } else
  4183. {
  4184. qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index;
  4185. return nullptr;
  4186. }
  4187. }
  4188. /* inherits documentation from base class */
  4189. bool QCPLayoutInset::take(QCPLayoutElement *element)
  4190. {
  4191. if (element)
  4192. {
  4193. for (int i=0; i<elementCount(); ++i)
  4194. {
  4195. if (elementAt(i) == element)
  4196. {
  4197. takeAt(i);
  4198. return true;
  4199. }
  4200. }
  4201. qDebug() << Q_FUNC_INFO << "Element not in this layout, couldn't take";
  4202. } else
  4203. qDebug() << Q_FUNC_INFO << "Can't take nullptr element";
  4204. return false;
  4205. }
  4206. /*!
  4207. The inset layout is sensitive to events only at areas where its (visible) child elements are
  4208. sensitive. If the selectTest method of any of the child elements returns a positive number for \a
  4209. pos, this method returns a value corresponding to 0.99 times the parent plot's selection
  4210. tolerance. The inset layout is not selectable itself by default. So if \a onlySelectable is true,
  4211. -1.0 is returned.
  4212. See \ref QCPLayerable::selectTest for a general explanation of this virtual method.
  4213. */
  4214. double QCPLayoutInset::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  4215. {
  4216. Q_UNUSED(details)
  4217. if (onlySelectable)
  4218. return -1;
  4219. foreach (QCPLayoutElement *el, mElements)
  4220. {
  4221. // inset layout shall only return positive selectTest, if actually an inset object is at pos
  4222. // else it would block the entire underlying QCPAxisRect with its surface.
  4223. if (el->realVisibility() && el->selectTest(pos, onlySelectable) >= 0)
  4224. return mParentPlot->selectionTolerance()*0.99;
  4225. }
  4226. return -1;
  4227. }
  4228. /*!
  4229. Adds the specified \a element to the layout as an inset aligned at the border (\ref
  4230. setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a
  4231. alignment.
  4232. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft,
  4233. Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other
  4234. alignment flags will be ignored.
  4235. \see addElement(QCPLayoutElement *element, const QRectF &rect)
  4236. */
  4237. void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment)
  4238. {
  4239. if (element)
  4240. {
  4241. if (element->layout()) // remove from old layout first
  4242. element->layout()->take(element);
  4243. mElements.append(element);
  4244. mInsetPlacement.append(ipBorderAligned);
  4245. mInsetAlignment.append(alignment);
  4246. mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4));
  4247. adoptElement(element);
  4248. } else
  4249. qDebug() << Q_FUNC_INFO << "Can't add nullptr element";
  4250. }
  4251. /*!
  4252. Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref
  4253. setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a
  4254. rect.
  4255. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1)
  4256. will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right
  4257. corner of the layout, with 35% width and height of the parent layout.
  4258. \see addElement(QCPLayoutElement *element, Qt::Alignment alignment)
  4259. */
  4260. void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect)
  4261. {
  4262. if (element)
  4263. {
  4264. if (element->layout()) // remove from old layout first
  4265. element->layout()->take(element);
  4266. mElements.append(element);
  4267. mInsetPlacement.append(ipFree);
  4268. mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop);
  4269. mInsetRect.append(rect);
  4270. adoptElement(element);
  4271. } else
  4272. qDebug() << Q_FUNC_INFO << "Can't add nullptr element";
  4273. }
  4274. /* end of 'src/layout.cpp' */
  4275. /* including file 'src/lineending.cpp' */
  4276. /* modified 2021-03-29T02:30:44, size 11189 */
  4277. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4278. //////////////////// QCPLineEnding
  4279. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4280. /*! \class QCPLineEnding
  4281. \brief Handles the different ending decorations for line-like items
  4282. \image html QCPLineEnding.png "The various ending styles currently supported"
  4283. For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine
  4284. has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail.
  4285. The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can
  4286. be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of
  4287. the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item.
  4288. For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite
  4289. directions, e.g. "outward". This can be changed by \ref setInverted, which would make the
  4290. respective arrow point inward.
  4291. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a
  4292. QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g.
  4293. \snippet documentation/doc-code-snippets/mainwindow.cpp qcplineending-sethead
  4294. */
  4295. /*!
  4296. Creates a QCPLineEnding instance with default values (style \ref esNone).
  4297. */
  4298. QCPLineEnding::QCPLineEnding() :
  4299. mStyle(esNone),
  4300. mWidth(8),
  4301. mLength(10),
  4302. mInverted(false)
  4303. {
  4304. }
  4305. /*!
  4306. Creates a QCPLineEnding instance with the specified values.
  4307. */
  4308. QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) :
  4309. mStyle(style),
  4310. mWidth(width),
  4311. mLength(length),
  4312. mInverted(inverted)
  4313. {
  4314. }
  4315. /*!
  4316. Sets the style of the ending decoration.
  4317. */
  4318. void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style)
  4319. {
  4320. mStyle = style;
  4321. }
  4322. /*!
  4323. Sets the width of the ending decoration, if the style supports it. On arrows, for example, the
  4324. width defines the size perpendicular to the arrow's pointing direction.
  4325. \see setLength
  4326. */
  4327. void QCPLineEnding::setWidth(double width)
  4328. {
  4329. mWidth = width;
  4330. }
  4331. /*!
  4332. Sets the length of the ending decoration, if the style supports it. On arrows, for example, the
  4333. length defines the size in pointing direction.
  4334. \see setWidth
  4335. */
  4336. void QCPLineEnding::setLength(double length)
  4337. {
  4338. mLength = length;
  4339. }
  4340. /*!
  4341. Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point
  4342. inward when \a inverted is set to true.
  4343. Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or
  4344. discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are
  4345. affected by it, which can be used to control to which side the half bar points to.
  4346. */
  4347. void QCPLineEnding::setInverted(bool inverted)
  4348. {
  4349. mInverted = inverted;
  4350. }
  4351. /*! \internal
  4352. Returns the maximum pixel radius the ending decoration might cover, starting from the position
  4353. the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item).
  4354. This is relevant for clipping. Only omit painting of the decoration when the position where the
  4355. decoration is supposed to be drawn is farther away from the clipping rect than the returned
  4356. distance.
  4357. */
  4358. double QCPLineEnding::boundingDistance() const
  4359. {
  4360. switch (mStyle)
  4361. {
  4362. case esNone:
  4363. return 0;
  4364. case esFlatArrow:
  4365. case esSpikeArrow:
  4366. case esLineArrow:
  4367. case esSkewedBar:
  4368. return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length
  4369. case esDisc:
  4370. case esSquare:
  4371. case esDiamond:
  4372. case esBar:
  4373. case esHalfBar:
  4374. return mWidth*1.42; // items that only have a width -> width*sqrt(2)
  4375. }
  4376. return 0;
  4377. }
  4378. /*!
  4379. Starting from the origin of this line ending (which is style specific), returns the length
  4380. covered by the line ending symbol, in backward direction.
  4381. For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if
  4382. both have the same \ref setLength value, because the spike arrow has an inward curved back, which
  4383. reduces the length along its center axis (the drawing origin for arrows is at the tip).
  4384. This function is used for precise, style specific placement of line endings, for example in
  4385. QCPAxes.
  4386. */
  4387. double QCPLineEnding::realLength() const
  4388. {
  4389. switch (mStyle)
  4390. {
  4391. case esNone:
  4392. case esLineArrow:
  4393. case esSkewedBar:
  4394. case esBar:
  4395. case esHalfBar:
  4396. return 0;
  4397. case esFlatArrow:
  4398. return mLength;
  4399. case esDisc:
  4400. case esSquare:
  4401. case esDiamond:
  4402. return mWidth*0.5;
  4403. case esSpikeArrow:
  4404. return mLength*0.8;
  4405. }
  4406. return 0;
  4407. }
  4408. /*! \internal
  4409. Draws the line ending with the specified \a painter at the position \a pos. The direction of the
  4410. line ending is controlled with \a dir.
  4411. */
  4412. void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, const QCPVector2D &dir) const
  4413. {
  4414. if (mStyle == esNone)
  4415. return;
  4416. QCPVector2D lengthVec = dir.normalized() * mLength*(mInverted ? -1 : 1);
  4417. if (lengthVec.isNull())
  4418. lengthVec = QCPVector2D(1, 0);
  4419. QCPVector2D widthVec = dir.normalized().perpendicular() * mWidth*0.5*(mInverted ? -1 : 1);
  4420. QPen penBackup = painter->pen();
  4421. QBrush brushBackup = painter->brush();
  4422. QPen miterPen = penBackup;
  4423. miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey
  4424. QBrush brush(painter->pen().color(), Qt::SolidPattern);
  4425. switch (mStyle)
  4426. {
  4427. case esNone: break;
  4428. case esFlatArrow:
  4429. {
  4430. QPointF points[3] = {pos.toPointF(),
  4431. (pos-lengthVec+widthVec).toPointF(),
  4432. (pos-lengthVec-widthVec).toPointF()
  4433. };
  4434. painter->setPen(miterPen);
  4435. painter->setBrush(brush);
  4436. painter->drawConvexPolygon(points, 3);
  4437. painter->setBrush(brushBackup);
  4438. painter->setPen(penBackup);
  4439. break;
  4440. }
  4441. case esSpikeArrow:
  4442. {
  4443. QPointF points[4] = {pos.toPointF(),
  4444. (pos-lengthVec+widthVec).toPointF(),
  4445. (pos-lengthVec*0.8).toPointF(),
  4446. (pos-lengthVec-widthVec).toPointF()
  4447. };
  4448. painter->setPen(miterPen);
  4449. painter->setBrush(brush);
  4450. painter->drawConvexPolygon(points, 4);
  4451. painter->setBrush(brushBackup);
  4452. painter->setPen(penBackup);
  4453. break;
  4454. }
  4455. case esLineArrow:
  4456. {
  4457. QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(),
  4458. pos.toPointF(),
  4459. (pos-lengthVec-widthVec).toPointF()
  4460. };
  4461. painter->setPen(miterPen);
  4462. painter->drawPolyline(points, 3);
  4463. painter->setPen(penBackup);
  4464. break;
  4465. }
  4466. case esDisc:
  4467. {
  4468. painter->setBrush(brush);
  4469. painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5);
  4470. painter->setBrush(brushBackup);
  4471. break;
  4472. }
  4473. case esSquare:
  4474. {
  4475. QCPVector2D widthVecPerp = widthVec.perpendicular();
  4476. QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(),
  4477. (pos-widthVecPerp-widthVec).toPointF(),
  4478. (pos+widthVecPerp-widthVec).toPointF(),
  4479. (pos+widthVecPerp+widthVec).toPointF()
  4480. };
  4481. painter->setPen(miterPen);
  4482. painter->setBrush(brush);
  4483. painter->drawConvexPolygon(points, 4);
  4484. painter->setBrush(brushBackup);
  4485. painter->setPen(penBackup);
  4486. break;
  4487. }
  4488. case esDiamond:
  4489. {
  4490. QCPVector2D widthVecPerp = widthVec.perpendicular();
  4491. QPointF points[4] = {(pos-widthVecPerp).toPointF(),
  4492. (pos-widthVec).toPointF(),
  4493. (pos+widthVecPerp).toPointF(),
  4494. (pos+widthVec).toPointF()
  4495. };
  4496. painter->setPen(miterPen);
  4497. painter->setBrush(brush);
  4498. painter->drawConvexPolygon(points, 4);
  4499. painter->setBrush(brushBackup);
  4500. painter->setPen(penBackup);
  4501. break;
  4502. }
  4503. case esBar:
  4504. {
  4505. painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF());
  4506. break;
  4507. }
  4508. case esHalfBar:
  4509. {
  4510. painter->drawLine((pos+widthVec).toPointF(), pos.toPointF());
  4511. break;
  4512. }
  4513. case esSkewedBar:
  4514. {
  4515. QCPVector2D shift;
  4516. if (!qFuzzyIsNull(painter->pen().widthF()) || painter->modes().testFlag(QCPPainter::pmNonCosmetic))
  4517. shift = dir.normalized()*qMax(qreal(1.0), painter->pen().widthF())*qreal(0.5);
  4518. // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly
  4519. painter->drawLine((pos+widthVec+lengthVec*0.2*(mInverted?-1:1)+shift).toPointF(),
  4520. (pos-widthVec-lengthVec*0.2*(mInverted?-1:1)+shift).toPointF());
  4521. break;
  4522. }
  4523. }
  4524. }
  4525. /*! \internal
  4526. \overload
  4527. Draws the line ending. The direction is controlled with the \a angle parameter in radians.
  4528. */
  4529. void QCPLineEnding::draw(QCPPainter *painter, const QCPVector2D &pos, double angle) const
  4530. {
  4531. draw(painter, pos, QCPVector2D(qCos(angle), qSin(angle)));
  4532. }
  4533. /* end of 'src/lineending.cpp' */
  4534. /* including file 'src/axis/labelpainter.cpp' */
  4535. /* modified 2021-03-29T02:30:44, size 27296 */
  4536. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4537. //////////////////// QCPLabelPainterPrivate
  4538. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4539. /*! \class QCPLabelPainterPrivate
  4540. \internal
  4541. \brief (Private)
  4542. This is a private class and not part of the public QCustomPlot interface.
  4543. */
  4544. const QChar QCPLabelPainterPrivate::SymbolDot(183);
  4545. const QChar QCPLabelPainterPrivate::SymbolCross(215);
  4546. /*!
  4547. Constructs a QCPLabelPainterPrivate instance. Make sure to not create a new
  4548. instance on every redraw, to utilize the caching mechanisms.
  4549. the \a parentPlot does not take ownership of the label painter. Make sure
  4550. to delete it appropriately.
  4551. */
  4552. QCPLabelPainterPrivate::QCPLabelPainterPrivate(QCustomPlot *parentPlot) :
  4553. mAnchorMode(amRectangular),
  4554. mAnchorSide(asLeft),
  4555. mAnchorReferenceType(artNormal),
  4556. mColor(Qt::black),
  4557. mPadding(0),
  4558. mRotation(0),
  4559. mSubstituteExponent(true),
  4560. mMultiplicationSymbol(QChar(215)),
  4561. mAbbreviateDecimalPowers(false),
  4562. mParentPlot(parentPlot),
  4563. mLabelCache(16)
  4564. {
  4565. analyzeFontMetrics();
  4566. }
  4567. QCPLabelPainterPrivate::~QCPLabelPainterPrivate()
  4568. {
  4569. }
  4570. void QCPLabelPainterPrivate::setAnchorSide(AnchorSide side)
  4571. {
  4572. mAnchorSide = side;
  4573. }
  4574. void QCPLabelPainterPrivate::setAnchorMode(AnchorMode mode)
  4575. {
  4576. mAnchorMode = mode;
  4577. }
  4578. void QCPLabelPainterPrivate::setAnchorReference(const QPointF &pixelPoint)
  4579. {
  4580. mAnchorReference = pixelPoint;
  4581. }
  4582. void QCPLabelPainterPrivate::setAnchorReferenceType(AnchorReferenceType type)
  4583. {
  4584. mAnchorReferenceType = type;
  4585. }
  4586. void QCPLabelPainterPrivate::setFont(const QFont &font)
  4587. {
  4588. if (mFont != font)
  4589. {
  4590. mFont = font;
  4591. analyzeFontMetrics();
  4592. }
  4593. }
  4594. void QCPLabelPainterPrivate::setColor(const QColor &color)
  4595. {
  4596. mColor = color;
  4597. }
  4598. void QCPLabelPainterPrivate::setPadding(int padding)
  4599. {
  4600. mPadding = padding;
  4601. }
  4602. void QCPLabelPainterPrivate::setRotation(double rotation)
  4603. {
  4604. mRotation = qBound(-90.0, rotation, 90.0);
  4605. }
  4606. void QCPLabelPainterPrivate::setSubstituteExponent(bool enabled)
  4607. {
  4608. mSubstituteExponent = enabled;
  4609. }
  4610. void QCPLabelPainterPrivate::setMultiplicationSymbol(QChar symbol)
  4611. {
  4612. mMultiplicationSymbol = symbol;
  4613. }
  4614. void QCPLabelPainterPrivate::setAbbreviateDecimalPowers(bool enabled)
  4615. {
  4616. mAbbreviateDecimalPowers = enabled;
  4617. }
  4618. void QCPLabelPainterPrivate::setCacheSize(int labelCount)
  4619. {
  4620. mLabelCache.setMaxCost(labelCount);
  4621. }
  4622. int QCPLabelPainterPrivate::cacheSize() const
  4623. {
  4624. return mLabelCache.maxCost();
  4625. }
  4626. void QCPLabelPainterPrivate::drawTickLabel(QCPPainter *painter, const QPointF &tickPos, const QString &text)
  4627. {
  4628. double realRotation = mRotation;
  4629. AnchorSide realSide = mAnchorSide;
  4630. // for circular axes, the anchor side is determined depending on the quadrant of tickPos with respect to mCircularReference
  4631. if (mAnchorMode == amSkewedUpright)
  4632. {
  4633. realSide = skewedAnchorSide(tickPos, 0.2, 0.3);
  4634. } else if (mAnchorMode == amSkewedRotated) // in this mode every label is individually rotated to match circle tangent
  4635. {
  4636. realSide = skewedAnchorSide(tickPos, 0, 0);
  4637. realRotation += QCPVector2D(tickPos-mAnchorReference).angle()/M_PI*180.0;
  4638. if (realRotation > 90) realRotation -= 180;
  4639. else if (realRotation < -90) realRotation += 180;
  4640. }
  4641. realSide = rotationCorrectedSide(realSide, realRotation); // rotation angles may change the true anchor side of the label
  4642. drawLabelMaybeCached(painter, mFont, mColor, getAnchorPos(tickPos), realSide, realRotation, text);
  4643. }
  4644. /*! \internal
  4645. Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
  4646. direction) needed to fit the axis.
  4647. */
  4648. /* TODO: needed?
  4649. int QCPLabelPainterPrivate::size() const
  4650. {
  4651. int result = 0;
  4652. // get length of tick marks pointing outwards:
  4653. if (!tickPositions.isEmpty())
  4654. result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  4655. // calculate size of tick labels:
  4656. if (tickLabelSide == QCPAxis::lsOutside)
  4657. {
  4658. QSize tickLabelsSize(0, 0);
  4659. if (!tickLabels.isEmpty())
  4660. {
  4661. for (int i=0; i<tickLabels.size(); ++i)
  4662. getMaxTickLabelSize(tickLabelFont, tickLabels.at(i), &tickLabelsSize);
  4663. result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
  4664. result += tickLabelPadding;
  4665. }
  4666. }
  4667. // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
  4668. if (!label.isEmpty())
  4669. {
  4670. QFontMetrics fontMetrics(labelFont);
  4671. QRect bounds;
  4672. bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
  4673. result += bounds.height() + labelPadding;
  4674. }
  4675. return result;
  4676. }
  4677. */
  4678. /*! \internal
  4679. Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
  4680. method is called automatically if any parameters have changed that invalidate the cached labels,
  4681. such as font, color, etc. Usually you won't need to call this method manually.
  4682. */
  4683. void QCPLabelPainterPrivate::clearCache()
  4684. {
  4685. mLabelCache.clear();
  4686. }
  4687. /*! \internal
  4688. Returns a hash that allows uniquely identifying whether the label parameters have changed such
  4689. that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
  4690. return value of this method hasn't changed since the last redraw, the respective label parameters
  4691. haven't changed and cached labels may be used.
  4692. */
  4693. QByteArray QCPLabelPainterPrivate::generateLabelParameterHash() const
  4694. {
  4695. QByteArray result;
  4696. result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio()));
  4697. result.append(QByteArray::number(mRotation));
  4698. //result.append(QByteArray::number((int)tickLabelSide)); TODO: check whether this is really a cache-invalidating property
  4699. result.append(QByteArray::number((int)mSubstituteExponent));
  4700. result.append(QString(mMultiplicationSymbol).toUtf8());
  4701. result.append(mColor.name().toLatin1()+QByteArray::number(mColor.alpha(), 16));
  4702. result.append(mFont.toString().toLatin1());
  4703. return result;
  4704. }
  4705. /*! \internal
  4706. Draws a single tick label with the provided \a painter, utilizing the internal label cache to
  4707. significantly speed up drawing of labels that were drawn in previous calls. The tick label is
  4708. always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
  4709. pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
  4710. for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
  4711. at which the label should be drawn.
  4712. In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
  4713. largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
  4714. drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
  4715. tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
  4716. holds.
  4717. The label is drawn with the font and pen that are currently set on the \a painter. To draw
  4718. superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
  4719. getTickLabelData).
  4720. */
  4721. void QCPLabelPainterPrivate::drawLabelMaybeCached(QCPPainter *painter, const QFont &font, const QColor &color, const QPointF &pos, AnchorSide side, double rotation, const QString &text)
  4722. {
  4723. // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
  4724. if (text.isEmpty()) return;
  4725. QSize finalSize;
  4726. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
  4727. {
  4728. QByteArray key = cacheKey(text, color, rotation, side);
  4729. CachedLabel *cachedLabel = mLabelCache.take(QString::fromUtf8(key)); // attempt to take label from cache (don't use object() because we want ownership/prevent deletion during our operations, we re-insert it afterwards)
  4730. if (!cachedLabel) // no cached label existed, create it
  4731. {
  4732. LabelData labelData = getTickLabelData(font, color, rotation, side, text);
  4733. cachedLabel = createCachedLabel(labelData);
  4734. }
  4735. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  4736. bool labelClippedByBorder = false;
  4737. /*
  4738. if (tickLabelSide == QCPAxis::lsOutside)
  4739. {
  4740. if (QCPAxis::orientation(type) == Qt::Horizontal)
  4741. labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
  4742. else
  4743. labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
  4744. }
  4745. */
  4746. if (!labelClippedByBorder)
  4747. {
  4748. painter->drawPixmap(pos+cachedLabel->offset, cachedLabel->pixmap);
  4749. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio(); // TODO: collect this in a member rect list?
  4750. }
  4751. mLabelCache.insert(QString::fromUtf8(key), cachedLabel);
  4752. } else // label caching disabled, draw text directly on surface:
  4753. {
  4754. LabelData labelData = getTickLabelData(font, color, rotation, side, text);
  4755. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  4756. bool labelClippedByBorder = false;
  4757. /*
  4758. if (tickLabelSide == QCPAxis::lsOutside)
  4759. {
  4760. if (QCPAxis::orientation(type) == Qt::Horizontal)
  4761. labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left();
  4762. else
  4763. labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top();
  4764. }
  4765. */
  4766. if (!labelClippedByBorder)
  4767. {
  4768. drawText(painter, pos, labelData);
  4769. finalSize = labelData.rotatedTotalBounds.size();
  4770. }
  4771. }
  4772. /*
  4773. // expand passed tickLabelsSize if current tick label is larger:
  4774. if (finalSize.width() > tickLabelsSize->width())
  4775. tickLabelsSize->setWidth(finalSize.width());
  4776. if (finalSize.height() > tickLabelsSize->height())
  4777. tickLabelsSize->setHeight(finalSize.height());
  4778. */
  4779. }
  4780. QPointF QCPLabelPainterPrivate::getAnchorPos(const QPointF &tickPos)
  4781. {
  4782. switch (mAnchorMode)
  4783. {
  4784. case amRectangular:
  4785. {
  4786. switch (mAnchorSide)
  4787. {
  4788. case asLeft: return tickPos+QPointF(mPadding, 0);
  4789. case asRight: return tickPos+QPointF(-mPadding, 0);
  4790. case asTop: return tickPos+QPointF(0, mPadding);
  4791. case asBottom: return tickPos+QPointF(0, -mPadding);
  4792. case asTopLeft: return tickPos+QPointF(mPadding*M_SQRT1_2, mPadding*M_SQRT1_2);
  4793. case asTopRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, mPadding*M_SQRT1_2);
  4794. case asBottomRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2);
  4795. case asBottomLeft: return tickPos+QPointF(mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2);
  4796. }
  4797. }
  4798. case amSkewedUpright:
  4799. case amSkewedRotated:
  4800. {
  4801. QCPVector2D anchorNormal(tickPos-mAnchorReference);
  4802. if (mAnchorReferenceType == artTangent)
  4803. anchorNormal = anchorNormal.perpendicular();
  4804. anchorNormal.normalize();
  4805. return tickPos+(anchorNormal*mPadding).toPointF();
  4806. }
  4807. }
  4808. return tickPos;
  4809. }
  4810. /*! \internal
  4811. This is a \ref placeTickLabel helper function.
  4812. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
  4813. y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
  4814. directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
  4815. QCP::phCacheLabels plotting hint is not set.
  4816. */
  4817. void QCPLabelPainterPrivate::drawText(QCPPainter *painter, const QPointF &pos, const LabelData &labelData) const
  4818. {
  4819. // backup painter settings that we're about to change:
  4820. QTransform oldTransform = painter->transform();
  4821. QFont oldFont = painter->font();
  4822. QPen oldPen = painter->pen();
  4823. // transform painter to position/rotation:
  4824. painter->translate(pos);
  4825. painter->setTransform(labelData.transform, true);
  4826. // draw text:
  4827. painter->setFont(labelData.baseFont);
  4828. painter->setPen(QPen(labelData.color));
  4829. if (!labelData.expPart.isEmpty()) // use superscripted exponent typesetting
  4830. {
  4831. painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
  4832. if (!labelData.suffixPart.isEmpty())
  4833. painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart);
  4834. painter->setFont(labelData.expFont);
  4835. painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
  4836. } else
  4837. {
  4838. painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
  4839. }
  4840. /* Debug code to draw label bounding boxes, baseline, and capheight
  4841. painter->save();
  4842. painter->setPen(QPen(QColor(0, 0, 0, 150)));
  4843. painter->drawRect(labelData.totalBounds);
  4844. const int baseline = labelData.totalBounds.height()-mLetterDescent;
  4845. painter->setPen(QPen(QColor(255, 0, 0, 150)));
  4846. painter->drawLine(QLineF(0, baseline, labelData.totalBounds.width(), baseline));
  4847. painter->setPen(QPen(QColor(0, 0, 255, 150)));
  4848. painter->drawLine(QLineF(0, baseline-mLetterCapHeight, labelData.totalBounds.width(), baseline-mLetterCapHeight));
  4849. painter->restore();
  4850. */
  4851. // reset painter settings to what it was before:
  4852. painter->setTransform(oldTransform);
  4853. painter->setFont(oldFont);
  4854. painter->setPen(oldPen);
  4855. }
  4856. /*! \internal
  4857. This is a \ref placeTickLabel helper function.
  4858. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
  4859. processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
  4860. exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
  4861. */
  4862. QCPLabelPainterPrivate::LabelData QCPLabelPainterPrivate::getTickLabelData(const QFont &font, const QColor &color, double rotation, AnchorSide side, const QString &text) const
  4863. {
  4864. LabelData result;
  4865. result.rotation = rotation;
  4866. result.side = side;
  4867. result.color = color;
  4868. // determine whether beautiful decimal powers should be used
  4869. bool useBeautifulPowers = false;
  4870. int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
  4871. int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
  4872. if (mSubstituteExponent)
  4873. {
  4874. ePos = text.indexOf(QLatin1Char('e'));
  4875. if (ePos > 0 && text.at(ePos-1).isDigit())
  4876. {
  4877. eLast = ePos;
  4878. while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
  4879. ++eLast;
  4880. if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
  4881. useBeautifulPowers = true;
  4882. }
  4883. }
  4884. // calculate text bounding rects and do string preparation for beautiful decimal powers:
  4885. result.baseFont = font;
  4886. if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line
  4887. result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding
  4888. QFontMetrics baseFontMetrics(result.baseFont);
  4889. if (useBeautifulPowers)
  4890. {
  4891. // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
  4892. result.basePart = text.left(ePos);
  4893. result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent
  4894. // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
  4895. if (mAbbreviateDecimalPowers && result.basePart == QLatin1String("1"))
  4896. result.basePart = QLatin1String("10");
  4897. else
  4898. result.basePart += QString(mMultiplicationSymbol) + QLatin1String("10");
  4899. result.expPart = text.mid(ePos+1, eLast-ePos);
  4900. // clip "+" and leading zeros off expPart:
  4901. while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
  4902. result.expPart.remove(1, 1);
  4903. if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
  4904. result.expPart.remove(0, 1);
  4905. // prepare smaller font for exponent:
  4906. result.expFont = font;
  4907. if (result.expFont.pointSize() > 0)
  4908. result.expFont.setPointSize(result.expFont.pointSize()*0.75);
  4909. else
  4910. result.expFont.setPixelSize(result.expFont.pixelSize()*0.75);
  4911. // calculate bounding rects of base part(s), exponent part and total one:
  4912. result.baseBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
  4913. result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
  4914. if (!result.suffixPart.isEmpty())
  4915. result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart);
  4916. result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+result.suffixBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA
  4917. } else // useBeautifulPowers == false
  4918. {
  4919. result.basePart = text;
  4920. result.totalBounds = baseFontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
  4921. }
  4922. result.totalBounds.moveTopLeft(QPoint(0, 0));
  4923. applyAnchorTransform(result);
  4924. result.rotatedTotalBounds = result.transform.mapRect(result.totalBounds);
  4925. return result;
  4926. }
  4927. void QCPLabelPainterPrivate::applyAnchorTransform(LabelData &labelData) const
  4928. {
  4929. if (!qFuzzyIsNull(labelData.rotation))
  4930. labelData.transform.rotate(labelData.rotation); // rotates effectively clockwise (due to flipped y axis of painter vs widget coordinate system)
  4931. // from now on we translate in rotated label-local coordinate system.
  4932. // shift origin of coordinate system to appropriate point on label:
  4933. labelData.transform.translate(0, -labelData.totalBounds.height()+mLetterDescent+mLetterCapHeight); // shifts origin to true top of capital (or number) characters
  4934. if (labelData.side == asLeft || labelData.side == asRight) // anchor is centered vertically
  4935. labelData.transform.translate(0, -mLetterCapHeight/2.0);
  4936. else if (labelData.side == asTop || labelData.side == asBottom) // anchor is centered horizontally
  4937. labelData.transform.translate(-labelData.totalBounds.width()/2.0, 0);
  4938. if (labelData.side == asTopRight || labelData.side == asRight || labelData.side == asBottomRight) // anchor is at right
  4939. labelData.transform.translate(-labelData.totalBounds.width(), 0);
  4940. if (labelData.side == asBottomLeft || labelData.side == asBottom || labelData.side == asBottomRight) // anchor is at bottom (no elseif!)
  4941. labelData.transform.translate(0, -mLetterCapHeight);
  4942. }
  4943. /*! \internal
  4944. Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
  4945. to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
  4946. margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
  4947. smaller width/height.
  4948. */
  4949. /*
  4950. void QCPLabelPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const
  4951. {
  4952. // note: this function must return the same tick label sizes as the placeTickLabel function.
  4953. QSize finalSize;
  4954. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
  4955. {
  4956. const CachedLabel *cachedLabel = mLabelCache.object(text);
  4957. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
  4958. } else // label caching disabled or no label with this text cached:
  4959. {
  4960. // TODO: LabelData labelData = getTickLabelData(font, text);
  4961. // TODO: finalSize = labelData.rotatedTotalBounds.size();
  4962. }
  4963. // expand passed tickLabelsSize if current tick label is larger:
  4964. if (finalSize.width() > tickLabelsSize->width())
  4965. tickLabelsSize->setWidth(finalSize.width());
  4966. if (finalSize.height() > tickLabelsSize->height())
  4967. tickLabelsSize->setHeight(finalSize.height());
  4968. }
  4969. */
  4970. QCPLabelPainterPrivate::CachedLabel *QCPLabelPainterPrivate::createCachedLabel(const LabelData &labelData) const
  4971. {
  4972. CachedLabel *result = new CachedLabel;
  4973. // allocate pixmap with the correct size and pixel ratio:
  4974. if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio()))
  4975. {
  4976. result->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio());
  4977. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  4978. # ifdef QCP_DEVICEPIXELRATIO_FLOAT
  4979. result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF());
  4980. # else
  4981. result->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio());
  4982. # endif
  4983. #endif
  4984. } else
  4985. result->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
  4986. result->pixmap.fill(Qt::transparent);
  4987. // draw the label into the pixmap
  4988. // offset is between label anchor and topleft of cache pixmap, so pixmap can be drawn at pos+offset to make the label anchor appear at pos.
  4989. // We use rotatedTotalBounds.topLeft() because rotatedTotalBounds is in a coordinate system where the label anchor is at (0, 0)
  4990. result->offset = labelData.rotatedTotalBounds.topLeft();
  4991. QCPPainter cachePainter(&result->pixmap);
  4992. drawText(&cachePainter, -result->offset, labelData);
  4993. return result;
  4994. }
  4995. QByteArray QCPLabelPainterPrivate::cacheKey(const QString &text, const QColor &color, double rotation, AnchorSide side) const
  4996. {
  4997. return text.toUtf8()+
  4998. QByteArray::number(color.red()+256*color.green()+65536*color.blue(), 36)+
  4999. QByteArray::number(color.alpha()+256*(int)side, 36)+
  5000. QByteArray::number((int)(rotation*100)%36000, 36);
  5001. }
  5002. QCPLabelPainterPrivate::AnchorSide QCPLabelPainterPrivate::skewedAnchorSide(const QPointF &tickPos, double sideExpandHorz, double sideExpandVert) const
  5003. {
  5004. QCPVector2D anchorNormal = QCPVector2D(tickPos-mAnchorReference);
  5005. if (mAnchorReferenceType == artTangent)
  5006. anchorNormal = anchorNormal.perpendicular();
  5007. const double radius = anchorNormal.length();
  5008. const double sideHorz = sideExpandHorz*radius;
  5009. const double sideVert = sideExpandVert*radius;
  5010. if (anchorNormal.x() > sideHorz)
  5011. {
  5012. if (anchorNormal.y() > sideVert) return asTopLeft;
  5013. else if (anchorNormal.y() < -sideVert) return asBottomLeft;
  5014. else return asLeft;
  5015. } else if (anchorNormal.x() < -sideHorz)
  5016. {
  5017. if (anchorNormal.y() > sideVert) return asTopRight;
  5018. else if (anchorNormal.y() < -sideVert) return asBottomRight;
  5019. else return asRight;
  5020. } else
  5021. {
  5022. if (anchorNormal.y() > 0) return asTop;
  5023. else return asBottom;
  5024. }
  5025. return asBottom; // should never be reached
  5026. }
  5027. QCPLabelPainterPrivate::AnchorSide QCPLabelPainterPrivate::rotationCorrectedSide(AnchorSide side, double rotation) const
  5028. {
  5029. AnchorSide result = side;
  5030. const bool rotateClockwise = rotation > 0;
  5031. if (!qFuzzyIsNull(rotation))
  5032. {
  5033. if (!qFuzzyCompare(qAbs(rotation), 90)) // avoid graphical collision with anchor tangent (e.g. axis line) when rotating, so change anchor side appropriately:
  5034. {
  5035. if (side == asTop) result = rotateClockwise ? asLeft : asRight;
  5036. else if (side == asBottom) result = rotateClockwise ? asRight : asLeft;
  5037. else if (side == asTopLeft) result = rotateClockwise ? asLeft : asTop;
  5038. else if (side == asTopRight) result = rotateClockwise ? asTop : asRight;
  5039. else if (side == asBottomLeft) result = rotateClockwise ? asBottom : asLeft;
  5040. else if (side == asBottomRight) result = rotateClockwise ? asRight : asBottom;
  5041. } else // for full rotation by +/-90 degrees, other sides are more appropriate for centering on anchor:
  5042. {
  5043. if (side == asLeft) result = rotateClockwise ? asBottom : asTop;
  5044. else if (side == asRight) result = rotateClockwise ? asTop : asBottom;
  5045. else if (side == asTop) result = rotateClockwise ? asLeft : asRight;
  5046. else if (side == asBottom) result = rotateClockwise ? asRight : asLeft;
  5047. else if (side == asTopLeft) result = rotateClockwise ? asBottomLeft : asTopRight;
  5048. else if (side == asTopRight) result = rotateClockwise ? asTopLeft : asBottomRight;
  5049. else if (side == asBottomLeft) result = rotateClockwise ? asBottomRight : asTopLeft;
  5050. else if (side == asBottomRight) result = rotateClockwise ? asTopRight : asBottomLeft;
  5051. }
  5052. }
  5053. return result;
  5054. }
  5055. void QCPLabelPainterPrivate::analyzeFontMetrics()
  5056. {
  5057. const QFontMetrics fm(mFont);
  5058. mLetterCapHeight = fm.tightBoundingRect(QLatin1String("8")).height(); // this method is slow, that's why we query it only upon font change
  5059. mLetterDescent = fm.descent();
  5060. }
  5061. /* end of 'src/axis/labelpainter.cpp' */
  5062. /* including file 'src/axis/axisticker.cpp' */
  5063. /* modified 2021-03-29T02:30:44, size 18688 */
  5064. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5065. //////////////////// QCPAxisTicker
  5066. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5067. /*! \class QCPAxisTicker
  5068. \brief The base class tick generator used by QCPAxis to create tick positions and tick labels
  5069. Each QCPAxis has an internal QCPAxisTicker (or a subclass) in order to generate tick positions
  5070. and tick labels for the current axis range. The ticker of an axis can be set via \ref
  5071. QCPAxis::setTicker. Since that method takes a <tt>QSharedPointer<QCPAxisTicker></tt>, multiple
  5072. axes can share the same ticker instance.
  5073. This base class generates normal tick coordinates and numeric labels for linear axes. It picks a
  5074. reasonable tick step (the separation between ticks) which results in readable tick labels. The
  5075. number of ticks that should be approximately generated can be set via \ref setTickCount.
  5076. Depending on the current tick step strategy (\ref setTickStepStrategy), the algorithm either
  5077. sacrifices readability to better match the specified tick count (\ref
  5078. QCPAxisTicker::tssMeetTickCount) or relaxes the tick count in favor of better tick steps (\ref
  5079. QCPAxisTicker::tssReadability), which is the default.
  5080. The following more specialized axis ticker subclasses are available, see details in the
  5081. respective class documentation:
  5082. <center>
  5083. <table>
  5084. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerFixed</td><td>\image html axisticker-fixed.png</td></tr>
  5085. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerLog</td><td>\image html axisticker-log.png</td></tr>
  5086. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerPi</td><td>\image html axisticker-pi.png</td></tr>
  5087. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerText</td><td>\image html axisticker-text.png</td></tr>
  5088. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerDateTime</td><td>\image html axisticker-datetime.png</td></tr>
  5089. <tr><td style="text-align:right; padding: 0 1em">QCPAxisTickerTime</td><td>\image html axisticker-time.png
  5090. \image html axisticker-time2.png</td></tr>
  5091. </table>
  5092. </center>
  5093. \section axisticker-subclassing Creating own axis tickers
  5094. Creating own axis tickers can be achieved very easily by sublassing QCPAxisTicker and
  5095. reimplementing some or all of the available virtual methods.
  5096. In the simplest case you might wish to just generate different tick steps than the other tickers,
  5097. so you only reimplement the method \ref getTickStep. If you additionally want control over the
  5098. string that will be shown as tick label, reimplement \ref getTickLabel.
  5099. If you wish to have complete control, you can generate the tick vectors and tick label vectors
  5100. yourself by reimplementing \ref createTickVector and \ref createLabelVector. The default
  5101. implementations use the previously mentioned virtual methods \ref getTickStep and \ref
  5102. getTickLabel, but your reimplementations don't necessarily need to do so. For example in the case
  5103. of unequal tick steps, the method \ref getTickStep loses its usefulness and can be ignored.
  5104. The sub tick count between major ticks can be controlled with \ref getSubTickCount. Full sub tick
  5105. placement control is obtained by reimplementing \ref createSubTickVector.
  5106. See the documentation of all these virtual methods in QCPAxisTicker for detailed information
  5107. about the parameters and expected return values.
  5108. */
  5109. /*!
  5110. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5111. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5112. */
  5113. QCPAxisTicker::QCPAxisTicker() :
  5114. mTickStepStrategy(tssReadability),
  5115. mTickCount(5),
  5116. mTickOrigin(0)
  5117. {
  5118. }
  5119. QCPAxisTicker::~QCPAxisTicker()
  5120. {
  5121. }
  5122. /*!
  5123. Sets which strategy the axis ticker follows when choosing the size of the tick step. For the
  5124. available strategies, see \ref TickStepStrategy.
  5125. */
  5126. void QCPAxisTicker::setTickStepStrategy(QCPAxisTicker::TickStepStrategy strategy)
  5127. {
  5128. mTickStepStrategy = strategy;
  5129. }
  5130. /*!
  5131. Sets how many ticks this ticker shall aim to generate across the axis range. Note that \a count
  5132. is not guaranteed to be matched exactly, as generating readable tick intervals may conflict with
  5133. the requested number of ticks.
  5134. Whether the readability has priority over meeting the requested \a count can be specified with
  5135. \ref setTickStepStrategy.
  5136. */
  5137. void QCPAxisTicker::setTickCount(int count)
  5138. {
  5139. if (count > 0)
  5140. mTickCount = count;
  5141. else
  5142. qDebug() << Q_FUNC_INFO << "tick count must be greater than zero:" << count;
  5143. }
  5144. /*!
  5145. Sets the mathematical coordinate (or "offset") of the zeroth tick. This tick coordinate is just a
  5146. concept and doesn't need to be inside the currently visible axis range.
  5147. By default \a origin is zero, which for example yields ticks {-5, 0, 5, 10, 15,...} when the tick
  5148. step is five. If \a origin is now set to 1 instead, the correspondingly generated ticks would be
  5149. {-4, 1, 6, 11, 16,...}.
  5150. */
  5151. void QCPAxisTicker::setTickOrigin(double origin)
  5152. {
  5153. mTickOrigin = origin;
  5154. }
  5155. /*!
  5156. This is the method called by QCPAxis in order to actually generate tick coordinates (\a ticks),
  5157. tick label strings (\a tickLabels) and sub tick coordinates (\a subTicks).
  5158. The ticks are generated for the specified \a range. The generated labels typically follow the
  5159. specified \a locale, \a formatChar and number \a precision, however this might be different (or
  5160. even irrelevant) for certain QCPAxisTicker subclasses.
  5161. The output parameter \a ticks is filled with the generated tick positions in axis coordinates.
  5162. The output parameters \a subTicks and \a tickLabels are optional (set them to \c nullptr if not
  5163. needed) and are respectively filled with sub tick coordinates, and tick label strings belonging
  5164. to \a ticks by index.
  5165. */
  5166. void QCPAxisTicker::generate(const QCPRange &range, const QLocale &locale, QChar formatChar, int precision, QVector<double> &ticks, QVector<double> *subTicks, QVector<QString> *tickLabels)
  5167. {
  5168. // generate (major) ticks:
  5169. double tickStep = getTickStep(range);
  5170. ticks = createTickVector(tickStep, range);
  5171. trimTicks(range, ticks, true); // trim ticks to visible range plus one outer tick on each side (incase a subclass createTickVector creates more)
  5172. // generate sub ticks between major ticks:
  5173. if (subTicks)
  5174. {
  5175. if (!ticks.isEmpty())
  5176. {
  5177. *subTicks = createSubTickVector(getSubTickCount(tickStep), ticks);
  5178. trimTicks(range, *subTicks, false);
  5179. } else
  5180. *subTicks = QVector<double>();
  5181. }
  5182. // finally trim also outliers (no further clipping happens in axis drawing):
  5183. trimTicks(range, ticks, false);
  5184. // generate labels for visible ticks if requested:
  5185. if (tickLabels)
  5186. *tickLabels = createLabelVector(ticks, locale, formatChar, precision);
  5187. }
  5188. /*! \internal
  5189. Takes the entire currently visible axis range and returns a sensible tick step in
  5190. order to provide readable tick labels as well as a reasonable number of tick counts (see \ref
  5191. setTickCount, \ref setTickStepStrategy).
  5192. If a QCPAxisTicker subclass only wants a different tick step behaviour than the default
  5193. implementation, it should reimplement this method. See \ref cleanMantissa for a possible helper
  5194. function.
  5195. */
  5196. double QCPAxisTicker::getTickStep(const QCPRange &range)
  5197. {
  5198. double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  5199. return cleanMantissa(exactStep);
  5200. }
  5201. /*! \internal
  5202. Takes the \a tickStep, i.e. the distance between two consecutive ticks, and returns
  5203. an appropriate number of sub ticks for that specific tick step.
  5204. Note that a returned sub tick count of e.g. 4 will split each tick interval into 5 sections.
  5205. */
  5206. int QCPAxisTicker::getSubTickCount(double tickStep)
  5207. {
  5208. int result = 1; // default to 1, if no proper value can be found
  5209. // separate integer and fractional part of mantissa:
  5210. double epsilon = 0.01;
  5211. double intPartf;
  5212. int intPart;
  5213. double fracPart = modf(getMantissa(tickStep), &intPartf);
  5214. intPart = int(intPartf);
  5215. // handle cases with (almost) integer mantissa:
  5216. if (fracPart < epsilon || 1.0-fracPart < epsilon)
  5217. {
  5218. if (1.0-fracPart < epsilon)
  5219. ++intPart;
  5220. switch (intPart)
  5221. {
  5222. case 1: result = 4; break; // 1.0 -> 0.2 substep
  5223. case 2: result = 3; break; // 2.0 -> 0.5 substep
  5224. case 3: result = 2; break; // 3.0 -> 1.0 substep
  5225. case 4: result = 3; break; // 4.0 -> 1.0 substep
  5226. case 5: result = 4; break; // 5.0 -> 1.0 substep
  5227. case 6: result = 2; break; // 6.0 -> 2.0 substep
  5228. case 7: result = 6; break; // 7.0 -> 1.0 substep
  5229. case 8: result = 3; break; // 8.0 -> 2.0 substep
  5230. case 9: result = 2; break; // 9.0 -> 3.0 substep
  5231. }
  5232. } else
  5233. {
  5234. // handle cases with significantly fractional mantissa:
  5235. if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa
  5236. {
  5237. switch (intPart)
  5238. {
  5239. case 1: result = 2; break; // 1.5 -> 0.5 substep
  5240. case 2: result = 4; break; // 2.5 -> 0.5 substep
  5241. case 3: result = 4; break; // 3.5 -> 0.7 substep
  5242. case 4: result = 2; break; // 4.5 -> 1.5 substep
  5243. case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with default getTickStep from here on)
  5244. case 6: result = 4; break; // 6.5 -> 1.3 substep
  5245. case 7: result = 2; break; // 7.5 -> 2.5 substep
  5246. case 8: result = 4; break; // 8.5 -> 1.7 substep
  5247. case 9: result = 4; break; // 9.5 -> 1.9 substep
  5248. }
  5249. }
  5250. // if mantissa fraction isn't 0.0 or 0.5, don't bother finding good sub tick marks, leave default
  5251. }
  5252. return result;
  5253. }
  5254. /*! \internal
  5255. This method returns the tick label string as it should be printed under the \a tick coordinate.
  5256. If a textual number is returned, it should respect the provided \a locale, \a formatChar and \a
  5257. precision.
  5258. If the returned value contains exponentials of the form "2e5" and beautifully typeset powers is
  5259. enabled in the QCPAxis number format (\ref QCPAxis::setNumberFormat), the exponential part will
  5260. be formatted accordingly using multiplication symbol and superscript during rendering of the
  5261. label automatically.
  5262. */
  5263. QString QCPAxisTicker::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5264. {
  5265. return locale.toString(tick, formatChar.toLatin1(), precision);
  5266. }
  5267. /*! \internal
  5268. Returns a vector containing all coordinates of sub ticks that should be drawn. It generates \a
  5269. subTickCount sub ticks between each tick pair given in \a ticks.
  5270. If a QCPAxisTicker subclass needs maximal control over the generated sub ticks, it should
  5271. reimplement this method. Depending on the purpose of the subclass it doesn't necessarily need to
  5272. base its result on \a subTickCount or \a ticks.
  5273. */
  5274. QVector<double> QCPAxisTicker::createSubTickVector(int subTickCount, const QVector<double> &ticks)
  5275. {
  5276. QVector<double> result;
  5277. if (subTickCount <= 0 || ticks.size() < 2)
  5278. return result;
  5279. result.reserve((ticks.size()-1)*subTickCount);
  5280. for (int i=1; i<ticks.size(); ++i)
  5281. {
  5282. double subTickStep = (ticks.at(i)-ticks.at(i-1))/double(subTickCount+1);
  5283. for (int k=1; k<=subTickCount; ++k)
  5284. result.append(ticks.at(i-1) + k*subTickStep);
  5285. }
  5286. return result;
  5287. }
  5288. /*! \internal
  5289. Returns a vector containing all coordinates of ticks that should be drawn. The default
  5290. implementation generates ticks with a spacing of \a tickStep (mathematically starting at the tick
  5291. step origin, see \ref setTickOrigin) distributed over the passed \a range.
  5292. In order for the axis ticker to generate proper sub ticks, it is necessary that the first and
  5293. last tick coordinates returned by this method are just below/above the provided \a range.
  5294. Otherwise the outer intervals won't contain any sub ticks.
  5295. If a QCPAxisTicker subclass needs maximal control over the generated ticks, it should reimplement
  5296. this method. Depending on the purpose of the subclass it doesn't necessarily need to base its
  5297. result on \a tickStep, e.g. when the ticks are spaced unequally like in the case of
  5298. QCPAxisTickerLog.
  5299. */
  5300. QVector<double> QCPAxisTicker::createTickVector(double tickStep, const QCPRange &range)
  5301. {
  5302. QVector<double> result;
  5303. // Generate tick positions according to tickStep:
  5304. qint64 firstStep = qint64(floor((range.lower-mTickOrigin)/tickStep)); // do not use qFloor here, or we'll lose 64 bit precision
  5305. qint64 lastStep = qint64(ceil((range.upper-mTickOrigin)/tickStep)); // do not use qCeil here, or we'll lose 64 bit precision
  5306. int tickcount = int(lastStep-firstStep+1);
  5307. if (tickcount < 0) tickcount = 0;
  5308. result.resize(tickcount);
  5309. for (int i=0; i<tickcount; ++i)
  5310. result[i] = mTickOrigin + (firstStep+i)*tickStep;
  5311. return result;
  5312. }
  5313. /*! \internal
  5314. Returns a vector containing all tick label strings corresponding to the tick coordinates provided
  5315. in \a ticks. The default implementation calls \ref getTickLabel to generate the respective
  5316. strings.
  5317. It is possible but uncommon for QCPAxisTicker subclasses to reimplement this method, as
  5318. reimplementing \ref getTickLabel often achieves the intended result easier.
  5319. */
  5320. QVector<QString> QCPAxisTicker::createLabelVector(const QVector<double> &ticks, const QLocale &locale, QChar formatChar, int precision)
  5321. {
  5322. QVector<QString> result;
  5323. result.reserve(ticks.size());
  5324. foreach (double tickCoord, ticks)
  5325. result.append(getTickLabel(tickCoord, locale, formatChar, precision));
  5326. return result;
  5327. }
  5328. /*! \internal
  5329. Removes tick coordinates from \a ticks which lie outside the specified \a range. If \a
  5330. keepOneOutlier is true, it preserves one tick just outside the range on both sides, if present.
  5331. The passed \a ticks must be sorted in ascending order.
  5332. */
  5333. void QCPAxisTicker::trimTicks(const QCPRange &range, QVector<double> &ticks, bool keepOneOutlier) const
  5334. {
  5335. bool lowFound = false;
  5336. bool highFound = false;
  5337. int lowIndex = 0;
  5338. int highIndex = -1;
  5339. for (int i=0; i < ticks.size(); ++i)
  5340. {
  5341. if (ticks.at(i) >= range.lower)
  5342. {
  5343. lowFound = true;
  5344. lowIndex = i;
  5345. break;
  5346. }
  5347. }
  5348. for (int i=ticks.size()-1; i >= 0; --i)
  5349. {
  5350. if (ticks.at(i) <= range.upper)
  5351. {
  5352. highFound = true;
  5353. highIndex = i;
  5354. break;
  5355. }
  5356. }
  5357. if (highFound && lowFound)
  5358. {
  5359. int trimFront = qMax(0, lowIndex-(keepOneOutlier ? 1 : 0));
  5360. int trimBack = qMax(0, ticks.size()-(keepOneOutlier ? 2 : 1)-highIndex);
  5361. if (trimFront > 0 || trimBack > 0)
  5362. ticks = ticks.mid(trimFront, ticks.size()-trimFront-trimBack);
  5363. } else // all ticks are either all below or all above the range
  5364. ticks.clear();
  5365. }
  5366. /*! \internal
  5367. Returns the coordinate contained in \a candidates which is closest to the provided \a target.
  5368. This method assumes \a candidates is not empty and sorted in ascending order.
  5369. */
  5370. double QCPAxisTicker::pickClosest(double target, const QVector<double> &candidates) const
  5371. {
  5372. if (candidates.size() == 1)
  5373. return candidates.first();
  5374. QVector<double>::const_iterator it = std::lower_bound(candidates.constBegin(), candidates.constEnd(), target);
  5375. if (it == candidates.constEnd())
  5376. return *(it-1);
  5377. else if (it == candidates.constBegin())
  5378. return *it;
  5379. else
  5380. return target-*(it-1) < *it-target ? *(it-1) : *it;
  5381. }
  5382. /*! \internal
  5383. Returns the decimal mantissa of \a input. Optionally, if \a magnitude is not set to zero, it also
  5384. returns the magnitude of \a input as a power of 10.
  5385. For example, an input of 142.6 will return a mantissa of 1.426 and a magnitude of 100.
  5386. */
  5387. double QCPAxisTicker::getMantissa(double input, double *magnitude) const
  5388. {
  5389. const double mag = qPow(10.0, qFloor(qLn(input)/qLn(10.0)));
  5390. if (magnitude) *magnitude = mag;
  5391. return input/mag;
  5392. }
  5393. /*! \internal
  5394. Returns a number that is close to \a input but has a clean, easier human readable mantissa. How
  5395. strongly the mantissa is altered, and thus how strong the result deviates from the original \a
  5396. input, depends on the current tick step strategy (see \ref setTickStepStrategy).
  5397. */
  5398. double QCPAxisTicker::cleanMantissa(double input) const
  5399. {
  5400. double magnitude;
  5401. const double mantissa = getMantissa(input, &magnitude);
  5402. switch (mTickStepStrategy)
  5403. {
  5404. case tssReadability:
  5405. {
  5406. return pickClosest(mantissa, QVector<double>() << 1.0 << 2.0 << 2.5 << 5.0 << 10.0)*magnitude;
  5407. }
  5408. case tssMeetTickCount:
  5409. {
  5410. // this gives effectively a mantissa of 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 6.0, 8.0, 10.0
  5411. if (mantissa <= 5.0)
  5412. return int(mantissa*2)/2.0*magnitude; // round digit after decimal point to 0.5
  5413. else
  5414. return int(mantissa/2.0)*2.0*magnitude; // round to first digit in multiples of 2
  5415. }
  5416. }
  5417. return input;
  5418. }
  5419. /* end of 'src/axis/axisticker.cpp' */
  5420. /* including file 'src/axis/axistickerdatetime.cpp' */
  5421. /* modified 2021-03-29T02:30:44, size 18829 */
  5422. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5423. //////////////////// QCPAxisTickerDateTime
  5424. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5425. /*! \class QCPAxisTickerDateTime
  5426. \brief Specialized axis ticker for calendar dates and times as axis ticks
  5427. \image html axisticker-datetime.png
  5428. This QCPAxisTicker subclass generates ticks that correspond to real calendar dates and times. The
  5429. plot axis coordinate is interpreted as Unix Time, so seconds since Epoch (January 1, 1970, 00:00
  5430. UTC). This is also used for example by QDateTime in the <tt>toTime_t()/setTime_t()</tt> methods
  5431. with a precision of one second. Since Qt 4.7, millisecond accuracy can be obtained from QDateTime
  5432. by using <tt>QDateTime::fromMSecsSinceEpoch()/1000.0</tt>. The static methods \ref dateTimeToKey
  5433. and \ref keyToDateTime conveniently perform this conversion achieving a precision of one
  5434. millisecond on all Qt versions.
  5435. The format of the date/time display in the tick labels is controlled with \ref setDateTimeFormat.
  5436. If a different time spec or time zone shall be used for the tick label appearance, see \ref
  5437. setDateTimeSpec or \ref setTimeZone, respectively.
  5438. This ticker produces unequal tick spacing in order to provide intuitive date and time-of-day
  5439. ticks. For example, if the axis range spans a few years such that there is one tick per year,
  5440. ticks will be positioned on 1. January of every year. This is intuitive but, due to leap years,
  5441. will result in slightly unequal tick intervals (visually unnoticeable). The same can be seen in
  5442. the image above: even though the number of days varies month by month, this ticker generates
  5443. ticks on the same day of each month.
  5444. If you would like to change the date/time that is used as a (mathematical) starting date for the
  5445. ticks, use the \ref setTickOrigin(const QDateTime &origin) method overload, which takes a
  5446. QDateTime. If you pass 15. July, 9:45 to this method, the yearly ticks will end up on 15. July at
  5447. 9:45 of every year.
  5448. The ticker can be created and assigned to an axis like this:
  5449. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerdatetime-creation
  5450. \note If you rather wish to display relative times in terms of days, hours, minutes, seconds and
  5451. milliseconds, and are not interested in the intricacies of real calendar dates with months and
  5452. (leap) years, have a look at QCPAxisTickerTime instead.
  5453. */
  5454. /*!
  5455. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5456. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5457. */
  5458. QCPAxisTickerDateTime::QCPAxisTickerDateTime() :
  5459. mDateTimeFormat(QLatin1String("hh:mm:ss\ndd.MM.yy")),
  5460. mDateTimeSpec(Qt::LocalTime),
  5461. mDateStrategy(dsNone)
  5462. {
  5463. setTickCount(4);
  5464. }
  5465. /*!
  5466. Sets the format in which dates and times are displayed as tick labels. For details about the \a
  5467. format string, see the documentation of QDateTime::toString().
  5468. Typical expressions are
  5469. <table>
  5470. <tr><td>\c d</td><td>The day as a number without a leading zero (1 to 31)</td></tr>
  5471. <tr><td>\c dd</td><td>The day as a number with a leading zero (01 to 31)</td></tr>
  5472. <tr><td>\c ddd</td><td>The abbreviated localized day name (e.g. 'Mon' to 'Sun'). Uses the system locale to localize the name, i.e. QLocale::system().</td></tr>
  5473. <tr><td>\c dddd</td><td>The long localized day name (e.g. 'Monday' to 'Sunday'). Uses the system locale to localize the name, i.e. QLocale::system().</td></tr>
  5474. <tr><td>\c M</td><td>The month as a number without a leading zero (1 to 12)</td></tr>
  5475. <tr><td>\c MM</td><td>The month as a number with a leading zero (01 to 12)</td></tr>
  5476. <tr><td>\c MMM</td><td>The abbreviated localized month name (e.g. 'Jan' to 'Dec'). Uses the system locale to localize the name, i.e. QLocale::system().</td></tr>
  5477. <tr><td>\c MMMM</td><td>The long localized month name (e.g. 'January' to 'December'). Uses the system locale to localize the name, i.e. QLocale::system().</td></tr>
  5478. <tr><td>\c yy</td><td>The year as a two digit number (00 to 99)</td></tr>
  5479. <tr><td>\c yyyy</td><td>The year as a four digit number. If the year is negative, a minus sign is prepended, making five characters.</td></tr>
  5480. <tr><td>\c h</td><td>The hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)</td></tr>
  5481. <tr><td>\c hh</td><td>The hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)</td></tr>
  5482. <tr><td>\c H</td><td>The hour without a leading zero (0 to 23, even with AM/PM display)</td></tr>
  5483. <tr><td>\c HH</td><td>The hour with a leading zero (00 to 23, even with AM/PM display)</td></tr>
  5484. <tr><td>\c m</td><td>The minute without a leading zero (0 to 59)</td></tr>
  5485. <tr><td>\c mm</td><td>The minute with a leading zero (00 to 59)</td></tr>
  5486. <tr><td>\c s</td><td>The whole second, without any leading zero (0 to 59)</td></tr>
  5487. <tr><td>\c ss</td><td>The whole second, with a leading zero where applicable (00 to 59)</td></tr>
  5488. <tr><td>\c z</td><td>The fractional part of the second, to go after a decimal point, without trailing zeroes (0 to 999). Thus "s.z" reports the seconds to full available (millisecond) precision without trailing zeroes.</td></tr>
  5489. <tr><td>\c zzz</td><td>The fractional part of the second, to millisecond precision, including trailing zeroes where applicable (000 to 999).</td></tr>
  5490. <tr><td>\c AP or \c A</td><td>Use AM/PM display. A/AP will be replaced by an upper-case version of either QLocale::amText() or QLocale::pmText().</td></tr>
  5491. <tr><td>\c ap or \c a</td><td>Use am/pm display. a/ap will be replaced by a lower-case version of either QLocale::amText() or QLocale::pmText().</td></tr>
  5492. <tr><td>\c t</td><td>The timezone (for example "CEST")</td></tr>
  5493. </table>
  5494. Newlines can be inserted with \c "\n", literal strings (even when containing above expressions)
  5495. by encapsulating them using single-quotes. A literal single quote can be generated by using two
  5496. consecutive single quotes in the format.
  5497. \see setDateTimeSpec, setTimeZone
  5498. */
  5499. void QCPAxisTickerDateTime::setDateTimeFormat(const QString &format)
  5500. {
  5501. mDateTimeFormat = format;
  5502. }
  5503. /*!
  5504. Sets the time spec that is used for creating the tick labels from corresponding dates/times.
  5505. The default value of QDateTime objects (and also QCPAxisTickerDateTime) is
  5506. <tt>Qt::LocalTime</tt>. However, if the displayed tick labels shall be given in UTC, set \a spec
  5507. to <tt>Qt::UTC</tt>.
  5508. Tick labels corresponding to other time zones can be achieved with \ref setTimeZone (which sets
  5509. \a spec to \c Qt::TimeZone internally). Note that if \a spec is afterwards set to not be \c
  5510. Qt::TimeZone again, the \ref setTimeZone setting will be ignored accordingly.
  5511. \see setDateTimeFormat, setTimeZone
  5512. */
  5513. void QCPAxisTickerDateTime::setDateTimeSpec(Qt::TimeSpec spec)
  5514. {
  5515. mDateTimeSpec = spec;
  5516. }
  5517. # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
  5518. /*!
  5519. Sets the time zone that is used for creating the tick labels from corresponding dates/times. The
  5520. time spec (\ref setDateTimeSpec) is set to \c Qt::TimeZone.
  5521. \see setDateTimeFormat, setTimeZone
  5522. */
  5523. void QCPAxisTickerDateTime::setTimeZone(const QTimeZone &zone)
  5524. {
  5525. mTimeZone = zone;
  5526. mDateTimeSpec = Qt::TimeZone;
  5527. }
  5528. #endif
  5529. /*!
  5530. Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) in seconds since Epoch (1. Jan 1970,
  5531. 00:00 UTC). For the date time ticker it might be more intuitive to use the overload which
  5532. directly takes a QDateTime, see \ref setTickOrigin(const QDateTime &origin).
  5533. This is useful to define the month/day/time recurring at greater tick interval steps. For
  5534. example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
  5535. per year, the ticks will end up on 15. July at 9:45 of every year.
  5536. */
  5537. void QCPAxisTickerDateTime::setTickOrigin(double origin)
  5538. {
  5539. QCPAxisTicker::setTickOrigin(origin);
  5540. }
  5541. /*!
  5542. Sets the tick origin (see \ref QCPAxisTicker::setTickOrigin) as a QDateTime \a origin.
  5543. This is useful to define the month/day/time recurring at greater tick interval steps. For
  5544. example, If you pass 15. July, 9:45 to this method and the tick interval happens to be one tick
  5545. per year, the ticks will end up on 15. July at 9:45 of every year.
  5546. */
  5547. void QCPAxisTickerDateTime::setTickOrigin(const QDateTime &origin)
  5548. {
  5549. setTickOrigin(dateTimeToKey(origin));
  5550. }
  5551. /*! \internal
  5552. Returns a sensible tick step with intervals appropriate for a date-time-display, such as weekly,
  5553. monthly, bi-monthly, etc.
  5554. Note that this tick step isn't used exactly when generating the tick vector in \ref
  5555. createTickVector, but only as a guiding value requiring some correction for each individual tick
  5556. interval. Otherwise this would lead to unintuitive date displays, e.g. jumping between first day
  5557. in the month to the last day in the previous month from tick to tick, due to the non-uniform
  5558. length of months. The same problem arises with leap years.
  5559. \seebaseclassmethod
  5560. */
  5561. double QCPAxisTickerDateTime::getTickStep(const QCPRange &range)
  5562. {
  5563. double result = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  5564. mDateStrategy = dsNone; // leaving it at dsNone means tick coordinates will not be tuned in any special way in createTickVector
  5565. if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
  5566. {
  5567. result = cleanMantissa(result);
  5568. } else if (result < 86400*30.4375*12) // below a year
  5569. {
  5570. result = pickClosest(result, QVector<double>()
  5571. << 1 << 2.5 << 5 << 10 << 15 << 30 << 60 << 2.5*60 << 5*60 << 10*60 << 15*60 << 30*60 << 60*60 // second, minute, hour range
  5572. << 3600*2 << 3600*3 << 3600*6 << 3600*12 << 3600*24 // hour to day range
  5573. << 86400*2 << 86400*5 << 86400*7 << 86400*14 << 86400*30.4375 << 86400*30.4375*2 << 86400*30.4375*3 << 86400*30.4375*6 << 86400*30.4375*12); // day, week, month range (avg. days per month includes leap years)
  5574. if (result > 86400*30.4375-1) // month tick intervals or larger
  5575. mDateStrategy = dsUniformDayInMonth;
  5576. else if (result > 3600*24-1) // day tick intervals or larger
  5577. mDateStrategy = dsUniformTimeInDay;
  5578. } else // more than a year, go back to normal clean mantissa algorithm but in units of years
  5579. {
  5580. const double secondsPerYear = 86400*30.4375*12; // average including leap years
  5581. result = cleanMantissa(result/secondsPerYear)*secondsPerYear;
  5582. mDateStrategy = dsUniformDayInMonth;
  5583. }
  5584. return result;
  5585. }
  5586. /*! \internal
  5587. Returns a sensible sub tick count with intervals appropriate for a date-time-display, such as weekly,
  5588. monthly, bi-monthly, etc.
  5589. \seebaseclassmethod
  5590. */
  5591. int QCPAxisTickerDateTime::getSubTickCount(double tickStep)
  5592. {
  5593. int result = QCPAxisTicker::getSubTickCount(tickStep);
  5594. switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day/week/month range (as specified in getTickStep)
  5595. {
  5596. case 5*60: result = 4; break;
  5597. case 10*60: result = 1; break;
  5598. case 15*60: result = 2; break;
  5599. case 30*60: result = 1; break;
  5600. case 60*60: result = 3; break;
  5601. case 3600*2: result = 3; break;
  5602. case 3600*3: result = 2; break;
  5603. case 3600*6: result = 1; break;
  5604. case 3600*12: result = 3; break;
  5605. case 3600*24: result = 3; break;
  5606. case 86400*2: result = 1; break;
  5607. case 86400*5: result = 4; break;
  5608. case 86400*7: result = 6; break;
  5609. case 86400*14: result = 1; break;
  5610. case int(86400*30.4375+0.5): result = 3; break;
  5611. case int(86400*30.4375*2+0.5): result = 1; break;
  5612. case int(86400*30.4375*3+0.5): result = 2; break;
  5613. case int(86400*30.4375*6+0.5): result = 5; break;
  5614. case int(86400*30.4375*12+0.5): result = 3; break;
  5615. }
  5616. return result;
  5617. }
  5618. /*! \internal
  5619. Generates a date/time tick label for tick coordinate \a tick, based on the currently set format
  5620. (\ref setDateTimeFormat), time spec (\ref setDateTimeSpec), and possibly time zone (\ref
  5621. setTimeZone).
  5622. \seebaseclassmethod
  5623. */
  5624. QString QCPAxisTickerDateTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5625. {
  5626. Q_UNUSED(precision)
  5627. Q_UNUSED(formatChar)
  5628. # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
  5629. if (mDateTimeSpec == Qt::TimeZone)
  5630. return locale.toString(keyToDateTime(tick).toTimeZone(mTimeZone), mDateTimeFormat);
  5631. else
  5632. return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
  5633. # else
  5634. return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
  5635. # endif
  5636. }
  5637. /*! \internal
  5638. Uses the passed \a tickStep as a guiding value and applies corrections in order to obtain
  5639. non-uniform tick intervals but intuitive tick labels, e.g. falling on the same day of each month.
  5640. \seebaseclassmethod
  5641. */
  5642. QVector<double> QCPAxisTickerDateTime::createTickVector(double tickStep, const QCPRange &range)
  5643. {
  5644. QVector<double> result = QCPAxisTicker::createTickVector(tickStep, range);
  5645. if (!result.isEmpty())
  5646. {
  5647. if (mDateStrategy == dsUniformTimeInDay)
  5648. {
  5649. QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // the time of this datetime will be set for all other ticks, if possible
  5650. QDateTime tickDateTime;
  5651. for (int i=0; i<result.size(); ++i)
  5652. {
  5653. tickDateTime = keyToDateTime(result.at(i));
  5654. tickDateTime.setTime(uniformDateTime.time());
  5655. result[i] = dateTimeToKey(tickDateTime);
  5656. }
  5657. } else if (mDateStrategy == dsUniformDayInMonth)
  5658. {
  5659. QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // this day (in month) and time will be set for all other ticks, if possible
  5660. QDateTime tickDateTime;
  5661. for (int i=0; i<result.size(); ++i)
  5662. {
  5663. tickDateTime = keyToDateTime(result.at(i));
  5664. tickDateTime.setTime(uniformDateTime.time());
  5665. int thisUniformDay = uniformDateTime.date().day() <= tickDateTime.date().daysInMonth() ? uniformDateTime.date().day() : tickDateTime.date().daysInMonth(); // don't exceed month (e.g. try to set day 31 in February)
  5666. if (thisUniformDay-tickDateTime.date().day() < -15) // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day
  5667. tickDateTime = tickDateTime.addMonths(1);
  5668. else if (thisUniformDay-tickDateTime.date().day() > 15) // with leap years involved, date month may jump backwards or forwards, and needs to be corrected before setting day
  5669. tickDateTime = tickDateTime.addMonths(-1);
  5670. tickDateTime.setDate(QDate(tickDateTime.date().year(), tickDateTime.date().month(), thisUniformDay));
  5671. result[i] = dateTimeToKey(tickDateTime);
  5672. }
  5673. }
  5674. }
  5675. return result;
  5676. }
  5677. /*!
  5678. A convenience method which turns \a key (in seconds since Epoch 1. Jan 1970, 00:00 UTC) into a
  5679. QDateTime object. This can be used to turn axis coordinates to actual QDateTimes.
  5680. The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
  5681. works around the lack of a QDateTime::fromMSecsSinceEpoch in Qt 4.6)
  5682. \see dateTimeToKey
  5683. */
  5684. QDateTime QCPAxisTickerDateTime::keyToDateTime(double key)
  5685. {
  5686. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5687. return QDateTime::fromTime_t(key).addMSecs((key-(qint64)key)*1000);
  5688. # else
  5689. return QDateTime::fromMSecsSinceEpoch(qint64(key*1000.0));
  5690. # endif
  5691. }
  5692. /*! \overload
  5693. A convenience method which turns a QDateTime object into a double value that corresponds to
  5694. seconds since Epoch (1. Jan 1970, 00:00 UTC). This is the format used as axis coordinates by
  5695. QCPAxisTickerDateTime.
  5696. The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
  5697. works around the lack of a QDateTime::toMSecsSinceEpoch in Qt 4.6)
  5698. \see keyToDateTime
  5699. */
  5700. double QCPAxisTickerDateTime::dateTimeToKey(const QDateTime &dateTime)
  5701. {
  5702. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5703. return dateTime.toTime_t()+dateTime.time().msec()/1000.0;
  5704. # else
  5705. return dateTime.toMSecsSinceEpoch()/1000.0;
  5706. # endif
  5707. }
  5708. /*! \overload
  5709. A convenience method which turns a QDate object into a double value that corresponds to seconds
  5710. since Epoch (1. Jan 1970, 00:00 UTC). This is the format used
  5711. as axis coordinates by QCPAxisTickerDateTime.
  5712. The returned value will be the start of the passed day of \a date, interpreted in the given \a
  5713. timeSpec.
  5714. \see keyToDateTime
  5715. */
  5716. double QCPAxisTickerDateTime::dateTimeToKey(const QDate &date, Qt::TimeSpec timeSpec)
  5717. {
  5718. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5719. return QDateTime(date, QTime(0, 0), timeSpec).toTime_t();
  5720. # elif QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  5721. return QDateTime(date, QTime(0, 0), timeSpec).toMSecsSinceEpoch()/1000.0;
  5722. # else
  5723. return date.startOfDay(timeSpec).toMSecsSinceEpoch()/1000.0;
  5724. # endif
  5725. }
  5726. /* end of 'src/axis/axistickerdatetime.cpp' */
  5727. /* including file 'src/axis/axistickertime.cpp' */
  5728. /* modified 2021-03-29T02:30:44, size 11745 */
  5729. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5730. //////////////////// QCPAxisTickerTime
  5731. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5732. /*! \class QCPAxisTickerTime
  5733. \brief Specialized axis ticker for time spans in units of milliseconds to days
  5734. \image html axisticker-time.png
  5735. This QCPAxisTicker subclass generates ticks that corresponds to time intervals.
  5736. The format of the time display in the tick labels is controlled with \ref setTimeFormat and \ref
  5737. setFieldWidth. The time coordinate is in the unit of seconds with respect to the time coordinate
  5738. zero. Unlike with QCPAxisTickerDateTime, the ticks don't correspond to a specific calendar date
  5739. and time.
  5740. The time can be displayed in milliseconds, seconds, minutes, hours and days. Depending on the
  5741. largest available unit in the format specified with \ref setTimeFormat, any time spans above will
  5742. be carried in that largest unit. So for example if the format string is "%m:%s" and a tick at
  5743. coordinate value 7815 (being 2 hours, 10 minutes and 15 seconds) is created, the resulting tick
  5744. label will show "130:15" (130 minutes, 15 seconds). If the format string is "%h:%m:%s", the hour
  5745. unit will be used and the label will thus be "02:10:15". Negative times with respect to the axis
  5746. zero will carry a leading minus sign.
  5747. The ticker can be created and assigned to an axis like this:
  5748. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation
  5749. Here is an example of a time axis providing time information in days, hours and minutes. Due to
  5750. the axis range spanning a few days and the wanted tick count (\ref setTickCount), the ticker
  5751. decided to use tick steps of 12 hours:
  5752. \image html axisticker-time2.png
  5753. The format string for this example is
  5754. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation-2
  5755. \note If you rather wish to display calendar dates and times, have a look at QCPAxisTickerDateTime
  5756. instead.
  5757. */
  5758. /*!
  5759. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5760. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5761. */
  5762. QCPAxisTickerTime::QCPAxisTickerTime() :
  5763. mTimeFormat(QLatin1String("%h:%m:%s")),
  5764. mSmallestUnit(tuSeconds),
  5765. mBiggestUnit(tuHours)
  5766. {
  5767. setTickCount(4);
  5768. mFieldWidth[tuMilliseconds] = 3;
  5769. mFieldWidth[tuSeconds] = 2;
  5770. mFieldWidth[tuMinutes] = 2;
  5771. mFieldWidth[tuHours] = 2;
  5772. mFieldWidth[tuDays] = 1;
  5773. mFormatPattern[tuMilliseconds] = QLatin1String("%z");
  5774. mFormatPattern[tuSeconds] = QLatin1String("%s");
  5775. mFormatPattern[tuMinutes] = QLatin1String("%m");
  5776. mFormatPattern[tuHours] = QLatin1String("%h");
  5777. mFormatPattern[tuDays] = QLatin1String("%d");
  5778. }
  5779. /*!
  5780. Sets the format that will be used to display time in the tick labels.
  5781. The available patterns are:
  5782. - %%z for milliseconds
  5783. - %%s for seconds
  5784. - %%m for minutes
  5785. - %%h for hours
  5786. - %%d for days
  5787. The field width (zero padding) can be controlled for each unit with \ref setFieldWidth.
  5788. The largest unit that appears in \a format will carry all the remaining time of a certain tick
  5789. coordinate, even if it overflows the natural limit of the unit. For example, if %%m is the
  5790. largest unit it might become larger than 59 in order to consume larger time values. If on the
  5791. other hand %%h is available, the minutes will wrap around to zero after 59 and the time will
  5792. carry to the hour digit.
  5793. */
  5794. void QCPAxisTickerTime::setTimeFormat(const QString &format)
  5795. {
  5796. mTimeFormat = format;
  5797. // determine smallest and biggest unit in format, to optimize unit replacement and allow biggest
  5798. // unit to consume remaining time of a tick value and grow beyond its modulo (e.g. min > 59)
  5799. mSmallestUnit = tuMilliseconds;
  5800. mBiggestUnit = tuMilliseconds;
  5801. bool hasSmallest = false;
  5802. for (int i = tuMilliseconds; i <= tuDays; ++i)
  5803. {
  5804. TimeUnit unit = static_cast<TimeUnit>(i);
  5805. if (mTimeFormat.contains(mFormatPattern.value(unit)))
  5806. {
  5807. if (!hasSmallest)
  5808. {
  5809. mSmallestUnit = unit;
  5810. hasSmallest = true;
  5811. }
  5812. mBiggestUnit = unit;
  5813. }
  5814. }
  5815. }
  5816. /*!
  5817. Sets the field widh of the specified \a unit to be \a width digits, when displayed in the tick
  5818. label. If the number for the specific unit is shorter than \a width, it will be padded with an
  5819. according number of zeros to the left in order to reach the field width.
  5820. \see setTimeFormat
  5821. */
  5822. void QCPAxisTickerTime::setFieldWidth(QCPAxisTickerTime::TimeUnit unit, int width)
  5823. {
  5824. mFieldWidth[unit] = qMax(width, 1);
  5825. }
  5826. /*! \internal
  5827. Returns the tick step appropriate for time displays, depending on the provided \a range and the
  5828. smallest available time unit in the current format (\ref setTimeFormat). For example if the unit
  5829. of seconds isn't available in the format, this method will not generate steps (like 2.5 minutes)
  5830. that require sub-minute precision to be displayed correctly.
  5831. \seebaseclassmethod
  5832. */
  5833. double QCPAxisTickerTime::getTickStep(const QCPRange &range)
  5834. {
  5835. double result = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  5836. if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
  5837. {
  5838. if (mSmallestUnit == tuMilliseconds)
  5839. result = qMax(cleanMantissa(result), 0.001); // smallest tick step is 1 millisecond
  5840. else // have no milliseconds available in format, so stick with 1 second tickstep
  5841. result = 1.0;
  5842. } else if (result < 3600*24) // below a day
  5843. {
  5844. // the filling of availableSteps seems a bit contorted but it fills in a sorted fashion and thus saves a post-fill sorting run
  5845. QVector<double> availableSteps;
  5846. // seconds range:
  5847. if (mSmallestUnit <= tuSeconds)
  5848. availableSteps << 1;
  5849. if (mSmallestUnit == tuMilliseconds)
  5850. availableSteps << 2.5; // only allow half second steps if milliseconds are there to display it
  5851. else if (mSmallestUnit == tuSeconds)
  5852. availableSteps << 2;
  5853. if (mSmallestUnit <= tuSeconds)
  5854. availableSteps << 5 << 10 << 15 << 30;
  5855. // minutes range:
  5856. if (mSmallestUnit <= tuMinutes)
  5857. availableSteps << 1*60;
  5858. if (mSmallestUnit <= tuSeconds)
  5859. availableSteps << 2.5*60; // only allow half minute steps if seconds are there to display it
  5860. else if (mSmallestUnit == tuMinutes)
  5861. availableSteps << 2*60;
  5862. if (mSmallestUnit <= tuMinutes)
  5863. availableSteps << 5*60 << 10*60 << 15*60 << 30*60;
  5864. // hours range:
  5865. if (mSmallestUnit <= tuHours)
  5866. availableSteps << 1*3600 << 2*3600 << 3*3600 << 6*3600 << 12*3600 << 24*3600;
  5867. // pick available step that is most appropriate to approximate ideal step:
  5868. result = pickClosest(result, availableSteps);
  5869. } else // more than a day, go back to normal clean mantissa algorithm but in units of days
  5870. {
  5871. const double secondsPerDay = 3600*24;
  5872. result = cleanMantissa(result/secondsPerDay)*secondsPerDay;
  5873. }
  5874. return result;
  5875. }
  5876. /*! \internal
  5877. Returns the sub tick count appropriate for the provided \a tickStep and time displays.
  5878. \seebaseclassmethod
  5879. */
  5880. int QCPAxisTickerTime::getSubTickCount(double tickStep)
  5881. {
  5882. int result = QCPAxisTicker::getSubTickCount(tickStep);
  5883. switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day range (as specified in getTickStep)
  5884. {
  5885. case 5*60: result = 4; break;
  5886. case 10*60: result = 1; break;
  5887. case 15*60: result = 2; break;
  5888. case 30*60: result = 1; break;
  5889. case 60*60: result = 3; break;
  5890. case 3600*2: result = 3; break;
  5891. case 3600*3: result = 2; break;
  5892. case 3600*6: result = 1; break;
  5893. case 3600*12: result = 3; break;
  5894. case 3600*24: result = 3; break;
  5895. }
  5896. return result;
  5897. }
  5898. /*! \internal
  5899. Returns the tick label corresponding to the provided \a tick and the configured format and field
  5900. widths (\ref setTimeFormat, \ref setFieldWidth).
  5901. \seebaseclassmethod
  5902. */
  5903. QString QCPAxisTickerTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5904. {
  5905. Q_UNUSED(precision)
  5906. Q_UNUSED(formatChar)
  5907. Q_UNUSED(locale)
  5908. bool negative = tick < 0;
  5909. if (negative) tick *= -1;
  5910. double values[tuDays+1]; // contains the msec/sec/min/... value with its respective modulo (e.g. minute 0..59)
  5911. double restValues[tuDays+1]; // contains the msec/sec/min/... value as if it's the largest available unit and thus consumes the remaining time
  5912. restValues[tuMilliseconds] = tick*1000;
  5913. values[tuMilliseconds] = modf(restValues[tuMilliseconds]/1000, &restValues[tuSeconds])*1000;
  5914. values[tuSeconds] = modf(restValues[tuSeconds]/60, &restValues[tuMinutes])*60;
  5915. values[tuMinutes] = modf(restValues[tuMinutes]/60, &restValues[tuHours])*60;
  5916. values[tuHours] = modf(restValues[tuHours]/24, &restValues[tuDays])*24;
  5917. // no need to set values[tuDays] because days are always a rest value (there is no higher unit so it consumes all remaining time)
  5918. QString result = mTimeFormat;
  5919. for (int i = mSmallestUnit; i <= mBiggestUnit; ++i)
  5920. {
  5921. TimeUnit iUnit = static_cast<TimeUnit>(i);
  5922. replaceUnit(result, iUnit, qRound(iUnit == mBiggestUnit ? restValues[iUnit] : values[iUnit]));
  5923. }
  5924. if (negative)
  5925. result.prepend(QLatin1Char('-'));
  5926. return result;
  5927. }
  5928. /*! \internal
  5929. Replaces all occurrences of the format pattern belonging to \a unit in \a text with the specified
  5930. \a value, using the field width as specified with \ref setFieldWidth for the \a unit.
  5931. */
  5932. void QCPAxisTickerTime::replaceUnit(QString &text, QCPAxisTickerTime::TimeUnit unit, int value) const
  5933. {
  5934. QString valueStr = QString::number(value);
  5935. while (valueStr.size() < mFieldWidth.value(unit))
  5936. valueStr.prepend(QLatin1Char('0'));
  5937. text.replace(mFormatPattern.value(unit), valueStr);
  5938. }
  5939. /* end of 'src/axis/axistickertime.cpp' */
  5940. /* including file 'src/axis/axistickerfixed.cpp' */
  5941. /* modified 2021-03-29T02:30:44, size 5575 */
  5942. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5943. //////////////////// QCPAxisTickerFixed
  5944. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5945. /*! \class QCPAxisTickerFixed
  5946. \brief Specialized axis ticker with a fixed tick step
  5947. \image html axisticker-fixed.png
  5948. This QCPAxisTicker subclass generates ticks with a fixed tick step set with \ref setTickStep. It
  5949. is also possible to allow integer multiples and integer powers of the specified tick step with
  5950. \ref setScaleStrategy.
  5951. A typical application of this ticker is to make an axis only display integers, by setting the
  5952. tick step of the ticker to 1.0 and the scale strategy to \ref ssMultiples.
  5953. Another case is when a certain number has a special meaning and axis ticks should only appear at
  5954. multiples of that value. In this case you might also want to consider \ref QCPAxisTickerPi
  5955. because despite the name it is not limited to only pi symbols/values.
  5956. The ticker can be created and assigned to an axis like this:
  5957. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerfixed-creation
  5958. */
  5959. /*!
  5960. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5961. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5962. */
  5963. QCPAxisTickerFixed::QCPAxisTickerFixed() :
  5964. mTickStep(1.0),
  5965. mScaleStrategy(ssNone)
  5966. {
  5967. }
  5968. /*!
  5969. Sets the fixed tick interval to \a step.
  5970. The axis ticker will only use this tick step when generating axis ticks. This might cause a very
  5971. high tick density and overlapping labels if the axis range is zoomed out. Using \ref
  5972. setScaleStrategy it is possible to relax the fixed step and also allow multiples or powers of \a
  5973. step. This will enable the ticker to reduce the number of ticks to a reasonable amount (see \ref
  5974. setTickCount).
  5975. */
  5976. void QCPAxisTickerFixed::setTickStep(double step)
  5977. {
  5978. if (step > 0)
  5979. mTickStep = step;
  5980. else
  5981. qDebug() << Q_FUNC_INFO << "tick step must be greater than zero:" << step;
  5982. }
  5983. /*!
  5984. Sets whether the specified tick step (\ref setTickStep) is absolutely fixed or whether
  5985. modifications may be applied to it before calculating the finally used tick step, such as
  5986. permitting multiples or powers. See \ref ScaleStrategy for details.
  5987. The default strategy is \ref ssNone, which means the tick step is absolutely fixed.
  5988. */
  5989. void QCPAxisTickerFixed::setScaleStrategy(QCPAxisTickerFixed::ScaleStrategy strategy)
  5990. {
  5991. mScaleStrategy = strategy;
  5992. }
  5993. /*! \internal
  5994. Determines the actually used tick step from the specified tick step and scale strategy (\ref
  5995. setTickStep, \ref setScaleStrategy).
  5996. This method either returns the specified tick step exactly, or, if the scale strategy is not \ref
  5997. ssNone, a modification of it to allow varying the number of ticks in the current axis range.
  5998. \seebaseclassmethod
  5999. */
  6000. double QCPAxisTickerFixed::getTickStep(const QCPRange &range)
  6001. {
  6002. switch (mScaleStrategy)
  6003. {
  6004. case ssNone:
  6005. {
  6006. return mTickStep;
  6007. }
  6008. case ssMultiples:
  6009. {
  6010. double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  6011. if (exactStep < mTickStep)
  6012. return mTickStep;
  6013. else
  6014. return qint64(cleanMantissa(exactStep/mTickStep)+0.5)*mTickStep;
  6015. }
  6016. case ssPowers:
  6017. {
  6018. double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  6019. return qPow(mTickStep, int(qLn(exactStep)/qLn(mTickStep)+0.5));
  6020. }
  6021. }
  6022. return mTickStep;
  6023. }
  6024. /* end of 'src/axis/axistickerfixed.cpp' */
  6025. /* including file 'src/axis/axistickertext.cpp' */
  6026. /* modified 2021-03-29T02:30:44, size 8742 */
  6027. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6028. //////////////////// QCPAxisTickerText
  6029. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6030. /*! \class QCPAxisTickerText
  6031. \brief Specialized axis ticker which allows arbitrary labels at specified coordinates
  6032. \image html axisticker-text.png
  6033. This QCPAxisTicker subclass generates ticks which can be directly specified by the user as
  6034. coordinates and associated strings. They can be passed as a whole with \ref setTicks or one at a
  6035. time with \ref addTick. Alternatively you can directly access the internal storage via \ref ticks
  6036. and modify the tick/label data there.
  6037. This is useful for cases where the axis represents categories rather than numerical values.
  6038. If you are updating the ticks of this ticker regularly and in a dynamic fasion (e.g. dependent on
  6039. the axis range), it is a sign that you should probably create an own ticker by subclassing
  6040. QCPAxisTicker, instead of using this one.
  6041. The ticker can be created and assigned to an axis like this:
  6042. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertext-creation
  6043. */
  6044. /* start of documentation of inline functions */
  6045. /*! \fn QMap<double, QString> &QCPAxisTickerText::ticks()
  6046. Returns a non-const reference to the internal map which stores the tick coordinates and their
  6047. labels.
  6048. You can access the map directly in order to add, remove or manipulate ticks, as an alternative to
  6049. using the methods provided by QCPAxisTickerText, such as \ref setTicks and \ref addTick.
  6050. */
  6051. /* end of documentation of inline functions */
  6052. /*!
  6053. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  6054. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  6055. */
  6056. QCPAxisTickerText::QCPAxisTickerText() :
  6057. mSubTickCount(0)
  6058. {
  6059. }
  6060. /*! \overload
  6061. Sets the ticks that shall appear on the axis. The map key of \a ticks corresponds to the axis
  6062. coordinate, and the map value is the string that will appear as tick label.
  6063. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6064. getter.
  6065. \see addTicks, addTick, clear
  6066. */
  6067. void QCPAxisTickerText::setTicks(const QMap<double, QString> &ticks)
  6068. {
  6069. mTicks = ticks;
  6070. }
  6071. /*! \overload
  6072. Sets the ticks that shall appear on the axis. The entries of \a positions correspond to the axis
  6073. coordinates, and the entries of \a labels are the respective strings that will appear as tick
  6074. labels.
  6075. \see addTicks, addTick, clear
  6076. */
  6077. void QCPAxisTickerText::setTicks(const QVector<double> &positions, const QVector<QString> &labels)
  6078. {
  6079. clear();
  6080. addTicks(positions, labels);
  6081. }
  6082. /*!
  6083. Sets the number of sub ticks that shall appear between ticks. For QCPAxisTickerText, there is no
  6084. automatic sub tick count calculation. So if sub ticks are needed, they must be configured with this
  6085. method.
  6086. */
  6087. void QCPAxisTickerText::setSubTickCount(int subTicks)
  6088. {
  6089. if (subTicks >= 0)
  6090. mSubTickCount = subTicks;
  6091. else
  6092. qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
  6093. }
  6094. /*!
  6095. Clears all ticks.
  6096. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6097. getter.
  6098. \see setTicks, addTicks, addTick
  6099. */
  6100. void QCPAxisTickerText::clear()
  6101. {
  6102. mTicks.clear();
  6103. }
  6104. /*!
  6105. Adds a single tick to the axis at the given axis coordinate \a position, with the provided tick \a
  6106. label.
  6107. \see addTicks, setTicks, clear
  6108. */
  6109. void QCPAxisTickerText::addTick(double position, const QString &label)
  6110. {
  6111. mTicks.insert(position, label);
  6112. }
  6113. /*! \overload
  6114. Adds the provided \a ticks to the ones already existing. The map key of \a ticks corresponds to
  6115. the axis coordinate, and the map value is the string that will appear as tick label.
  6116. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6117. getter.
  6118. \see addTick, setTicks, clear
  6119. */
  6120. void QCPAxisTickerText::addTicks(const QMap<double, QString> &ticks)
  6121. {
  6122. #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
  6123. mTicks.unite(ticks);
  6124. #else
  6125. mTicks.insert(ticks);
  6126. #endif
  6127. }
  6128. /*! \overload
  6129. Adds the provided ticks to the ones already existing. The entries of \a positions correspond to
  6130. the axis coordinates, and the entries of \a labels are the respective strings that will appear as
  6131. tick labels.
  6132. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6133. getter.
  6134. \see addTick, setTicks, clear
  6135. */
  6136. void QCPAxisTickerText::addTicks(const QVector<double> &positions, const QVector<QString> &labels)
  6137. {
  6138. if (positions.size() != labels.size())
  6139. qDebug() << Q_FUNC_INFO << "passed unequal length vectors for positions and labels:" << positions.size() << labels.size();
  6140. int n = qMin(positions.size(), labels.size());
  6141. for (int i=0; i<n; ++i)
  6142. mTicks.insert(positions.at(i), labels.at(i));
  6143. }
  6144. /*!
  6145. Since the tick coordinates are provided externally, this method implementation does nothing.
  6146. \seebaseclassmethod
  6147. */
  6148. double QCPAxisTickerText::getTickStep(const QCPRange &range)
  6149. {
  6150. // text axis ticker has manual tick positions, so doesn't need this method
  6151. Q_UNUSED(range)
  6152. return 1.0;
  6153. }
  6154. /*!
  6155. Returns the sub tick count that was configured with \ref setSubTickCount.
  6156. \seebaseclassmethod
  6157. */
  6158. int QCPAxisTickerText::getSubTickCount(double tickStep)
  6159. {
  6160. Q_UNUSED(tickStep)
  6161. return mSubTickCount;
  6162. }
  6163. /*!
  6164. Returns the tick label which corresponds to the key \a tick in the internal tick storage. Since
  6165. the labels are provided externally, \a locale, \a formatChar, and \a precision are ignored.
  6166. \seebaseclassmethod
  6167. */
  6168. QString QCPAxisTickerText::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  6169. {
  6170. Q_UNUSED(locale)
  6171. Q_UNUSED(formatChar)
  6172. Q_UNUSED(precision)
  6173. return mTicks.value(tick);
  6174. }
  6175. /*!
  6176. Returns the externally provided tick coordinates which are in the specified \a range. If
  6177. available, one tick above and below the range is provided in addition, to allow possible sub tick
  6178. calculation. The parameter \a tickStep is ignored.
  6179. \seebaseclassmethod
  6180. */
  6181. QVector<double> QCPAxisTickerText::createTickVector(double tickStep, const QCPRange &range)
  6182. {
  6183. Q_UNUSED(tickStep)
  6184. QVector<double> result;
  6185. if (mTicks.isEmpty())
  6186. return result;
  6187. QMap<double, QString>::const_iterator start = mTicks.lowerBound(range.lower);
  6188. QMap<double, QString>::const_iterator end = mTicks.upperBound(range.upper);
  6189. // this method should try to give one tick outside of range so proper subticks can be generated:
  6190. if (start != mTicks.constBegin()) --start;
  6191. if (end != mTicks.constEnd()) ++end;
  6192. for (QMap<double, QString>::const_iterator it = start; it != end; ++it)
  6193. result.append(it.key());
  6194. return result;
  6195. }
  6196. /* end of 'src/axis/axistickertext.cpp' */
  6197. /* including file 'src/axis/axistickerpi.cpp' */
  6198. /* modified 2021-03-29T02:30:44, size 11177 */
  6199. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6200. //////////////////// QCPAxisTickerPi
  6201. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6202. /*! \class QCPAxisTickerPi
  6203. \brief Specialized axis ticker to display ticks in units of an arbitrary constant, for example pi
  6204. \image html axisticker-pi.png
  6205. This QCPAxisTicker subclass generates ticks that are expressed with respect to a given symbolic
  6206. constant with a numerical value specified with \ref setPiValue and an appearance in the tick
  6207. labels specified with \ref setPiSymbol.
  6208. Ticks may be generated at fractions of the symbolic constant. How these fractions appear in the
  6209. tick label can be configured with \ref setFractionStyle.
  6210. The ticker can be created and assigned to an axis like this:
  6211. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerpi-creation
  6212. */
  6213. /*!
  6214. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  6215. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  6216. */
  6217. QCPAxisTickerPi::QCPAxisTickerPi() :
  6218. mPiSymbol(QLatin1String(" ")+QChar(0x03C0)),
  6219. mPiValue(M_PI),
  6220. mPeriodicity(0),
  6221. mFractionStyle(fsUnicodeFractions),
  6222. mPiTickStep(0)
  6223. {
  6224. setTickCount(4);
  6225. }
  6226. /*!
  6227. Sets how the symbol part (which is always a suffix to the number) shall appear in the axis tick
  6228. label.
  6229. If a space shall appear between the number and the symbol, make sure the space is contained in \a
  6230. symbol.
  6231. */
  6232. void QCPAxisTickerPi::setPiSymbol(QString symbol)
  6233. {
  6234. mPiSymbol = symbol;
  6235. }
  6236. /*!
  6237. Sets the numerical value that the symbolic constant has.
  6238. This will be used to place the appropriate fractions of the symbol at the respective axis
  6239. coordinates.
  6240. */
  6241. void QCPAxisTickerPi::setPiValue(double pi)
  6242. {
  6243. mPiValue = pi;
  6244. }
  6245. /*!
  6246. Sets whether the axis labels shall appear periodicly and if so, at which multiplicity of the
  6247. symbolic constant.
  6248. To disable periodicity, set \a multiplesOfPi to zero.
  6249. For example, an axis that identifies 0 with 2pi would set \a multiplesOfPi to two.
  6250. */
  6251. void QCPAxisTickerPi::setPeriodicity(int multiplesOfPi)
  6252. {
  6253. mPeriodicity = qAbs(multiplesOfPi);
  6254. }
  6255. /*!
  6256. Sets how the numerical/fractional part preceding the symbolic constant is displayed in tick
  6257. labels. See \ref FractionStyle for the various options.
  6258. */
  6259. void QCPAxisTickerPi::setFractionStyle(QCPAxisTickerPi::FractionStyle style)
  6260. {
  6261. mFractionStyle = style;
  6262. }
  6263. /*! \internal
  6264. Returns the tick step, using the constant's value (\ref setPiValue) as base unit. In consequence
  6265. the numerical/fractional part preceding the symbolic constant is made to have a readable
  6266. mantissa.
  6267. \seebaseclassmethod
  6268. */
  6269. double QCPAxisTickerPi::getTickStep(const QCPRange &range)
  6270. {
  6271. mPiTickStep = range.size()/mPiValue/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  6272. mPiTickStep = cleanMantissa(mPiTickStep);
  6273. return mPiTickStep*mPiValue;
  6274. }
  6275. /*! \internal
  6276. Returns the sub tick count, using the constant's value (\ref setPiValue) as base unit. In
  6277. consequence the sub ticks divide the numerical/fractional part preceding the symbolic constant
  6278. reasonably, and not the total tick coordinate.
  6279. \seebaseclassmethod
  6280. */
  6281. int QCPAxisTickerPi::getSubTickCount(double tickStep)
  6282. {
  6283. return QCPAxisTicker::getSubTickCount(tickStep/mPiValue);
  6284. }
  6285. /*! \internal
  6286. Returns the tick label as a fractional/numerical part and a symbolic string as suffix. The
  6287. formatting of the fraction is done according to the specified \ref setFractionStyle. The appended
  6288. symbol is specified with \ref setPiSymbol.
  6289. \seebaseclassmethod
  6290. */
  6291. QString QCPAxisTickerPi::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  6292. {
  6293. double tickInPis = tick/mPiValue;
  6294. if (mPeriodicity > 0)
  6295. tickInPis = fmod(tickInPis, mPeriodicity);
  6296. if (mFractionStyle != fsFloatingPoint && mPiTickStep > 0.09 && mPiTickStep < 50)
  6297. {
  6298. // simply construct fraction from decimal like 1.234 -> 1234/1000 and then simplify fraction, smaller digits are irrelevant due to mPiTickStep conditional above
  6299. int denominator = 1000;
  6300. int numerator = qRound(tickInPis*denominator);
  6301. simplifyFraction(numerator, denominator);
  6302. if (qAbs(numerator) == 1 && denominator == 1)
  6303. return (numerator < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
  6304. else if (numerator == 0)
  6305. return QLatin1String("0");
  6306. else
  6307. return fractionToString(numerator, denominator) + mPiSymbol;
  6308. } else
  6309. {
  6310. if (qFuzzyIsNull(tickInPis))
  6311. return QLatin1String("0");
  6312. else if (qFuzzyCompare(qAbs(tickInPis), 1.0))
  6313. return (tickInPis < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
  6314. else
  6315. return QCPAxisTicker::getTickLabel(tickInPis, locale, formatChar, precision) + mPiSymbol;
  6316. }
  6317. }
  6318. /*! \internal
  6319. Takes the fraction given by \a numerator and \a denominator and modifies the values to make sure
  6320. the fraction is in irreducible form, i.e. numerator and denominator don't share any common
  6321. factors which could be cancelled.
  6322. */
  6323. void QCPAxisTickerPi::simplifyFraction(int &numerator, int &denominator) const
  6324. {
  6325. if (numerator == 0 || denominator == 0)
  6326. return;
  6327. int num = numerator;
  6328. int denom = denominator;
  6329. while (denom != 0) // euclidean gcd algorithm
  6330. {
  6331. int oldDenom = denom;
  6332. denom = num % denom;
  6333. num = oldDenom;
  6334. }
  6335. // num is now gcd of numerator and denominator
  6336. numerator /= num;
  6337. denominator /= num;
  6338. }
  6339. /*! \internal
  6340. Takes the fraction given by \a numerator and \a denominator and returns a string representation.
  6341. The result depends on the configured fraction style (\ref setFractionStyle).
  6342. This method is used to format the numerical/fractional part when generating tick labels. It
  6343. simplifies the passed fraction to an irreducible form using \ref simplifyFraction and factors out
  6344. any integer parts of the fraction (e.g. "10/4" becomes "2 1/2").
  6345. */
  6346. QString QCPAxisTickerPi::fractionToString(int numerator, int denominator) const
  6347. {
  6348. if (denominator == 0)
  6349. {
  6350. qDebug() << Q_FUNC_INFO << "called with zero denominator";
  6351. return QString();
  6352. }
  6353. if (mFractionStyle == fsFloatingPoint) // should never be the case when calling this function
  6354. {
  6355. qDebug() << Q_FUNC_INFO << "shouldn't be called with fraction style fsDecimal";
  6356. return QString::number(numerator/double(denominator)); // failsafe
  6357. }
  6358. int sign = numerator*denominator < 0 ? -1 : 1;
  6359. numerator = qAbs(numerator);
  6360. denominator = qAbs(denominator);
  6361. if (denominator == 1)
  6362. {
  6363. return QString::number(sign*numerator);
  6364. } else
  6365. {
  6366. int integerPart = numerator/denominator;
  6367. int remainder = numerator%denominator;
  6368. if (remainder == 0)
  6369. {
  6370. return QString::number(sign*integerPart);
  6371. } else
  6372. {
  6373. if (mFractionStyle == fsAsciiFractions)
  6374. {
  6375. return QString(QLatin1String("%1%2%3/%4"))
  6376. .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
  6377. .arg(integerPart > 0 ? QString::number(integerPart)+QLatin1String(" ") : QString(QLatin1String("")))
  6378. .arg(remainder)
  6379. .arg(denominator);
  6380. } else if (mFractionStyle == fsUnicodeFractions)
  6381. {
  6382. return QString(QLatin1String("%1%2%3"))
  6383. .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
  6384. .arg(integerPart > 0 ? QString::number(integerPart) : QLatin1String(""))
  6385. .arg(unicodeFraction(remainder, denominator));
  6386. }
  6387. }
  6388. }
  6389. return QString();
  6390. }
  6391. /*! \internal
  6392. Returns the unicode string representation of the fraction given by \a numerator and \a
  6393. denominator. This is the representation used in \ref fractionToString when the fraction style
  6394. (\ref setFractionStyle) is \ref fsUnicodeFractions.
  6395. This method doesn't use the single-character common fractions but builds each fraction from a
  6396. superscript unicode number, the unicode fraction character, and a subscript unicode number.
  6397. */
  6398. QString QCPAxisTickerPi::unicodeFraction(int numerator, int denominator) const
  6399. {
  6400. return unicodeSuperscript(numerator)+QChar(0x2044)+unicodeSubscript(denominator);
  6401. }
  6402. /*! \internal
  6403. Returns the unicode string representing \a number as superscript. This is used to build
  6404. unicode fractions in \ref unicodeFraction.
  6405. */
  6406. QString QCPAxisTickerPi::unicodeSuperscript(int number) const
  6407. {
  6408. if (number == 0)
  6409. return QString(QChar(0x2070));
  6410. QString result;
  6411. while (number > 0)
  6412. {
  6413. const int digit = number%10;
  6414. switch (digit)
  6415. {
  6416. case 1: { result.prepend(QChar(0x00B9)); break; }
  6417. case 2: { result.prepend(QChar(0x00B2)); break; }
  6418. case 3: { result.prepend(QChar(0x00B3)); break; }
  6419. default: { result.prepend(QChar(0x2070+digit)); break; }
  6420. }
  6421. number /= 10;
  6422. }
  6423. return result;
  6424. }
  6425. /*! \internal
  6426. Returns the unicode string representing \a number as subscript. This is used to build unicode
  6427. fractions in \ref unicodeFraction.
  6428. */
  6429. QString QCPAxisTickerPi::unicodeSubscript(int number) const
  6430. {
  6431. if (number == 0)
  6432. return QString(QChar(0x2080));
  6433. QString result;
  6434. while (number > 0)
  6435. {
  6436. result.prepend(QChar(0x2080+number%10));
  6437. number /= 10;
  6438. }
  6439. return result;
  6440. }
  6441. /* end of 'src/axis/axistickerpi.cpp' */
  6442. /* including file 'src/axis/axistickerlog.cpp' */
  6443. /* modified 2021-03-29T02:30:44, size 7890 */
  6444. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6445. //////////////////// QCPAxisTickerLog
  6446. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6447. /*! \class QCPAxisTickerLog
  6448. \brief Specialized axis ticker suited for logarithmic axes
  6449. \image html axisticker-log.png
  6450. This QCPAxisTicker subclass generates ticks with unequal tick intervals suited for logarithmic
  6451. axis scales. The ticks are placed at powers of the specified log base (\ref setLogBase).
  6452. Especially in the case of a log base equal to 10 (the default), it might be desirable to have
  6453. tick labels in the form of powers of ten without mantissa display. To achieve this, set the
  6454. number precision (\ref QCPAxis::setNumberPrecision) to zero and the number format (\ref
  6455. QCPAxis::setNumberFormat) to scientific (exponential) display with beautifully typeset decimal
  6456. powers, so a format string of <tt>"eb"</tt>. This will result in the following axis tick labels:
  6457. \image html axisticker-log-powers.png
  6458. The ticker can be created and assigned to an axis like this:
  6459. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerlog-creation
  6460. Note that the nature of logarithmic ticks imply that there exists a smallest possible tick step,
  6461. corresponding to one multiplication by the log base. If the user zooms in further than that, no
  6462. new ticks would appear, leading to very sparse or even no axis ticks on the axis. To prevent this
  6463. situation, this ticker falls back to regular tick generation if the axis range would be covered
  6464. by too few logarithmically placed ticks.
  6465. */
  6466. /*!
  6467. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  6468. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  6469. */
  6470. QCPAxisTickerLog::QCPAxisTickerLog() :
  6471. mLogBase(10.0),
  6472. mSubTickCount(8), // generates 10 intervals
  6473. mLogBaseLnInv(1.0/qLn(mLogBase))
  6474. {
  6475. }
  6476. /*!
  6477. Sets the logarithm base used for tick coordinate generation. The ticks will be placed at integer
  6478. powers of \a base.
  6479. */
  6480. void QCPAxisTickerLog::setLogBase(double base)
  6481. {
  6482. if (base > 0)
  6483. {
  6484. mLogBase = base;
  6485. mLogBaseLnInv = 1.0/qLn(mLogBase);
  6486. } else
  6487. qDebug() << Q_FUNC_INFO << "log base has to be greater than zero:" << base;
  6488. }
  6489. /*!
  6490. Sets the number of sub ticks in a tick interval. Within each interval, the sub ticks are spaced
  6491. linearly to provide a better visual guide, so the sub tick density increases toward the higher
  6492. tick.
  6493. Note that \a subTicks is the number of sub ticks (not sub intervals) in one tick interval. So in
  6494. the case of logarithm base 10 an intuitive sub tick spacing would be achieved with eight sub
  6495. ticks (the default). This means e.g. between the ticks 10 and 100 there will be eight ticks,
  6496. namely at 20, 30, 40, 50, 60, 70, 80 and 90.
  6497. */
  6498. void QCPAxisTickerLog::setSubTickCount(int subTicks)
  6499. {
  6500. if (subTicks >= 0)
  6501. mSubTickCount = subTicks;
  6502. else
  6503. qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
  6504. }
  6505. /*! \internal
  6506. Returns the sub tick count specified in \ref setSubTickCount. For QCPAxisTickerLog, there is no
  6507. automatic sub tick count calculation necessary.
  6508. \seebaseclassmethod
  6509. */
  6510. int QCPAxisTickerLog::getSubTickCount(double tickStep)
  6511. {
  6512. Q_UNUSED(tickStep)
  6513. return mSubTickCount;
  6514. }
  6515. /*! \internal
  6516. Creates ticks with a spacing given by the logarithm base and an increasing integer power in the
  6517. provided \a range. The step in which the power increases tick by tick is chosen in order to keep
  6518. the total number of ticks as close as possible to the tick count (\ref setTickCount).
  6519. The parameter \a tickStep is ignored for the normal logarithmic ticker generation. Only when
  6520. zoomed in very far such that not enough logarithmically placed ticks would be visible, this
  6521. function falls back to the regular QCPAxisTicker::createTickVector, which then uses \a tickStep.
  6522. \seebaseclassmethod
  6523. */
  6524. QVector<double> QCPAxisTickerLog::createTickVector(double tickStep, const QCPRange &range)
  6525. {
  6526. QVector<double> result;
  6527. if (range.lower > 0 && range.upper > 0) // positive range
  6528. {
  6529. const double baseTickCount = qLn(range.upper/range.lower)*mLogBaseLnInv;
  6530. if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation
  6531. return QCPAxisTicker::createTickVector(tickStep, range);
  6532. const double exactPowerStep = baseTickCount/double(mTickCount+1e-10);
  6533. const double newLogBase = qPow(mLogBase, qMax(int(cleanMantissa(exactPowerStep)), 1));
  6534. double currentTick = qPow(newLogBase, qFloor(qLn(range.lower)/qLn(newLogBase)));
  6535. result.append(currentTick);
  6536. while (currentTick < range.upper && currentTick > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  6537. {
  6538. currentTick *= newLogBase;
  6539. result.append(currentTick);
  6540. }
  6541. } else if (range.lower < 0 && range.upper < 0) // negative range
  6542. {
  6543. const double baseTickCount = qLn(range.lower/range.upper)*mLogBaseLnInv;
  6544. if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation
  6545. return QCPAxisTicker::createTickVector(tickStep, range);
  6546. const double exactPowerStep = baseTickCount/double(mTickCount+1e-10);
  6547. const double newLogBase = qPow(mLogBase, qMax(int(cleanMantissa(exactPowerStep)), 1));
  6548. double currentTick = -qPow(newLogBase, qCeil(qLn(-range.lower)/qLn(newLogBase)));
  6549. result.append(currentTick);
  6550. while (currentTick < range.upper && currentTick < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  6551. {
  6552. currentTick /= newLogBase;
  6553. result.append(currentTick);
  6554. }
  6555. } else // invalid range for logarithmic scale, because lower and upper have different sign
  6556. {
  6557. qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << range.lower << ".." << range.upper;
  6558. }
  6559. return result;
  6560. }
  6561. /* end of 'src/axis/axistickerlog.cpp' */
  6562. /* including file 'src/axis/axis.cpp' */
  6563. /* modified 2021-03-29T02:30:44, size 99883 */
  6564. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6565. //////////////////// QCPGrid
  6566. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6567. /*! \class QCPGrid
  6568. \brief Responsible for drawing the grid of a QCPAxis.
  6569. This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the
  6570. grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref
  6571. QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself.
  6572. The axis and grid drawing was split into two classes to allow them to be placed on different
  6573. layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid
  6574. in the background and the axes in the foreground, and any plottables/items in between. This
  6575. described situation is the default setup, see the QCPLayer documentation.
  6576. */
  6577. /*!
  6578. Creates a QCPGrid instance and sets default values.
  6579. You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid.
  6580. */
  6581. QCPGrid::QCPGrid(QCPAxis *parentAxis) :
  6582. QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
  6583. mSubGridVisible{},
  6584. mAntialiasedSubGrid{},
  6585. mAntialiasedZeroLine{},
  6586. mParentAxis(parentAxis)
  6587. {
  6588. // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called
  6589. setParent(parentAxis);
  6590. setPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  6591. setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  6592. setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
  6593. setSubGridVisible(false);
  6594. setAntialiased(false);
  6595. setAntialiasedSubGrid(false);
  6596. setAntialiasedZeroLine(false);
  6597. }
  6598. /*!
  6599. Sets whether grid lines at sub tick marks are drawn.
  6600. \see setSubGridPen
  6601. */
  6602. void QCPGrid::setSubGridVisible(bool visible)
  6603. {
  6604. mSubGridVisible = visible;
  6605. }
  6606. /*!
  6607. Sets whether sub grid lines are drawn antialiased.
  6608. */
  6609. void QCPGrid::setAntialiasedSubGrid(bool enabled)
  6610. {
  6611. mAntialiasedSubGrid = enabled;
  6612. }
  6613. /*!
  6614. Sets whether zero lines are drawn antialiased.
  6615. */
  6616. void QCPGrid::setAntialiasedZeroLine(bool enabled)
  6617. {
  6618. mAntialiasedZeroLine = enabled;
  6619. }
  6620. /*!
  6621. Sets the pen with which (major) grid lines are drawn.
  6622. */
  6623. void QCPGrid::setPen(const QPen &pen)
  6624. {
  6625. mPen = pen;
  6626. }
  6627. /*!
  6628. Sets the pen with which sub grid lines are drawn.
  6629. */
  6630. void QCPGrid::setSubGridPen(const QPen &pen)
  6631. {
  6632. mSubGridPen = pen;
  6633. }
  6634. /*!
  6635. Sets the pen with which zero lines are drawn.
  6636. Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid
  6637. lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen.
  6638. */
  6639. void QCPGrid::setZeroLinePen(const QPen &pen)
  6640. {
  6641. mZeroLinePen = pen;
  6642. }
  6643. /*! \internal
  6644. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6645. before drawing the major grid lines.
  6646. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  6647. This function takes into account the local setting of the antialiasing flag as well as the
  6648. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6649. QCustomPlot::setNotAntialiasedElements.
  6650. \see setAntialiased
  6651. */
  6652. void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
  6653. {
  6654. applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
  6655. }
  6656. /*! \internal
  6657. Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
  6658. over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
  6659. */
  6660. void QCPGrid::draw(QCPPainter *painter)
  6661. {
  6662. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6663. if (mParentAxis->subTicks() && mSubGridVisible)
  6664. drawSubGridLines(painter);
  6665. drawGridLines(painter);
  6666. }
  6667. /*! \internal
  6668. Draws the main grid lines and possibly a zero line with the specified painter.
  6669. This is a helper function called by \ref draw.
  6670. */
  6671. void QCPGrid::drawGridLines(QCPPainter *painter) const
  6672. {
  6673. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6674. const int tickCount = mParentAxis->mTickVector.size();
  6675. double t; // helper variable, result of coordinate-to-pixel transforms
  6676. if (mParentAxis->orientation() == Qt::Horizontal)
  6677. {
  6678. // draw zeroline:
  6679. int zeroLineIndex = -1;
  6680. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
  6681. {
  6682. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  6683. painter->setPen(mZeroLinePen);
  6684. double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero
  6685. for (int i=0; i<tickCount; ++i)
  6686. {
  6687. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
  6688. {
  6689. zeroLineIndex = i;
  6690. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  6691. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6692. break;
  6693. }
  6694. }
  6695. }
  6696. // draw grid lines:
  6697. applyDefaultAntialiasingHint(painter);
  6698. painter->setPen(mPen);
  6699. for (int i=0; i<tickCount; ++i)
  6700. {
  6701. if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
  6702. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  6703. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6704. }
  6705. } else
  6706. {
  6707. // draw zeroline:
  6708. int zeroLineIndex = -1;
  6709. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
  6710. {
  6711. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  6712. painter->setPen(mZeroLinePen);
  6713. double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero
  6714. for (int i=0; i<tickCount; ++i)
  6715. {
  6716. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
  6717. {
  6718. zeroLineIndex = i;
  6719. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  6720. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6721. break;
  6722. }
  6723. }
  6724. }
  6725. // draw grid lines:
  6726. applyDefaultAntialiasingHint(painter);
  6727. painter->setPen(mPen);
  6728. for (int i=0; i<tickCount; ++i)
  6729. {
  6730. if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
  6731. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  6732. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6733. }
  6734. }
  6735. }
  6736. /*! \internal
  6737. Draws the sub grid lines with the specified painter.
  6738. This is a helper function called by \ref draw.
  6739. */
  6740. void QCPGrid::drawSubGridLines(QCPPainter *painter) const
  6741. {
  6742. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6743. applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid);
  6744. double t; // helper variable, result of coordinate-to-pixel transforms
  6745. painter->setPen(mSubGridPen);
  6746. if (mParentAxis->orientation() == Qt::Horizontal)
  6747. {
  6748. foreach (double tickCoord, mParentAxis->mSubTickVector)
  6749. {
  6750. t = mParentAxis->coordToPixel(tickCoord); // x
  6751. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6752. }
  6753. } else
  6754. {
  6755. foreach (double tickCoord, mParentAxis->mSubTickVector)
  6756. {
  6757. t = mParentAxis->coordToPixel(tickCoord); // y
  6758. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6759. }
  6760. }
  6761. }
  6762. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6763. //////////////////// QCPAxis
  6764. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6765. /*! \class QCPAxis
  6766. \brief Manages a single axis inside a QCustomPlot.
  6767. Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via
  6768. QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and
  6769. QCustomPlot::yAxis2 (right).
  6770. Axes are always part of an axis rect, see QCPAxisRect.
  6771. \image html AxisNamesOverview.png
  6772. <center>Naming convention of axis parts</center>
  6773. \n
  6774. \image html AxisRectSpacingOverview.png
  6775. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line
  6776. on the left represents the QCustomPlot widget border.</center>
  6777. Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
  6778. tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
  6779. the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
  6780. documentation of QCPAxisTicker.
  6781. */
  6782. /* start of documentation of inline functions */
  6783. /*! \fn Qt::Orientation QCPAxis::orientation() const
  6784. Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced
  6785. from the axis type (left, top, right or bottom).
  6786. \see orientation(AxisType type), pixelOrientation
  6787. */
  6788. /*! \fn QCPGrid *QCPAxis::grid() const
  6789. Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the
  6790. grid is displayed.
  6791. */
  6792. /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type)
  6793. Returns the orientation of the specified axis type
  6794. \see orientation(), pixelOrientation
  6795. */
  6796. /*! \fn int QCPAxis::pixelOrientation() const
  6797. Returns which direction points towards higher coordinate values/keys, in pixel space.
  6798. This method returns either 1 or -1. If it returns 1, then going in the positive direction along
  6799. the orientation of the axis in pixels corresponds to going from lower to higher axis coordinates.
  6800. On the other hand, if this method returns -1, going to smaller pixel values corresponds to going
  6801. from lower to higher axis coordinates.
  6802. For example, this is useful to easily shift axis coordinates by a certain amount given in pixels,
  6803. without having to care about reversed or vertically aligned axes:
  6804. \code
  6805. double newKey = keyAxis->pixelToCoord(keyAxis->coordToPixel(oldKey)+10*keyAxis->pixelOrientation());
  6806. \endcode
  6807. \a newKey will then contain a key that is ten pixels towards higher keys, starting from \a oldKey.
  6808. */
  6809. /*! \fn QSharedPointer<QCPAxisTicker> QCPAxis::ticker() const
  6810. Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
  6811. responsible for generating the tick positions and tick labels of this axis. You can access the
  6812. \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
  6813. (\ref QCPAxisTicker::setTickCount).
  6814. You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
  6815. the documentation there. A new axis ticker can be set with \ref setTicker.
  6816. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  6817. ticker simply by passing the same shared pointer to multiple axes.
  6818. \see setTicker
  6819. */
  6820. /* end of documentation of inline functions */
  6821. /* start of documentation of signals */
  6822. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange)
  6823. This signal is emitted when the range of this axis has changed. You can connect it to the \ref
  6824. setRange slot of another axis to communicate the new range to the other axis, in order for it to
  6825. be synchronized.
  6826. You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
  6827. This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
  6828. range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
  6829. slot would limit the x axis to ranges between 0 and 10:
  6830. \code
  6831. customPlot->xAxis->setRange(newRange.bounded(0, 10))
  6832. \endcode
  6833. */
  6834. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
  6835. \overload
  6836. Additionally to the new range, this signal also provides the previous range held by the axis as
  6837. \a oldRange.
  6838. */
  6839. /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType);
  6840. This signal is emitted when the scale type changes, by calls to \ref setScaleType
  6841. */
  6842. /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection)
  6843. This signal is emitted when the selection state of this axis has changed, either by user interaction
  6844. or by a direct call to \ref setSelectedParts.
  6845. */
  6846. /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts);
  6847. This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
  6848. */
  6849. /* end of documentation of signals */
  6850. /*!
  6851. Constructs an Axis instance of Type \a type for the axis rect \a parent.
  6852. Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
  6853. them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
  6854. create them manually and then inject them also via \ref QCPAxisRect::addAxis.
  6855. */
  6856. QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) :
  6857. QCPLayerable(parent->parentPlot(), QString(), parent),
  6858. // axis base:
  6859. mAxisType(type),
  6860. mAxisRect(parent),
  6861. mPadding(5),
  6862. mOrientation(orientation(type)),
  6863. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  6864. mSelectedParts(spNone),
  6865. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6866. mSelectedBasePen(QPen(Qt::blue, 2)),
  6867. // axis label:
  6868. mLabel(),
  6869. mLabelFont(mParentPlot->font()),
  6870. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  6871. mLabelColor(Qt::black),
  6872. mSelectedLabelColor(Qt::blue),
  6873. // tick labels:
  6874. mTickLabels(true),
  6875. mTickLabelFont(mParentPlot->font()),
  6876. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  6877. mTickLabelColor(Qt::black),
  6878. mSelectedTickLabelColor(Qt::blue),
  6879. mNumberPrecision(6),
  6880. mNumberFormatChar('g'),
  6881. mNumberBeautifulPowers(true),
  6882. // ticks and subticks:
  6883. mTicks(true),
  6884. mSubTicks(true),
  6885. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6886. mSelectedTickPen(QPen(Qt::blue, 2)),
  6887. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6888. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  6889. // scale and range:
  6890. mRange(0, 5),
  6891. mRangeReversed(false),
  6892. mScaleType(stLinear),
  6893. // internal members:
  6894. mGrid(new QCPGrid(this)),
  6895. mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())),
  6896. mTicker(new QCPAxisTicker),
  6897. mCachedMarginValid(false),
  6898. mCachedMargin(0),
  6899. mDragging(false)
  6900. {
  6901. setParent(parent);
  6902. mGrid->setVisible(false);
  6903. setAntialiased(false);
  6904. setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again
  6905. if (type == atTop)
  6906. {
  6907. setTickLabelPadding(3);
  6908. setLabelPadding(6);
  6909. } else if (type == atRight)
  6910. {
  6911. setTickLabelPadding(7);
  6912. setLabelPadding(12);
  6913. } else if (type == atBottom)
  6914. {
  6915. setTickLabelPadding(3);
  6916. setLabelPadding(3);
  6917. } else if (type == atLeft)
  6918. {
  6919. setTickLabelPadding(5);
  6920. setLabelPadding(10);
  6921. }
  6922. }
  6923. QCPAxis::~QCPAxis()
  6924. {
  6925. delete mAxisPainter;
  6926. delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
  6927. }
  6928. /* No documentation as it is a property getter */
  6929. int QCPAxis::tickLabelPadding() const
  6930. {
  6931. return mAxisPainter->tickLabelPadding;
  6932. }
  6933. /* No documentation as it is a property getter */
  6934. double QCPAxis::tickLabelRotation() const
  6935. {
  6936. return mAxisPainter->tickLabelRotation;
  6937. }
  6938. /* No documentation as it is a property getter */
  6939. QCPAxis::LabelSide QCPAxis::tickLabelSide() const
  6940. {
  6941. return mAxisPainter->tickLabelSide;
  6942. }
  6943. /* No documentation as it is a property getter */
  6944. QString QCPAxis::numberFormat() const
  6945. {
  6946. QString result;
  6947. result.append(mNumberFormatChar);
  6948. if (mNumberBeautifulPowers)
  6949. {
  6950. result.append(QLatin1Char('b'));
  6951. if (mAxisPainter->numberMultiplyCross)
  6952. result.append(QLatin1Char('c'));
  6953. }
  6954. return result;
  6955. }
  6956. /* No documentation as it is a property getter */
  6957. int QCPAxis::tickLengthIn() const
  6958. {
  6959. return mAxisPainter->tickLengthIn;
  6960. }
  6961. /* No documentation as it is a property getter */
  6962. int QCPAxis::tickLengthOut() const
  6963. {
  6964. return mAxisPainter->tickLengthOut;
  6965. }
  6966. /* No documentation as it is a property getter */
  6967. int QCPAxis::subTickLengthIn() const
  6968. {
  6969. return mAxisPainter->subTickLengthIn;
  6970. }
  6971. /* No documentation as it is a property getter */
  6972. int QCPAxis::subTickLengthOut() const
  6973. {
  6974. return mAxisPainter->subTickLengthOut;
  6975. }
  6976. /* No documentation as it is a property getter */
  6977. int QCPAxis::labelPadding() const
  6978. {
  6979. return mAxisPainter->labelPadding;
  6980. }
  6981. /* No documentation as it is a property getter */
  6982. int QCPAxis::offset() const
  6983. {
  6984. return mAxisPainter->offset;
  6985. }
  6986. /* No documentation as it is a property getter */
  6987. QCPLineEnding QCPAxis::lowerEnding() const
  6988. {
  6989. return mAxisPainter->lowerEnding;
  6990. }
  6991. /* No documentation as it is a property getter */
  6992. QCPLineEnding QCPAxis::upperEnding() const
  6993. {
  6994. return mAxisPainter->upperEnding;
  6995. }
  6996. /*!
  6997. Sets whether the axis uses a linear scale or a logarithmic scale.
  6998. Note that this method controls the coordinate transformation. For logarithmic scales, you will
  6999. likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
  7000. the axis ticker to an instance of \ref QCPAxisTickerLog :
  7001. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation
  7002. See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
  7003. creation.
  7004. \ref setNumberPrecision
  7005. */
  7006. void QCPAxis::setScaleType(QCPAxis::ScaleType type)
  7007. {
  7008. if (mScaleType != type)
  7009. {
  7010. mScaleType = type;
  7011. if (mScaleType == stLogarithmic)
  7012. setRange(mRange.sanitizedForLogScale());
  7013. mCachedMarginValid = false;
  7014. Q_EMIT scaleTypeChanged(mScaleType);
  7015. }
  7016. }
  7017. /*!
  7018. Sets the range of the axis.
  7019. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  7020. is always synchronized with the other axis range, when it changes.
  7021. To invert the direction of an axis, use \ref setRangeReversed.
  7022. */
  7023. void QCPAxis::setRange(const QCPRange &range)
  7024. {
  7025. if (range.lower == mRange.lower && range.upper == mRange.upper)
  7026. return;
  7027. if (!QCPRange::validRange(range)) return;
  7028. QCPRange oldRange = mRange;
  7029. if (mScaleType == stLogarithmic)
  7030. {
  7031. mRange = range.sanitizedForLogScale();
  7032. } else
  7033. {
  7034. mRange = range.sanitizedForLinScale();
  7035. }
  7036. Q_EMIT rangeChanged(mRange);
  7037. Q_EMIT rangeChanged(mRange, oldRange);
  7038. }
  7039. /*!
  7040. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  7041. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  7042. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  7043. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  7044. directly.
  7045. \see SelectablePart, setSelectedParts
  7046. */
  7047. void QCPAxis::setSelectableParts(const SelectableParts &selectable)
  7048. {
  7049. if (mSelectableParts != selectable)
  7050. {
  7051. mSelectableParts = selectable;
  7052. Q_EMIT selectableChanged(mSelectableParts);
  7053. }
  7054. }
  7055. /*!
  7056. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  7057. is selected, it uses a different pen/font.
  7058. The entire selection mechanism for axes is handled automatically when \ref
  7059. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  7060. wish to change the selection state manually.
  7061. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  7062. Q_EMITs the \ref selectionChanged signal when \a selected is different from the previous selection state.
  7063. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  7064. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  7065. */
  7066. void QCPAxis::setSelectedParts(const SelectableParts &selected)
  7067. {
  7068. if (mSelectedParts != selected)
  7069. {
  7070. mSelectedParts = selected;
  7071. Q_EMIT selectionChanged(mSelectedParts);
  7072. }
  7073. }
  7074. /*!
  7075. \overload
  7076. Sets the lower and upper bound of the axis range.
  7077. To invert the direction of an axis, use \ref setRangeReversed.
  7078. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  7079. */
  7080. void QCPAxis::setRange(double lower, double upper)
  7081. {
  7082. if (lower == mRange.lower && upper == mRange.upper)
  7083. return;
  7084. if (!QCPRange::validRange(lower, upper)) return;
  7085. QCPRange oldRange = mRange;
  7086. mRange.lower = lower;
  7087. mRange.upper = upper;
  7088. if (mScaleType == stLogarithmic)
  7089. {
  7090. mRange = mRange.sanitizedForLogScale();
  7091. } else
  7092. {
  7093. mRange = mRange.sanitizedForLinScale();
  7094. }
  7095. Q_EMIT rangeChanged(mRange);
  7096. Q_EMIT rangeChanged(mRange, oldRange);
  7097. }
  7098. /*!
  7099. \overload
  7100. Sets the range of the axis.
  7101. The \a position coordinate indicates together with the \a alignment parameter, where the new
  7102. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  7103. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  7104. or center of the range to be aligned with \a position. Any other values of \a alignment will
  7105. default to Qt::AlignCenter.
  7106. */
  7107. void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment)
  7108. {
  7109. if (alignment == Qt::AlignLeft)
  7110. setRange(position, position+size);
  7111. else if (alignment == Qt::AlignRight)
  7112. setRange(position-size, position);
  7113. else // alignment == Qt::AlignCenter
  7114. setRange(position-size/2.0, position+size/2.0);
  7115. }
  7116. /*!
  7117. Sets the lower bound of the axis range. The upper bound is not changed.
  7118. \see setRange
  7119. */
  7120. void QCPAxis::setRangeLower(double lower)
  7121. {
  7122. if (mRange.lower == lower)
  7123. return;
  7124. QCPRange oldRange = mRange;
  7125. mRange.lower = lower;
  7126. if (mScaleType == stLogarithmic)
  7127. {
  7128. mRange = mRange.sanitizedForLogScale();
  7129. } else
  7130. {
  7131. mRange = mRange.sanitizedForLinScale();
  7132. }
  7133. Q_EMIT rangeChanged(mRange);
  7134. Q_EMIT rangeChanged(mRange, oldRange);
  7135. }
  7136. /*!
  7137. Sets the upper bound of the axis range. The lower bound is not changed.
  7138. \see setRange
  7139. */
  7140. void QCPAxis::setRangeUpper(double upper)
  7141. {
  7142. if (mRange.upper == upper)
  7143. return;
  7144. QCPRange oldRange = mRange;
  7145. mRange.upper = upper;
  7146. if (mScaleType == stLogarithmic)
  7147. {
  7148. mRange = mRange.sanitizedForLogScale();
  7149. } else
  7150. {
  7151. mRange = mRange.sanitizedForLinScale();
  7152. }
  7153. Q_EMIT rangeChanged(mRange);
  7154. Q_EMIT rangeChanged(mRange, oldRange);
  7155. }
  7156. /*!
  7157. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  7158. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  7159. direction of increasing values is inverted.
  7160. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  7161. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  7162. upper part.
  7163. */
  7164. void QCPAxis::setRangeReversed(bool reversed)
  7165. {
  7166. mRangeReversed = reversed;
  7167. }
  7168. /*!
  7169. The axis ticker is responsible for generating the tick positions and tick labels. See the
  7170. documentation of QCPAxisTicker for details on how to work with axis tickers.
  7171. You can change the tick positioning/labeling behaviour of this axis by setting a different
  7172. QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
  7173. ticker, access it via \ref ticker.
  7174. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  7175. ticker simply by passing the same shared pointer to multiple axes.
  7176. \see ticker
  7177. */
  7178. void QCPAxis::setTicker(QSharedPointer<QCPAxisTicker> ticker)
  7179. {
  7180. if (ticker)
  7181. mTicker = ticker;
  7182. else
  7183. qDebug() << Q_FUNC_INFO << "can not set nullptr as axis ticker";
  7184. // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
  7185. }
  7186. /*!
  7187. Sets whether tick marks are displayed.
  7188. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  7189. that, see \ref setTickLabels.
  7190. \see setSubTicks
  7191. */
  7192. void QCPAxis::setTicks(bool show)
  7193. {
  7194. if (mTicks != show)
  7195. {
  7196. mTicks = show;
  7197. mCachedMarginValid = false;
  7198. }
  7199. }
  7200. /*!
  7201. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  7202. */
  7203. void QCPAxis::setTickLabels(bool show)
  7204. {
  7205. if (mTickLabels != show)
  7206. {
  7207. mTickLabels = show;
  7208. mCachedMarginValid = false;
  7209. if (!mTickLabels)
  7210. mTickVectorLabels.clear();
  7211. }
  7212. }
  7213. /*!
  7214. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  7215. \see setLabelPadding, setPadding
  7216. */
  7217. void QCPAxis::setTickLabelPadding(int padding)
  7218. {
  7219. if (mAxisPainter->tickLabelPadding != padding)
  7220. {
  7221. mAxisPainter->tickLabelPadding = padding;
  7222. mCachedMarginValid = false;
  7223. }
  7224. }
  7225. /*!
  7226. Sets the font of the tick labels.
  7227. \see setTickLabels, setTickLabelColor
  7228. */
  7229. void QCPAxis::setTickLabelFont(const QFont &font)
  7230. {
  7231. if (font != mTickLabelFont)
  7232. {
  7233. mTickLabelFont = font;
  7234. mCachedMarginValid = false;
  7235. }
  7236. }
  7237. /*!
  7238. Sets the color of the tick labels.
  7239. \see setTickLabels, setTickLabelFont
  7240. */
  7241. void QCPAxis::setTickLabelColor(const QColor &color)
  7242. {
  7243. mTickLabelColor = color;
  7244. }
  7245. /*!
  7246. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  7247. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  7248. from -90 to 90 degrees.
  7249. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  7250. other angles, the label is drawn with an offset such that it seems to point toward or away from
  7251. the tick mark.
  7252. */
  7253. void QCPAxis::setTickLabelRotation(double degrees)
  7254. {
  7255. if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation))
  7256. {
  7257. mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0);
  7258. mCachedMarginValid = false;
  7259. }
  7260. }
  7261. /*!
  7262. Sets whether the tick labels (numbers) shall appear inside or outside the axis rect.
  7263. The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels
  7264. to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels
  7265. appear on the inside are additionally clipped to the axis rect.
  7266. */
  7267. void QCPAxis::setTickLabelSide(LabelSide side)
  7268. {
  7269. mAxisPainter->tickLabelSide = side;
  7270. mCachedMarginValid = false;
  7271. }
  7272. /*!
  7273. Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
  7274. of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
  7275. that, see the "Argument Formats" section in the detailed description of the QString class.
  7276. \a formatCode is a string of one, two or three characters.
  7277. <b>The first character</b> is identical to
  7278. the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
  7279. format, 'g'/'G' scientific or fixed, whichever is shorter. For the 'e', 'E', and 'f' formats,
  7280. the precision set by \ref setNumberPrecision represents the number of digits after the decimal
  7281. point. For the 'g' and 'G' formats, the precision represents the maximum number of significant
  7282. digits, trailing zeroes are omitted.
  7283. <b>The second and third characters</b> are optional and specific to QCustomPlot:\n
  7284. If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
  7285. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
  7286. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  7287. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  7288. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  7289. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  7290. cross and 183 (0xB7) for the dot.
  7291. Examples for \a formatCode:
  7292. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  7293. normal scientific format is used
  7294. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  7295. beautifully typeset decimal powers and a dot as multiplication sign
  7296. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  7297. multiplication sign
  7298. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  7299. powers. Format code will be reduced to 'f'.
  7300. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  7301. code will not be changed.
  7302. */
  7303. void QCPAxis::setNumberFormat(const QString &formatCode)
  7304. {
  7305. if (formatCode.isEmpty())
  7306. {
  7307. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  7308. return;
  7309. }
  7310. mCachedMarginValid = false;
  7311. // interpret first char as number format char:
  7312. QString allowedFormatChars(QLatin1String("eEfgG"));
  7313. if (allowedFormatChars.contains(formatCode.at(0)))
  7314. {
  7315. mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
  7316. } else
  7317. {
  7318. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  7319. return;
  7320. }
  7321. if (formatCode.length() < 2)
  7322. {
  7323. mNumberBeautifulPowers = false;
  7324. mAxisPainter->numberMultiplyCross = false;
  7325. return;
  7326. }
  7327. // interpret second char as indicator for beautiful decimal powers:
  7328. if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
  7329. {
  7330. mNumberBeautifulPowers = true;
  7331. } else
  7332. {
  7333. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  7334. return;
  7335. }
  7336. if (formatCode.length() < 3)
  7337. {
  7338. mAxisPainter->numberMultiplyCross = false;
  7339. return;
  7340. }
  7341. // interpret third char as indicator for dot or cross multiplication symbol:
  7342. if (formatCode.at(2) == QLatin1Char('c'))
  7343. {
  7344. mAxisPainter->numberMultiplyCross = true;
  7345. } else if (formatCode.at(2) == QLatin1Char('d'))
  7346. {
  7347. mAxisPainter->numberMultiplyCross = false;
  7348. } else
  7349. {
  7350. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  7351. return;
  7352. }
  7353. }
  7354. /*!
  7355. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  7356. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  7357. \ref setNumberFormat
  7358. */
  7359. void QCPAxis::setNumberPrecision(int precision)
  7360. {
  7361. if (mNumberPrecision != precision)
  7362. {
  7363. mNumberPrecision = precision;
  7364. mCachedMarginValid = false;
  7365. }
  7366. }
  7367. /*!
  7368. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  7369. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  7370. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  7371. they won't collide with the ticks.
  7372. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  7373. */
  7374. void QCPAxis::setTickLength(int inside, int outside)
  7375. {
  7376. setTickLengthIn(inside);
  7377. setTickLengthOut(outside);
  7378. }
  7379. /*!
  7380. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  7381. inside the plot.
  7382. \see setTickLengthOut, setTickLength, setSubTickLength
  7383. */
  7384. void QCPAxis::setTickLengthIn(int inside)
  7385. {
  7386. if (mAxisPainter->tickLengthIn != inside)
  7387. {
  7388. mAxisPainter->tickLengthIn = inside;
  7389. }
  7390. }
  7391. /*!
  7392. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  7393. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  7394. increase their distance to the axis accordingly, so they won't collide with the ticks.
  7395. \see setTickLengthIn, setTickLength, setSubTickLength
  7396. */
  7397. void QCPAxis::setTickLengthOut(int outside)
  7398. {
  7399. if (mAxisPainter->tickLengthOut != outside)
  7400. {
  7401. mAxisPainter->tickLengthOut = outside;
  7402. mCachedMarginValid = false; // only outside tick length can change margin
  7403. }
  7404. }
  7405. /*!
  7406. Sets whether sub tick marks are displayed.
  7407. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
  7408. \see setTicks
  7409. */
  7410. void QCPAxis::setSubTicks(bool show)
  7411. {
  7412. if (mSubTicks != show)
  7413. {
  7414. mSubTicks = show;
  7415. mCachedMarginValid = false;
  7416. }
  7417. }
  7418. /*!
  7419. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  7420. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  7421. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  7422. so they won't collide with the ticks.
  7423. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  7424. */
  7425. void QCPAxis::setSubTickLength(int inside, int outside)
  7426. {
  7427. setSubTickLengthIn(inside);
  7428. setSubTickLengthOut(outside);
  7429. }
  7430. /*!
  7431. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  7432. the plot.
  7433. \see setSubTickLengthOut, setSubTickLength, setTickLength
  7434. */
  7435. void QCPAxis::setSubTickLengthIn(int inside)
  7436. {
  7437. if (mAxisPainter->subTickLengthIn != inside)
  7438. {
  7439. mAxisPainter->subTickLengthIn = inside;
  7440. }
  7441. }
  7442. /*!
  7443. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  7444. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  7445. distance to the axis accordingly, so they won't collide with the ticks.
  7446. \see setSubTickLengthIn, setSubTickLength, setTickLength
  7447. */
  7448. void QCPAxis::setSubTickLengthOut(int outside)
  7449. {
  7450. if (mAxisPainter->subTickLengthOut != outside)
  7451. {
  7452. mAxisPainter->subTickLengthOut = outside;
  7453. mCachedMarginValid = false; // only outside tick length can change margin
  7454. }
  7455. }
  7456. /*!
  7457. Sets the pen, the axis base line is drawn with.
  7458. \see setTickPen, setSubTickPen
  7459. */
  7460. void QCPAxis::setBasePen(const QPen &pen)
  7461. {
  7462. mBasePen = pen;
  7463. }
  7464. /*!
  7465. Sets the pen, tick marks will be drawn with.
  7466. \see setTickLength, setBasePen
  7467. */
  7468. void QCPAxis::setTickPen(const QPen &pen)
  7469. {
  7470. mTickPen = pen;
  7471. }
  7472. /*!
  7473. Sets the pen, subtick marks will be drawn with.
  7474. \see setSubTickCount, setSubTickLength, setBasePen
  7475. */
  7476. void QCPAxis::setSubTickPen(const QPen &pen)
  7477. {
  7478. mSubTickPen = pen;
  7479. }
  7480. /*!
  7481. Sets the font of the axis label.
  7482. \see setLabelColor
  7483. */
  7484. void QCPAxis::setLabelFont(const QFont &font)
  7485. {
  7486. if (mLabelFont != font)
  7487. {
  7488. mLabelFont = font;
  7489. mCachedMarginValid = false;
  7490. }
  7491. }
  7492. /*!
  7493. Sets the color of the axis label.
  7494. \see setLabelFont
  7495. */
  7496. void QCPAxis::setLabelColor(const QColor &color)
  7497. {
  7498. mLabelColor = color;
  7499. }
  7500. /*!
  7501. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  7502. its orientation. To disable axis labels, pass an empty string as \a str.
  7503. */
  7504. void QCPAxis::setLabel(const QString &str)
  7505. {
  7506. if (mLabel != str)
  7507. {
  7508. mLabel = str;
  7509. mCachedMarginValid = false;
  7510. }
  7511. }
  7512. /*!
  7513. Sets the distance between the tick labels and the axis label.
  7514. \see setTickLabelPadding, setPadding
  7515. */
  7516. void QCPAxis::setLabelPadding(int padding)
  7517. {
  7518. if (mAxisPainter->labelPadding != padding)
  7519. {
  7520. mAxisPainter->labelPadding = padding;
  7521. mCachedMarginValid = false;
  7522. }
  7523. }
  7524. /*!
  7525. Sets the padding of the axis.
  7526. When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space,
  7527. that is left blank.
  7528. The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled.
  7529. \see setLabelPadding, setTickLabelPadding
  7530. */
  7531. void QCPAxis::setPadding(int padding)
  7532. {
  7533. if (mPadding != padding)
  7534. {
  7535. mPadding = padding;
  7536. mCachedMarginValid = false;
  7537. }
  7538. }
  7539. /*!
  7540. Sets the offset the axis has to its axis rect side.
  7541. If an axis rect side has multiple axes and automatic margin calculation is enabled for that side,
  7542. only the offset of the inner most axis has meaning (even if it is set to be invisible). The
  7543. offset of the other, outer axes is controlled automatically, to place them at appropriate
  7544. positions.
  7545. */
  7546. void QCPAxis::setOffset(int offset)
  7547. {
  7548. mAxisPainter->offset = offset;
  7549. }
  7550. /*!
  7551. Sets the font that is used for tick labels when they are selected.
  7552. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7553. */
  7554. void QCPAxis::setSelectedTickLabelFont(const QFont &font)
  7555. {
  7556. if (font != mSelectedTickLabelFont)
  7557. {
  7558. mSelectedTickLabelFont = font;
  7559. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  7560. }
  7561. }
  7562. /*!
  7563. Sets the font that is used for the axis label when it is selected.
  7564. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7565. */
  7566. void QCPAxis::setSelectedLabelFont(const QFont &font)
  7567. {
  7568. mSelectedLabelFont = font;
  7569. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  7570. }
  7571. /*!
  7572. Sets the color that is used for tick labels when they are selected.
  7573. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7574. */
  7575. void QCPAxis::setSelectedTickLabelColor(const QColor &color)
  7576. {
  7577. if (color != mSelectedTickLabelColor)
  7578. {
  7579. mSelectedTickLabelColor = color;
  7580. }
  7581. }
  7582. /*!
  7583. Sets the color that is used for the axis label when it is selected.
  7584. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7585. */
  7586. void QCPAxis::setSelectedLabelColor(const QColor &color)
  7587. {
  7588. mSelectedLabelColor = color;
  7589. }
  7590. /*!
  7591. Sets the pen that is used to draw the axis base line when selected.
  7592. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7593. */
  7594. void QCPAxis::setSelectedBasePen(const QPen &pen)
  7595. {
  7596. mSelectedBasePen = pen;
  7597. }
  7598. /*!
  7599. Sets the pen that is used to draw the (major) ticks when selected.
  7600. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7601. */
  7602. void QCPAxis::setSelectedTickPen(const QPen &pen)
  7603. {
  7604. mSelectedTickPen = pen;
  7605. }
  7606. /*!
  7607. Sets the pen that is used to draw the subticks when selected.
  7608. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7609. */
  7610. void QCPAxis::setSelectedSubTickPen(const QPen &pen)
  7611. {
  7612. mSelectedSubTickPen = pen;
  7613. }
  7614. /*!
  7615. Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available
  7616. styles.
  7617. For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending.
  7618. Note that this meaning does not change when the axis range is reversed with \ref
  7619. setRangeReversed.
  7620. \see setUpperEnding
  7621. */
  7622. void QCPAxis::setLowerEnding(const QCPLineEnding &ending)
  7623. {
  7624. mAxisPainter->lowerEnding = ending;
  7625. }
  7626. /*!
  7627. Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available
  7628. styles.
  7629. For horizontal axes, this method refers to the right ending, for vertical axes the top ending.
  7630. Note that this meaning does not change when the axis range is reversed with \ref
  7631. setRangeReversed.
  7632. \see setLowerEnding
  7633. */
  7634. void QCPAxis::setUpperEnding(const QCPLineEnding &ending)
  7635. {
  7636. mAxisPainter->upperEnding = ending;
  7637. }
  7638. /*!
  7639. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  7640. bounds of the range. The range is simply moved by \a diff.
  7641. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  7642. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  7643. */
  7644. void QCPAxis::moveRange(double diff)
  7645. {
  7646. QCPRange oldRange = mRange;
  7647. if (mScaleType == stLinear)
  7648. {
  7649. mRange.lower += diff;
  7650. mRange.upper += diff;
  7651. } else // mScaleType == stLogarithmic
  7652. {
  7653. mRange.lower *= diff;
  7654. mRange.upper *= diff;
  7655. }
  7656. Q_EMIT rangeChanged(mRange);
  7657. Q_EMIT rangeChanged(mRange, oldRange);
  7658. }
  7659. /*!
  7660. Scales the range of this axis by \a factor around the center of the current axis range. For
  7661. example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
  7662. range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
  7663. the center will have moved symmetrically closer).
  7664. If you wish to scale around a different coordinate than the current axis range center, use the
  7665. overload \ref scaleRange(double factor, double center).
  7666. */
  7667. void QCPAxis::scaleRange(double factor)
  7668. {
  7669. scaleRange(factor, range().center());
  7670. }
  7671. /*! \overload
  7672. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  7673. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  7674. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  7675. around 1.0 will have moved symmetrically closer to 1.0).
  7676. \see scaleRange(double factor)
  7677. */
  7678. void QCPAxis::scaleRange(double factor, double center)
  7679. {
  7680. QCPRange oldRange = mRange;
  7681. if (mScaleType == stLinear)
  7682. {
  7683. QCPRange newRange;
  7684. newRange.lower = (mRange.lower-center)*factor + center;
  7685. newRange.upper = (mRange.upper-center)*factor + center;
  7686. if (QCPRange::validRange(newRange))
  7687. mRange = newRange.sanitizedForLinScale();
  7688. } else // mScaleType == stLogarithmic
  7689. {
  7690. if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
  7691. {
  7692. QCPRange newRange;
  7693. newRange.lower = qPow(mRange.lower/center, factor)*center;
  7694. newRange.upper = qPow(mRange.upper/center, factor)*center;
  7695. if (QCPRange::validRange(newRange))
  7696. mRange = newRange.sanitizedForLogScale();
  7697. } else
  7698. qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
  7699. }
  7700. Q_EMIT rangeChanged(mRange);
  7701. Q_EMIT rangeChanged(mRange, oldRange);
  7702. }
  7703. /*!
  7704. Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will
  7705. be done around the center of the current axis range.
  7706. For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs
  7707. plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the
  7708. axis rect has.
  7709. This is an operation that changes the range of this axis once, it doesn't fix the scale ratio
  7710. indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent
  7711. won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent
  7712. will follow.
  7713. */
  7714. void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio)
  7715. {
  7716. int otherPixelSize, ownPixelSize;
  7717. if (otherAxis->orientation() == Qt::Horizontal)
  7718. otherPixelSize = otherAxis->axisRect()->width();
  7719. else
  7720. otherPixelSize = otherAxis->axisRect()->height();
  7721. if (orientation() == Qt::Horizontal)
  7722. ownPixelSize = axisRect()->width();
  7723. else
  7724. ownPixelSize = axisRect()->height();
  7725. double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/double(otherPixelSize);
  7726. setRange(range().center(), newRangeSize, Qt::AlignCenter);
  7727. }
  7728. /*!
  7729. Changes the axis range such that all plottables associated with this axis are fully visible in
  7730. that dimension.
  7731. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  7732. */
  7733. void QCPAxis::rescale(bool onlyVisiblePlottables)
  7734. {
  7735. QCPRange newRange;
  7736. bool haveRange = false;
  7737. foreach (QCPAbstractPlottable *plottable, plottables())
  7738. {
  7739. if (!plottable->realVisibility() && onlyVisiblePlottables)
  7740. continue;
  7741. QCPRange plottableRange;
  7742. bool currentFoundRange;
  7743. QCP::SignDomain signDomain = QCP::sdBoth;
  7744. if (mScaleType == stLogarithmic)
  7745. signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  7746. if (plottable->keyAxis() == this)
  7747. plottableRange = plottable->getKeyRange(currentFoundRange, signDomain);
  7748. else
  7749. plottableRange = plottable->getValueRange(currentFoundRange, signDomain);
  7750. if (currentFoundRange)
  7751. {
  7752. if (!haveRange)
  7753. newRange = plottableRange;
  7754. else
  7755. newRange.expand(plottableRange);
  7756. haveRange = true;
  7757. }
  7758. }
  7759. if (haveRange)
  7760. {
  7761. if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
  7762. {
  7763. double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
  7764. if (mScaleType == stLinear)
  7765. {
  7766. newRange.lower = center-mRange.size()/2.0;
  7767. newRange.upper = center+mRange.size()/2.0;
  7768. } else // mScaleType == stLogarithmic
  7769. {
  7770. newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
  7771. newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
  7772. }
  7773. }
  7774. setRange(newRange);
  7775. }
  7776. }
  7777. /*!
  7778. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  7779. */
  7780. double QCPAxis::pixelToCoord(double value) const
  7781. {
  7782. if (orientation() == Qt::Horizontal)
  7783. {
  7784. if (mScaleType == stLinear)
  7785. {
  7786. if (!mRangeReversed)
  7787. return (value-mAxisRect->left())/double(mAxisRect->width())*mRange.size()+mRange.lower;
  7788. else
  7789. return -(value-mAxisRect->left())/double(mAxisRect->width())*mRange.size()+mRange.upper;
  7790. } else // mScaleType == stLogarithmic
  7791. {
  7792. if (!mRangeReversed)
  7793. return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/double(mAxisRect->width()))*mRange.lower;
  7794. else
  7795. return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/double(mAxisRect->width()))*mRange.upper;
  7796. }
  7797. } else // orientation() == Qt::Vertical
  7798. {
  7799. if (mScaleType == stLinear)
  7800. {
  7801. if (!mRangeReversed)
  7802. return (mAxisRect->bottom()-value)/double(mAxisRect->height())*mRange.size()+mRange.lower;
  7803. else
  7804. return -(mAxisRect->bottom()-value)/double(mAxisRect->height())*mRange.size()+mRange.upper;
  7805. } else // mScaleType == stLogarithmic
  7806. {
  7807. if (!mRangeReversed)
  7808. return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/double(mAxisRect->height()))*mRange.lower;
  7809. else
  7810. return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/double(mAxisRect->height()))*mRange.upper;
  7811. }
  7812. }
  7813. }
  7814. /*!
  7815. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  7816. */
  7817. double QCPAxis::coordToPixel(double value) const
  7818. {
  7819. if (orientation() == Qt::Horizontal)
  7820. {
  7821. if (mScaleType == stLinear)
  7822. {
  7823. if (!mRangeReversed)
  7824. return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left();
  7825. else
  7826. return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left();
  7827. } else // mScaleType == stLogarithmic
  7828. {
  7829. if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7830. return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200;
  7831. else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7832. return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200;
  7833. else
  7834. {
  7835. if (!mRangeReversed)
  7836. return qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
  7837. else
  7838. return qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
  7839. }
  7840. }
  7841. } else // orientation() == Qt::Vertical
  7842. {
  7843. if (mScaleType == stLinear)
  7844. {
  7845. if (!mRangeReversed)
  7846. return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height();
  7847. else
  7848. return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height();
  7849. } else // mScaleType == stLogarithmic
  7850. {
  7851. if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7852. return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200;
  7853. else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7854. return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200;
  7855. else
  7856. {
  7857. if (!mRangeReversed)
  7858. return mAxisRect->bottom()-qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
  7859. else
  7860. return mAxisRect->bottom()-qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
  7861. }
  7862. }
  7863. }
  7864. }
  7865. /*!
  7866. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  7867. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  7868. function does not change the current selection state of the axis.
  7869. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  7870. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  7871. */
  7872. QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const
  7873. {
  7874. if (!mVisible)
  7875. return spNone;
  7876. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  7877. return spAxis;
  7878. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  7879. return spTickLabels;
  7880. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  7881. return spAxisLabel;
  7882. else
  7883. return spNone;
  7884. }
  7885. /* inherits documentation from base class */
  7886. double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  7887. {
  7888. if (!mParentPlot) return -1;
  7889. SelectablePart part = getPartAt(pos);
  7890. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  7891. return -1;
  7892. if (details)
  7893. details->setValue(part);
  7894. return mParentPlot->selectionTolerance()*0.99;
  7895. }
  7896. /*!
  7897. Returns a list of all the plottables that have this axis as key or value axis.
  7898. If you are only interested in plottables of type QCPGraph, see \ref graphs.
  7899. \see graphs, items
  7900. */
  7901. QList<QCPAbstractPlottable*> QCPAxis::plottables() const
  7902. {
  7903. QList<QCPAbstractPlottable*> result;
  7904. if (!mParentPlot) return result;
  7905. foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables)
  7906. {
  7907. if (plottable->keyAxis() == this || plottable->valueAxis() == this)
  7908. result.append(plottable);
  7909. }
  7910. return result;
  7911. }
  7912. /*!
  7913. Returns a list of all the graphs that have this axis as key or value axis.
  7914. \see plottables, items
  7915. */
  7916. QList<QCPGraph*> QCPAxis::graphs() const
  7917. {
  7918. QList<QCPGraph*> result;
  7919. if (!mParentPlot) return result;
  7920. foreach (QCPGraph *graph, mParentPlot->mGraphs)
  7921. {
  7922. if (graph->keyAxis() == this || graph->valueAxis() == this)
  7923. result.append(graph);
  7924. }
  7925. return result;
  7926. }
  7927. /*!
  7928. Returns a list of all the items that are associated with this axis. An item is considered
  7929. associated with an axis if at least one of its positions uses the axis as key or value axis.
  7930. \see plottables, graphs
  7931. */
  7932. QList<QCPAbstractItem*> QCPAxis::items() const
  7933. {
  7934. QList<QCPAbstractItem*> result;
  7935. if (!mParentPlot) return result;
  7936. foreach (QCPAbstractItem *item, mParentPlot->mItems)
  7937. {
  7938. foreach (QCPItemPosition *position, item->positions())
  7939. {
  7940. if (position->keyAxis() == this || position->valueAxis() == this)
  7941. {
  7942. result.append(item);
  7943. break;
  7944. }
  7945. }
  7946. }
  7947. return result;
  7948. }
  7949. /*!
  7950. Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to
  7951. QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.)
  7952. */
  7953. QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side)
  7954. {
  7955. switch (side)
  7956. {
  7957. case QCP::msLeft: return atLeft;
  7958. case QCP::msRight: return atRight;
  7959. case QCP::msTop: return atTop;
  7960. case QCP::msBottom: return atBottom;
  7961. default: break;
  7962. }
  7963. qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << static_cast<int>(side);
  7964. return atLeft;
  7965. }
  7966. /*!
  7967. Returns the axis type that describes the opposite axis of an axis with the specified \a type.
  7968. */
  7969. QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type)
  7970. {
  7971. switch (type)
  7972. {
  7973. case atLeft: return atRight;
  7974. case atRight: return atLeft;
  7975. case atBottom: return atTop;
  7976. case atTop: return atBottom;
  7977. }
  7978. qDebug() << Q_FUNC_INFO << "invalid axis type";
  7979. return atLeft;
  7980. }
  7981. /* inherits documentation from base class */
  7982. void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  7983. {
  7984. Q_UNUSED(event)
  7985. SelectablePart part = details.value<SelectablePart>();
  7986. if (mSelectableParts.testFlag(part))
  7987. {
  7988. SelectableParts selBefore = mSelectedParts;
  7989. setSelectedParts(additive ? mSelectedParts^part : part);
  7990. if (selectionStateChanged)
  7991. *selectionStateChanged = mSelectedParts != selBefore;
  7992. }
  7993. }
  7994. /* inherits documentation from base class */
  7995. void QCPAxis::deselectEvent(bool *selectionStateChanged)
  7996. {
  7997. SelectableParts selBefore = mSelectedParts;
  7998. setSelectedParts(mSelectedParts & ~mSelectableParts);
  7999. if (selectionStateChanged)
  8000. *selectionStateChanged = mSelectedParts != selBefore;
  8001. }
  8002. /*! \internal
  8003. This mouse event reimplementation provides the functionality to let the user drag individual axes
  8004. exclusively, by startig the drag on top of the axis.
  8005. For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect
  8006. must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis
  8007. (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref
  8008. QCPAxisRect::setRangeDragAxes)
  8009. \seebaseclassmethod
  8010. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  8011. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  8012. */
  8013. void QCPAxis::mousePressEvent(QMouseEvent *event, const QVariant &details)
  8014. {
  8015. Q_UNUSED(details)
  8016. if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag) ||
  8017. !mAxisRect->rangeDrag().testFlag(orientation()) ||
  8018. !mAxisRect->rangeDragAxes(orientation()).contains(this))
  8019. {
  8020. event->ignore();
  8021. return;
  8022. }
  8023. if (event->buttons() & Qt::LeftButton)
  8024. {
  8025. mDragging = true;
  8026. // initialize antialiasing backup in case we start dragging:
  8027. if (mParentPlot->noAntialiasingOnDrag())
  8028. {
  8029. mAADragBackup = mParentPlot->antialiasedElements();
  8030. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  8031. }
  8032. // Mouse range dragging interaction:
  8033. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  8034. mDragStartRange = mRange;
  8035. }
  8036. }
  8037. /*! \internal
  8038. This mouse event reimplementation provides the functionality to let the user drag individual axes
  8039. exclusively, by startig the drag on top of the axis.
  8040. \seebaseclassmethod
  8041. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  8042. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  8043. \see QCPAxis::mousePressEvent
  8044. */
  8045. void QCPAxis::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  8046. {
  8047. if (mDragging)
  8048. {
  8049. const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y();
  8050. const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y();
  8051. if (mScaleType == QCPAxis::stLinear)
  8052. {
  8053. const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel);
  8054. setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff);
  8055. } else if (mScaleType == QCPAxis::stLogarithmic)
  8056. {
  8057. const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel);
  8058. setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff);
  8059. }
  8060. if (mParentPlot->noAntialiasingOnDrag())
  8061. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  8062. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  8063. }
  8064. }
  8065. /*! \internal
  8066. This mouse event reimplementation provides the functionality to let the user drag individual axes
  8067. exclusively, by startig the drag on top of the axis.
  8068. \seebaseclassmethod
  8069. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  8070. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  8071. \see QCPAxis::mousePressEvent
  8072. */
  8073. void QCPAxis::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  8074. {
  8075. Q_UNUSED(event)
  8076. Q_UNUSED(startPos)
  8077. mDragging = false;
  8078. if (mParentPlot->noAntialiasingOnDrag())
  8079. {
  8080. mParentPlot->setAntialiasedElements(mAADragBackup);
  8081. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  8082. }
  8083. }
  8084. /*! \internal
  8085. This mouse event reimplementation provides the functionality to let the user zoom individual axes
  8086. exclusively, by performing the wheel event on top of the axis.
  8087. For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect
  8088. must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis
  8089. (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref
  8090. QCPAxisRect::setRangeZoomAxes)
  8091. \seebaseclassmethod
  8092. \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the
  8093. axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent.
  8094. */
  8095. void QCPAxis::wheelEvent(QWheelEvent *event)
  8096. {
  8097. // Mouse range zooming interaction:
  8098. if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom) ||
  8099. !mAxisRect->rangeZoom().testFlag(orientation()) ||
  8100. !mAxisRect->rangeZoomAxes(orientation()).contains(this))
  8101. {
  8102. event->ignore();
  8103. return;
  8104. }
  8105. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  8106. const double delta = event->delta();
  8107. #else
  8108. const double delta = event->angleDelta().y();
  8109. #endif
  8110. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  8111. const QPointF pos = event->pos();
  8112. #else
  8113. const QPointF pos = event->position();
  8114. #endif
  8115. const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
  8116. const double factor = qPow(mAxisRect->rangeZoomFactor(orientation()), wheelSteps);
  8117. scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? pos.x() : pos.y()));
  8118. mParentPlot->replot();
  8119. }
  8120. /*! \internal
  8121. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  8122. before drawing axis lines.
  8123. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  8124. This function takes into account the local setting of the antialiasing flag as well as the
  8125. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  8126. QCustomPlot::setNotAntialiasedElements.
  8127. \seebaseclassmethod
  8128. \see setAntialiased
  8129. */
  8130. void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const
  8131. {
  8132. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  8133. }
  8134. /*! \internal
  8135. Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
  8136. \seebaseclassmethod
  8137. */
  8138. void QCPAxis::draw(QCPPainter *painter)
  8139. {
  8140. QVector<double> subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  8141. QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  8142. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  8143. tickPositions.reserve(mTickVector.size());
  8144. tickLabels.reserve(mTickVector.size());
  8145. subTickPositions.reserve(mSubTickVector.size());
  8146. if (mTicks)
  8147. {
  8148. for (int i=0; i<mTickVector.size(); ++i)
  8149. {
  8150. tickPositions.append(coordToPixel(mTickVector.at(i)));
  8151. if (mTickLabels)
  8152. tickLabels.append(mTickVectorLabels.at(i));
  8153. }
  8154. if (mSubTicks)
  8155. {
  8156. const int subTickCount = mSubTickVector.size();
  8157. for (int i=0; i<subTickCount; ++i)
  8158. subTickPositions.append(coordToPixel(mSubTickVector.at(i)));
  8159. }
  8160. }
  8161. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis.
  8162. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
  8163. mAxisPainter->type = mAxisType;
  8164. mAxisPainter->basePen = getBasePen();
  8165. mAxisPainter->labelFont = getLabelFont();
  8166. mAxisPainter->labelColor = getLabelColor();
  8167. mAxisPainter->label = mLabel;
  8168. mAxisPainter->substituteExponent = mNumberBeautifulPowers;
  8169. mAxisPainter->tickPen = getTickPen();
  8170. mAxisPainter->subTickPen = getSubTickPen();
  8171. mAxisPainter->tickLabelFont = getTickLabelFont();
  8172. mAxisPainter->tickLabelColor = getTickLabelColor();
  8173. mAxisPainter->axisRect = mAxisRect->rect();
  8174. mAxisPainter->viewportRect = mParentPlot->viewport();
  8175. mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic;
  8176. mAxisPainter->reversedEndings = mRangeReversed;
  8177. mAxisPainter->tickPositions = tickPositions;
  8178. mAxisPainter->tickLabels = tickLabels;
  8179. mAxisPainter->subTickPositions = subTickPositions;
  8180. mAxisPainter->draw(painter);
  8181. }
  8182. /*! \internal
  8183. Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
  8184. QCPAxisTicker::generate on the currently installed ticker.
  8185. If a change in the label text/count is detected, the cached axis margin is invalidated to make
  8186. sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
  8187. */
  8188. void QCPAxis::setupTickVectors()
  8189. {
  8190. if (!mParentPlot) return;
  8191. if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
  8192. QVector<QString> oldLabels = mTickVectorLabels;
  8193. mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : nullptr, mTickLabels ? &mTickVectorLabels : nullptr);
  8194. mCachedMarginValid &= mTickVectorLabels == oldLabels; // if labels have changed, margin might have changed, too
  8195. }
  8196. /*! \internal
  8197. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  8198. is either mSelectedBasePen or mBasePen.
  8199. */
  8200. QPen QCPAxis::getBasePen() const
  8201. {
  8202. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  8203. }
  8204. /*! \internal
  8205. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  8206. is either mSelectedTickPen or mTickPen.
  8207. */
  8208. QPen QCPAxis::getTickPen() const
  8209. {
  8210. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  8211. }
  8212. /*! \internal
  8213. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  8214. is either mSelectedSubTickPen or mSubTickPen.
  8215. */
  8216. QPen QCPAxis::getSubTickPen() const
  8217. {
  8218. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  8219. }
  8220. /*! \internal
  8221. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  8222. is either mSelectedTickLabelFont or mTickLabelFont.
  8223. */
  8224. QFont QCPAxis::getTickLabelFont() const
  8225. {
  8226. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  8227. }
  8228. /*! \internal
  8229. Returns the font that is used to draw the axis label. Depending on the selection state, this
  8230. is either mSelectedLabelFont or mLabelFont.
  8231. */
  8232. QFont QCPAxis::getLabelFont() const
  8233. {
  8234. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  8235. }
  8236. /*! \internal
  8237. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  8238. is either mSelectedTickLabelColor or mTickLabelColor.
  8239. */
  8240. QColor QCPAxis::getTickLabelColor() const
  8241. {
  8242. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  8243. }
  8244. /*! \internal
  8245. Returns the color that is used to draw the axis label. Depending on the selection state, this
  8246. is either mSelectedLabelColor or mLabelColor.
  8247. */
  8248. QColor QCPAxis::getLabelColor() const
  8249. {
  8250. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  8251. }
  8252. /*! \internal
  8253. Returns the appropriate outward margin for this axis. It is needed if \ref
  8254. QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref
  8255. atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom
  8256. margin and so forth. For the calculation, this function goes through similar steps as \ref draw,
  8257. so changing one function likely requires the modification of the other one as well.
  8258. The margin consists of the outward tick length, tick label padding, tick label size, label
  8259. padding, label size, and padding.
  8260. The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc.
  8261. unchanged are very fast.
  8262. */
  8263. int QCPAxis::calculateMargin()
  8264. {
  8265. if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis
  8266. return 0;
  8267. if (mCachedMarginValid)
  8268. return mCachedMargin;
  8269. // run through similar steps as QCPAxis::draw, and calculate margin needed to fit axis and its labels
  8270. int margin = 0;
  8271. QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  8272. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  8273. tickPositions.reserve(mTickVector.size());
  8274. tickLabels.reserve(mTickVector.size());
  8275. if (mTicks)
  8276. {
  8277. for (int i=0; i<mTickVector.size(); ++i)
  8278. {
  8279. tickPositions.append(coordToPixel(mTickVector.at(i)));
  8280. if (mTickLabels)
  8281. tickLabels.append(mTickVectorLabels.at(i));
  8282. }
  8283. }
  8284. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size.
  8285. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
  8286. mAxisPainter->type = mAxisType;
  8287. mAxisPainter->labelFont = getLabelFont();
  8288. mAxisPainter->label = mLabel;
  8289. mAxisPainter->tickLabelFont = mTickLabelFont;
  8290. mAxisPainter->axisRect = mAxisRect->rect();
  8291. mAxisPainter->viewportRect = mParentPlot->viewport();
  8292. mAxisPainter->tickPositions = tickPositions;
  8293. mAxisPainter->tickLabels = tickLabels;
  8294. margin += mAxisPainter->size();
  8295. margin += mPadding;
  8296. mCachedMargin = margin;
  8297. mCachedMarginValid = true;
  8298. return margin;
  8299. }
  8300. /* inherits documentation from base class */
  8301. QCP::Interaction QCPAxis::selectionCategory() const
  8302. {
  8303. return QCP::iSelectAxes;
  8304. }
  8305. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8306. //////////////////// QCPAxisPainterPrivate
  8307. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8308. /*! \class QCPAxisPainterPrivate
  8309. \internal
  8310. \brief (Private)
  8311. This is a private class and not part of the public QCustomPlot interface.
  8312. It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and
  8313. axis label. It also buffers the labels to reduce replot times. The parameters are configured by
  8314. directly accessing the public member variables.
  8315. */
  8316. /*!
  8317. Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every
  8318. redraw, to utilize the caching mechanisms.
  8319. */
  8320. QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) :
  8321. type(QCPAxis::atLeft),
  8322. basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  8323. lowerEnding(QCPLineEnding::esNone),
  8324. upperEnding(QCPLineEnding::esNone),
  8325. labelPadding(0),
  8326. tickLabelPadding(0),
  8327. tickLabelRotation(0),
  8328. tickLabelSide(QCPAxis::lsOutside),
  8329. substituteExponent(true),
  8330. numberMultiplyCross(false),
  8331. tickLengthIn(5),
  8332. tickLengthOut(0),
  8333. subTickLengthIn(2),
  8334. subTickLengthOut(0),
  8335. tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  8336. subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  8337. offset(0),
  8338. abbreviateDecimalPowers(false),
  8339. reversedEndings(false),
  8340. mParentPlot(parentPlot),
  8341. mLabelCache(16) // cache at most 16 (tick) labels
  8342. {
  8343. }
  8344. QCPAxisPainterPrivate::~QCPAxisPainterPrivate()
  8345. {
  8346. }
  8347. /*! \internal
  8348. Draws the axis with the specified \a painter.
  8349. The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set
  8350. here, too.
  8351. */
  8352. void QCPAxisPainterPrivate::draw(QCPPainter *painter)
  8353. {
  8354. QByteArray newHash = generateLabelParameterHash();
  8355. if (newHash != mLabelParameterHash)
  8356. {
  8357. mLabelCache.clear();
  8358. mLabelParameterHash = newHash;
  8359. }
  8360. QPoint origin;
  8361. switch (type)
  8362. {
  8363. case QCPAxis::atLeft: origin = axisRect.bottomLeft() +QPoint(-offset, 0); break;
  8364. case QCPAxis::atRight: origin = axisRect.bottomRight()+QPoint(+offset, 0); break;
  8365. case QCPAxis::atTop: origin = axisRect.topLeft() +QPoint(0, -offset); break;
  8366. case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break;
  8367. }
  8368. double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes)
  8369. switch (type)
  8370. {
  8371. case QCPAxis::atTop: yCor = -1; break;
  8372. case QCPAxis::atRight: xCor = 1; break;
  8373. default: break;
  8374. }
  8375. int margin = 0;
  8376. // draw baseline:
  8377. QLineF baseLine;
  8378. painter->setPen(basePen);
  8379. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8380. baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor));
  8381. else
  8382. baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor));
  8383. if (reversedEndings)
  8384. baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later
  8385. painter->drawLine(baseLine);
  8386. // draw ticks:
  8387. if (!tickPositions.isEmpty())
  8388. {
  8389. painter->setPen(tickPen);
  8390. int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis)
  8391. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8392. {
  8393. foreach (double tickPos, tickPositions)
  8394. painter->drawLine(QLineF(tickPos+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPos+xCor, origin.y()+tickLengthIn*tickDir+yCor));
  8395. } else
  8396. {
  8397. foreach (double tickPos, tickPositions)
  8398. painter->drawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPos+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPos+yCor));
  8399. }
  8400. }
  8401. // draw subticks:
  8402. if (!subTickPositions.isEmpty())
  8403. {
  8404. painter->setPen(subTickPen);
  8405. // direction of ticks ("inward" is right for left axis and left for right axis)
  8406. int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1;
  8407. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8408. {
  8409. foreach (double subTickPos, subTickPositions)
  8410. painter->drawLine(QLineF(subTickPos+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPos+xCor, origin.y()+subTickLengthIn*tickDir+yCor));
  8411. } else
  8412. {
  8413. foreach (double subTickPos, subTickPositions)
  8414. painter->drawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPos+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPos+yCor));
  8415. }
  8416. }
  8417. margin += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  8418. // draw axis base endings:
  8419. bool antialiasingBackup = painter->antialiasing();
  8420. painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't
  8421. painter->setBrush(QBrush(basePen.color()));
  8422. QCPVector2D baseLineVector(baseLine.dx(), baseLine.dy());
  8423. if (lowerEnding.style() != QCPLineEnding::esNone)
  8424. lowerEnding.draw(painter, QCPVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector);
  8425. if (upperEnding.style() != QCPLineEnding::esNone)
  8426. upperEnding.draw(painter, QCPVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector);
  8427. painter->setAntialiasing(antialiasingBackup);
  8428. // tick labels:
  8429. QRect oldClipRect;
  8430. if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect
  8431. {
  8432. oldClipRect = painter->clipRegion().boundingRect();
  8433. painter->setClipRect(axisRect);
  8434. }
  8435. QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label
  8436. if (!tickLabels.isEmpty())
  8437. {
  8438. if (tickLabelSide == QCPAxis::lsOutside)
  8439. margin += tickLabelPadding;
  8440. painter->setFont(tickLabelFont);
  8441. painter->setPen(QPen(tickLabelColor));
  8442. const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size());
  8443. int distanceToAxis = margin;
  8444. if (tickLabelSide == QCPAxis::lsInside)
  8445. distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
  8446. for (int i=0; i<maxLabelIndex; ++i)
  8447. placeTickLabel(painter, tickPositions.at(i), distanceToAxis, tickLabels.at(i), &tickLabelsSize);
  8448. if (tickLabelSide == QCPAxis::lsOutside)
  8449. margin += (QCPAxis::orientation(type) == Qt::Horizontal) ? tickLabelsSize.height() : tickLabelsSize.width();
  8450. }
  8451. if (tickLabelSide == QCPAxis::lsInside)
  8452. painter->setClipRect(oldClipRect);
  8453. // axis label:
  8454. QRect labelBounds;
  8455. if (!label.isEmpty())
  8456. {
  8457. margin += labelPadding;
  8458. painter->setFont(labelFont);
  8459. painter->setPen(QPen(labelColor));
  8460. labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label);
  8461. if (type == QCPAxis::atLeft)
  8462. {
  8463. QTransform oldTransform = painter->transform();
  8464. painter->translate((origin.x()-margin-labelBounds.height()), origin.y());
  8465. painter->rotate(-90);
  8466. painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8467. painter->setTransform(oldTransform);
  8468. }
  8469. else if (type == QCPAxis::atRight)
  8470. {
  8471. QTransform oldTransform = painter->transform();
  8472. painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height());
  8473. painter->rotate(90);
  8474. painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8475. painter->setTransform(oldTransform);
  8476. }
  8477. else if (type == QCPAxis::atTop)
  8478. painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8479. else if (type == QCPAxis::atBottom)
  8480. painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8481. }
  8482. // set selection boxes:
  8483. int selectionTolerance = 0;
  8484. if (mParentPlot)
  8485. selectionTolerance = mParentPlot->selectionTolerance();
  8486. else
  8487. qDebug() << Q_FUNC_INFO << "mParentPlot is null";
  8488. int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance);
  8489. int selAxisInSize = selectionTolerance;
  8490. int selTickLabelSize;
  8491. int selTickLabelOffset;
  8492. if (tickLabelSide == QCPAxis::lsOutside)
  8493. {
  8494. selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
  8495. selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding;
  8496. } else
  8497. {
  8498. selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
  8499. selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
  8500. }
  8501. int selLabelSize = labelBounds.height();
  8502. int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding;
  8503. if (type == QCPAxis::atLeft)
  8504. {
  8505. mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom());
  8506. mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom());
  8507. mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom());
  8508. } else if (type == QCPAxis::atRight)
  8509. {
  8510. mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom());
  8511. mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom());
  8512. mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom());
  8513. } else if (type == QCPAxis::atTop)
  8514. {
  8515. mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize);
  8516. mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset);
  8517. mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset);
  8518. } else if (type == QCPAxis::atBottom)
  8519. {
  8520. mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize);
  8521. mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset);
  8522. mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset);
  8523. }
  8524. mAxisSelectionBox = mAxisSelectionBox.normalized();
  8525. mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized();
  8526. mLabelSelectionBox = mLabelSelectionBox.normalized();
  8527. // draw hitboxes for debug purposes:
  8528. //painter->setBrush(Qt::NoBrush);
  8529. //painter->drawRects(QVector<QRect>() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox);
  8530. }
  8531. /*! \internal
  8532. Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
  8533. direction) needed to fit the axis.
  8534. */
  8535. int QCPAxisPainterPrivate::size()
  8536. {
  8537. int result = 0;
  8538. QByteArray newHash = generateLabelParameterHash();
  8539. if (newHash != mLabelParameterHash)
  8540. {
  8541. mLabelCache.clear();
  8542. mLabelParameterHash = newHash;
  8543. }
  8544. // get length of tick marks pointing outwards:
  8545. if (!tickPositions.isEmpty())
  8546. result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  8547. // calculate size of tick labels:
  8548. if (tickLabelSide == QCPAxis::lsOutside)
  8549. {
  8550. QSize tickLabelsSize(0, 0);
  8551. if (!tickLabels.isEmpty())
  8552. {
  8553. foreach (const QString &tickLabel, tickLabels)
  8554. getMaxTickLabelSize(tickLabelFont, tickLabel, &tickLabelsSize);
  8555. result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
  8556. result += tickLabelPadding;
  8557. }
  8558. }
  8559. // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
  8560. if (!label.isEmpty())
  8561. {
  8562. QFontMetrics fontMetrics(labelFont);
  8563. QRect bounds;
  8564. bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
  8565. result += bounds.height() + labelPadding;
  8566. }
  8567. return result;
  8568. }
  8569. /*! \internal
  8570. Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
  8571. method is called automatically in \ref draw, if any parameters have changed that invalidate the
  8572. cached labels, such as font, color, etc.
  8573. */
  8574. void QCPAxisPainterPrivate::clearCache()
  8575. {
  8576. mLabelCache.clear();
  8577. }
  8578. /*! \internal
  8579. Returns a hash that allows uniquely identifying whether the label parameters have changed such
  8580. that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
  8581. return value of this method hasn't changed since the last redraw, the respective label parameters
  8582. haven't changed and cached labels may be used.
  8583. */
  8584. QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const
  8585. {
  8586. QByteArray result;
  8587. result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio()));
  8588. result.append(QByteArray::number(tickLabelRotation));
  8589. result.append(QByteArray::number(int(tickLabelSide)));
  8590. result.append(QByteArray::number(int(substituteExponent)));
  8591. result.append(QByteArray::number(int(numberMultiplyCross)));
  8592. result.append(tickLabelColor.name().toLatin1()+QByteArray::number(tickLabelColor.alpha(), 16));
  8593. result.append(tickLabelFont.toString().toLatin1());
  8594. return result;
  8595. }
  8596. /*! \internal
  8597. Draws a single tick label with the provided \a painter, utilizing the internal label cache to
  8598. significantly speed up drawing of labels that were drawn in previous calls. The tick label is
  8599. always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
  8600. pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
  8601. for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
  8602. at which the label should be drawn.
  8603. In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
  8604. largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
  8605. drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
  8606. tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
  8607. holds.
  8608. The label is drawn with the font and pen that are currently set on the \a painter. To draw
  8609. superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
  8610. getTickLabelData).
  8611. */
  8612. void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize)
  8613. {
  8614. // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
  8615. if (text.isEmpty()) return;
  8616. QSize finalSize;
  8617. QPointF labelAnchor;
  8618. switch (type)
  8619. {
  8620. case QCPAxis::atLeft: labelAnchor = QPointF(axisRect.left()-distanceToAxis-offset, position); break;
  8621. case QCPAxis::atRight: labelAnchor = QPointF(axisRect.right()+distanceToAxis+offset, position); break;
  8622. case QCPAxis::atTop: labelAnchor = QPointF(position, axisRect.top()-distanceToAxis-offset); break;
  8623. case QCPAxis::atBottom: labelAnchor = QPointF(position, axisRect.bottom()+distanceToAxis+offset); break;
  8624. }
  8625. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
  8626. {
  8627. CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache
  8628. if (!cachedLabel) // no cached label existed, create it
  8629. {
  8630. cachedLabel = new CachedLabel;
  8631. TickLabelData labelData = getTickLabelData(painter->font(), text);
  8632. cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft();
  8633. if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio()))
  8634. {
  8635. cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio());
  8636. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  8637. # ifdef QCP_DEVICEPIXELRATIO_FLOAT
  8638. cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF());
  8639. # else
  8640. cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio());
  8641. # endif
  8642. #endif
  8643. } else
  8644. cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
  8645. cachedLabel->pixmap.fill(Qt::transparent);
  8646. QCPPainter cachePainter(&cachedLabel->pixmap);
  8647. cachePainter.setPen(painter->pen());
  8648. drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData);
  8649. }
  8650. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  8651. bool labelClippedByBorder = false;
  8652. if (tickLabelSide == QCPAxis::lsOutside)
  8653. {
  8654. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8655. labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
  8656. else
  8657. labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
  8658. }
  8659. if (!labelClippedByBorder)
  8660. {
  8661. painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap);
  8662. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
  8663. }
  8664. mLabelCache.insert(text, cachedLabel); // return label to cache or insert for the first time if newly created
  8665. } else // label caching disabled, draw text directly on surface:
  8666. {
  8667. TickLabelData labelData = getTickLabelData(painter->font(), text);
  8668. QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData);
  8669. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  8670. bool labelClippedByBorder = false;
  8671. if (tickLabelSide == QCPAxis::lsOutside)
  8672. {
  8673. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8674. labelClippedByBorder = finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left();
  8675. else
  8676. labelClippedByBorder = finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top();
  8677. }
  8678. if (!labelClippedByBorder)
  8679. {
  8680. drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData);
  8681. finalSize = labelData.rotatedTotalBounds.size();
  8682. }
  8683. }
  8684. // expand passed tickLabelsSize if current tick label is larger:
  8685. if (finalSize.width() > tickLabelsSize->width())
  8686. tickLabelsSize->setWidth(finalSize.width());
  8687. if (finalSize.height() > tickLabelsSize->height())
  8688. tickLabelsSize->setHeight(finalSize.height());
  8689. }
  8690. /*! \internal
  8691. This is a \ref placeTickLabel helper function.
  8692. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
  8693. y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
  8694. directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
  8695. QCP::phCacheLabels plotting hint is not set.
  8696. */
  8697. void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const
  8698. {
  8699. // backup painter settings that we're about to change:
  8700. QTransform oldTransform = painter->transform();
  8701. QFont oldFont = painter->font();
  8702. // transform painter to position/rotation:
  8703. painter->translate(x, y);
  8704. if (!qFuzzyIsNull(tickLabelRotation))
  8705. painter->rotate(tickLabelRotation);
  8706. // draw text:
  8707. if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used
  8708. {
  8709. painter->setFont(labelData.baseFont);
  8710. painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
  8711. if (!labelData.suffixPart.isEmpty())
  8712. painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart);
  8713. painter->setFont(labelData.expFont);
  8714. painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
  8715. } else
  8716. {
  8717. painter->setFont(labelData.baseFont);
  8718. painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
  8719. }
  8720. // reset painter settings to what it was before:
  8721. painter->setTransform(oldTransform);
  8722. painter->setFont(oldFont);
  8723. }
  8724. /*! \internal
  8725. This is a \ref placeTickLabel helper function.
  8726. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
  8727. processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
  8728. exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
  8729. */
  8730. QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const
  8731. {
  8732. TickLabelData result;
  8733. // determine whether beautiful decimal powers should be used
  8734. bool useBeautifulPowers = false;
  8735. int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
  8736. int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
  8737. if (substituteExponent)
  8738. {
  8739. ePos = text.indexOf(QLatin1Char('e'));
  8740. if (ePos > 0 && text.at(ePos-1).isDigit())
  8741. {
  8742. eLast = ePos;
  8743. while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
  8744. ++eLast;
  8745. if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
  8746. useBeautifulPowers = true;
  8747. }
  8748. }
  8749. // calculate text bounding rects and do string preparation for beautiful decimal powers:
  8750. result.baseFont = font;
  8751. if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line
  8752. result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding
  8753. if (useBeautifulPowers)
  8754. {
  8755. // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
  8756. result.basePart = text.left(ePos);
  8757. result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent
  8758. // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
  8759. if (abbreviateDecimalPowers && result.basePart == QLatin1String("1"))
  8760. result.basePart = QLatin1String("10");
  8761. else
  8762. result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + QLatin1String("10");
  8763. result.expPart = text.mid(ePos+1, eLast-ePos);
  8764. // clip "+" and leading zeros off expPart:
  8765. while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
  8766. result.expPart.remove(1, 1);
  8767. if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
  8768. result.expPart.remove(0, 1);
  8769. // prepare smaller font for exponent:
  8770. result.expFont = font;
  8771. if (result.expFont.pointSize() > 0)
  8772. result.expFont.setPointSize(int(result.expFont.pointSize()*0.75));
  8773. else
  8774. result.expFont.setPixelSize(int(result.expFont.pixelSize()*0.75));
  8775. // calculate bounding rects of base part(s), exponent part and total one:
  8776. result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
  8777. result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
  8778. if (!result.suffixPart.isEmpty())
  8779. result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart);
  8780. result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+result.suffixBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA
  8781. } else // useBeautifulPowers == false
  8782. {
  8783. result.basePart = text;
  8784. result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
  8785. }
  8786. result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler
  8787. // calculate possibly different bounding rect after rotation:
  8788. result.rotatedTotalBounds = result.totalBounds;
  8789. if (!qFuzzyIsNull(tickLabelRotation))
  8790. {
  8791. QTransform transform;
  8792. transform.rotate(tickLabelRotation);
  8793. result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds);
  8794. }
  8795. return result;
  8796. }
  8797. /*! \internal
  8798. This is a \ref placeTickLabel helper function.
  8799. Calculates the offset at which the top left corner of the specified tick label shall be drawn.
  8800. The offset is relative to a point right next to the tick the label belongs to.
  8801. This function is thus responsible for e.g. centering tick labels under ticks and positioning them
  8802. appropriately when they are rotated.
  8803. */
  8804. QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const
  8805. {
  8806. /*
  8807. calculate label offset from base point at tick (non-trivial, for best visual appearance): short
  8808. explanation for bottom axis: The anchor, i.e. the point in the label that is placed
  8809. horizontally under the corresponding tick is always on the label side that is closer to the
  8810. axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height
  8811. is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text
  8812. will be centered under the tick (i.e. displaced horizontally by half its height). At the same
  8813. time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick
  8814. labels.
  8815. */
  8816. bool doRotation = !qFuzzyIsNull(tickLabelRotation);
  8817. bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes.
  8818. double radians = tickLabelRotation/180.0*M_PI;
  8819. double x = 0;
  8820. double y = 0;
  8821. if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label
  8822. {
  8823. if (doRotation)
  8824. {
  8825. if (tickLabelRotation > 0)
  8826. {
  8827. x = -qCos(radians)*labelData.totalBounds.width();
  8828. y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0;
  8829. } else
  8830. {
  8831. x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height();
  8832. y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0;
  8833. }
  8834. } else
  8835. {
  8836. x = -labelData.totalBounds.width();
  8837. y = -labelData.totalBounds.height()/2.0;
  8838. }
  8839. } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label
  8840. {
  8841. if (doRotation)
  8842. {
  8843. if (tickLabelRotation > 0)
  8844. {
  8845. x = +qSin(radians)*labelData.totalBounds.height();
  8846. y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0;
  8847. } else
  8848. {
  8849. x = 0;
  8850. y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0;
  8851. }
  8852. } else
  8853. {
  8854. x = 0;
  8855. y = -labelData.totalBounds.height()/2.0;
  8856. }
  8857. } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label
  8858. {
  8859. if (doRotation)
  8860. {
  8861. if (tickLabelRotation > 0)
  8862. {
  8863. x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0;
  8864. y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height();
  8865. } else
  8866. {
  8867. x = -qSin(-radians)*labelData.totalBounds.height()/2.0;
  8868. y = -qCos(-radians)*labelData.totalBounds.height();
  8869. }
  8870. } else
  8871. {
  8872. x = -labelData.totalBounds.width()/2.0;
  8873. y = -labelData.totalBounds.height();
  8874. }
  8875. } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label
  8876. {
  8877. if (doRotation)
  8878. {
  8879. if (tickLabelRotation > 0)
  8880. {
  8881. x = +qSin(radians)*labelData.totalBounds.height()/2.0;
  8882. y = 0;
  8883. } else
  8884. {
  8885. x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0;
  8886. y = +qSin(-radians)*labelData.totalBounds.width();
  8887. }
  8888. } else
  8889. {
  8890. x = -labelData.totalBounds.width()/2.0;
  8891. y = 0;
  8892. }
  8893. }
  8894. return {x, y};
  8895. }
  8896. /*! \internal
  8897. Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
  8898. to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
  8899. margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
  8900. smaller width/height.
  8901. */
  8902. void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const
  8903. {
  8904. // note: this function must return the same tick label sizes as the placeTickLabel function.
  8905. QSize finalSize;
  8906. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
  8907. {
  8908. const CachedLabel *cachedLabel = mLabelCache.object(text);
  8909. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
  8910. } else // label caching disabled or no label with this text cached:
  8911. {
  8912. TickLabelData labelData = getTickLabelData(font, text);
  8913. finalSize = labelData.rotatedTotalBounds.size();
  8914. }
  8915. // expand passed tickLabelsSize if current tick label is larger:
  8916. if (finalSize.width() > tickLabelsSize->width())
  8917. tickLabelsSize->setWidth(finalSize.width());
  8918. if (finalSize.height() > tickLabelsSize->height())
  8919. tickLabelsSize->setHeight(finalSize.height());
  8920. }
  8921. /* end of 'src/axis/axis.cpp' */
  8922. /* including file 'src/scatterstyle.cpp' */
  8923. /* modified 2021-03-29T02:30:44, size 17466 */
  8924. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8925. //////////////////// QCPScatterStyle
  8926. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8927. /*! \class QCPScatterStyle
  8928. \brief Represents the visual appearance of scatter points
  8929. This class holds information about shape, color and size of scatter points. In plottables like
  8930. QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
  8931. QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
  8932. A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
  8933. fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
  8934. be controlled with \ref setSize.
  8935. \section QCPScatterStyle-defining Specifying a scatter style
  8936. You can set all these configurations either by calling the respective functions on an instance:
  8937. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1
  8938. Or you can use one of the various constructors that take different parameter combinations, making
  8939. it easy to specify a scatter style in a single call, like so:
  8940. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2
  8941. \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
  8942. There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
  8943. QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
  8944. isPenDefined will return false. It leads to scatter points that inherit the pen from the
  8945. plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line
  8946. color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes
  8947. it very convenient to set up typical scatter settings:
  8948. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation
  8949. Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
  8950. because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
  8951. into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
  8952. constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
  8953. ScatterShape, where actually a QCPScatterStyle is expected.
  8954. \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
  8955. QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
  8956. For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
  8957. setCustomPath function or call the constructor that takes a painter path. The scatter shape will
  8958. automatically be set to \ref ssCustom.
  8959. For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
  8960. constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
  8961. Note that \ref setSize does not influence the appearance of the pixmap.
  8962. */
  8963. /* start documentation of inline functions */
  8964. /*! \fn bool QCPScatterStyle::isNone() const
  8965. Returns whether the scatter shape is \ref ssNone.
  8966. \see setShape
  8967. */
  8968. /*! \fn bool QCPScatterStyle::isPenDefined() const
  8969. Returns whether a pen has been defined for this scatter style.
  8970. The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those
  8971. are \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen
  8972. is undefined, the pen of the respective plottable will be used for drawing scatters.
  8973. If a pen was defined for this scatter style instance, and you now wish to undefine the pen, call
  8974. \ref undefinePen.
  8975. \see setPen
  8976. */
  8977. /* end documentation of inline functions */
  8978. /*!
  8979. Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
  8980. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  8981. from the plottable that uses this scatter style.
  8982. */
  8983. QCPScatterStyle::QCPScatterStyle() :
  8984. mSize(6),
  8985. mShape(ssNone),
  8986. mPen(Qt::NoPen),
  8987. mBrush(Qt::NoBrush),
  8988. mPenDefined(false)
  8989. {
  8990. }
  8991. /*!
  8992. Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
  8993. brush is defined.
  8994. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  8995. from the plottable that uses this scatter style.
  8996. */
  8997. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) :
  8998. mSize(size),
  8999. mShape(shape),
  9000. mPen(Qt::NoPen),
  9001. mBrush(Qt::NoBrush),
  9002. mPenDefined(false)
  9003. {
  9004. }
  9005. /*!
  9006. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  9007. and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
  9008. */
  9009. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) :
  9010. mSize(size),
  9011. mShape(shape),
  9012. mPen(QPen(color)),
  9013. mBrush(Qt::NoBrush),
  9014. mPenDefined(true)
  9015. {
  9016. }
  9017. /*!
  9018. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  9019. the brush color to \a fill (with a solid pattern), and size to \a size.
  9020. */
  9021. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) :
  9022. mSize(size),
  9023. mShape(shape),
  9024. mPen(QPen(color)),
  9025. mBrush(QBrush(fill)),
  9026. mPenDefined(true)
  9027. {
  9028. }
  9029. /*!
  9030. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
  9031. brush to \a brush, and size to \a size.
  9032. \warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen
  9033. and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n
  9034. <tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n
  9035. doesn't necessarily lead C++ to use this constructor in some cases, but might mistake
  9036. <tt>Qt::NoPen</tt> for a QColor and use the
  9037. \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size)
  9038. constructor instead (which will lead to an unexpected look of the scatter points). To prevent
  9039. this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt>
  9040. instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is
  9041. wanted.
  9042. */
  9043. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) :
  9044. mSize(size),
  9045. mShape(shape),
  9046. mPen(pen),
  9047. mBrush(brush),
  9048. mPenDefined(pen.style() != Qt::NoPen)
  9049. {
  9050. }
  9051. /*!
  9052. Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
  9053. is set to \ref ssPixmap.
  9054. */
  9055. QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) :
  9056. mSize(5),
  9057. mShape(ssPixmap),
  9058. mPen(Qt::NoPen),
  9059. mBrush(Qt::NoBrush),
  9060. mPixmap(pixmap),
  9061. mPenDefined(false)
  9062. {
  9063. }
  9064. /*!
  9065. Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
  9066. scatter shape is set to \ref ssCustom.
  9067. The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
  9068. different meaning than for built-in scatter points: The custom path will be drawn scaled by a
  9069. factor of \a size/6.0. Since the default \a size is 6, the custom path will appear in its
  9070. original size by default. To for example double the size of the path, set \a size to 12.
  9071. */
  9072. QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) :
  9073. mSize(size),
  9074. mShape(ssCustom),
  9075. mPen(pen),
  9076. mBrush(brush),
  9077. mCustomPath(customPath),
  9078. mPenDefined(pen.style() != Qt::NoPen)
  9079. {
  9080. }
  9081. /*!
  9082. Copies the specified \a properties from the \a other scatter style to this scatter style.
  9083. */
  9084. void QCPScatterStyle::setFromOther(const QCPScatterStyle &other, ScatterProperties properties)
  9085. {
  9086. if (properties.testFlag(spPen))
  9087. {
  9088. setPen(other.pen());
  9089. if (!other.isPenDefined())
  9090. undefinePen();
  9091. }
  9092. if (properties.testFlag(spBrush))
  9093. setBrush(other.brush());
  9094. if (properties.testFlag(spSize))
  9095. setSize(other.size());
  9096. if (properties.testFlag(spShape))
  9097. {
  9098. setShape(other.shape());
  9099. if (other.shape() == ssPixmap)
  9100. setPixmap(other.pixmap());
  9101. else if (other.shape() == ssCustom)
  9102. setCustomPath(other.customPath());
  9103. }
  9104. }
  9105. /*!
  9106. Sets the size (pixel diameter) of the drawn scatter points to \a size.
  9107. \see setShape
  9108. */
  9109. void QCPScatterStyle::setSize(double size)
  9110. {
  9111. mSize = size;
  9112. }
  9113. /*!
  9114. Sets the shape to \a shape.
  9115. Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
  9116. ssPixmap and \ref ssCustom, respectively.
  9117. \see setSize
  9118. */
  9119. void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
  9120. {
  9121. mShape = shape;
  9122. }
  9123. /*!
  9124. Sets the pen that will be used to draw scatter points to \a pen.
  9125. If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
  9126. a call to this function, even if \a pen is <tt>Qt::NoPen</tt>. If you have defined a pen
  9127. previously by calling this function and now wish to undefine the pen, call \ref undefinePen.
  9128. \see setBrush
  9129. */
  9130. void QCPScatterStyle::setPen(const QPen &pen)
  9131. {
  9132. mPenDefined = true;
  9133. mPen = pen;
  9134. }
  9135. /*!
  9136. Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
  9137. shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
  9138. \see setPen
  9139. */
  9140. void QCPScatterStyle::setBrush(const QBrush &brush)
  9141. {
  9142. mBrush = brush;
  9143. }
  9144. /*!
  9145. Sets the pixmap that will be drawn as scatter point to \a pixmap.
  9146. Note that \ref setSize does not influence the appearance of the pixmap.
  9147. The scatter shape is automatically set to \ref ssPixmap.
  9148. */
  9149. void QCPScatterStyle::setPixmap(const QPixmap &pixmap)
  9150. {
  9151. setShape(ssPixmap);
  9152. mPixmap = pixmap;
  9153. }
  9154. /*!
  9155. Sets the custom shape that will be drawn as scatter point to \a customPath.
  9156. The scatter shape is automatically set to \ref ssCustom.
  9157. */
  9158. void QCPScatterStyle::setCustomPath(const QPainterPath &customPath)
  9159. {
  9160. setShape(ssCustom);
  9161. mCustomPath = customPath;
  9162. }
  9163. /*!
  9164. Sets this scatter style to have an undefined pen (see \ref isPenDefined for what an undefined pen
  9165. implies).
  9166. A call to \ref setPen will define a pen.
  9167. */
  9168. void QCPScatterStyle::undefinePen()
  9169. {
  9170. mPenDefined = false;
  9171. }
  9172. /*!
  9173. Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
  9174. undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
  9175. This function is used by plottables (or any class that wants to draw scatters) just before a
  9176. number of scatters with this style shall be drawn with the \a painter.
  9177. \see drawShape
  9178. */
  9179. void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const
  9180. {
  9181. painter->setPen(mPenDefined ? mPen : defaultPen);
  9182. painter->setBrush(mBrush);
  9183. }
  9184. /*!
  9185. Draws the scatter shape with \a painter at position \a pos.
  9186. This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
  9187. called before scatter points are drawn with \ref drawShape.
  9188. \see applyTo
  9189. */
  9190. void QCPScatterStyle::drawShape(QCPPainter *painter, const QPointF &pos) const
  9191. {
  9192. drawShape(painter, pos.x(), pos.y());
  9193. }
  9194. /*! \overload
  9195. Draws the scatter shape with \a painter at position \a x and \a y.
  9196. */
  9197. void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const
  9198. {
  9199. double w = mSize/2.0;
  9200. switch (mShape)
  9201. {
  9202. case ssNone: break;
  9203. case ssDot:
  9204. {
  9205. painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y));
  9206. break;
  9207. }
  9208. case ssCross:
  9209. {
  9210. painter->drawLine(QLineF(x-w, y-w, x+w, y+w));
  9211. painter->drawLine(QLineF(x-w, y+w, x+w, y-w));
  9212. break;
  9213. }
  9214. case ssPlus:
  9215. {
  9216. painter->drawLine(QLineF(x-w, y, x+w, y));
  9217. painter->drawLine(QLineF( x, y+w, x, y-w));
  9218. break;
  9219. }
  9220. case ssCircle:
  9221. {
  9222. painter->drawEllipse(QPointF(x , y), w, w);
  9223. break;
  9224. }
  9225. case ssDisc:
  9226. {
  9227. QBrush b = painter->brush();
  9228. painter->setBrush(painter->pen().color());
  9229. painter->drawEllipse(QPointF(x , y), w, w);
  9230. painter->setBrush(b);
  9231. break;
  9232. }
  9233. case ssSquare:
  9234. {
  9235. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  9236. break;
  9237. }
  9238. case ssDiamond:
  9239. {
  9240. QPointF lineArray[4] = {QPointF(x-w, y),
  9241. QPointF( x, y-w),
  9242. QPointF(x+w, y),
  9243. QPointF( x, y+w)};
  9244. painter->drawPolygon(lineArray, 4);
  9245. break;
  9246. }
  9247. case ssStar:
  9248. {
  9249. painter->drawLine(QLineF(x-w, y, x+w, y));
  9250. painter->drawLine(QLineF( x, y+w, x, y-w));
  9251. painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707));
  9252. painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707));
  9253. break;
  9254. }
  9255. case ssTriangle:
  9256. {
  9257. QPointF lineArray[3] = {QPointF(x-w, y+0.755*w),
  9258. QPointF(x+w, y+0.755*w),
  9259. QPointF( x, y-0.977*w)};
  9260. painter->drawPolygon(lineArray, 3);
  9261. break;
  9262. }
  9263. case ssTriangleInverted:
  9264. {
  9265. QPointF lineArray[3] = {QPointF(x-w, y-0.755*w),
  9266. QPointF(x+w, y-0.755*w),
  9267. QPointF( x, y+0.977*w)};
  9268. painter->drawPolygon(lineArray, 3);
  9269. break;
  9270. }
  9271. case ssCrossSquare:
  9272. {
  9273. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  9274. painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95));
  9275. painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w));
  9276. break;
  9277. }
  9278. case ssPlusSquare:
  9279. {
  9280. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  9281. painter->drawLine(QLineF(x-w, y, x+w*0.95, y));
  9282. painter->drawLine(QLineF( x, y+w, x, y-w));
  9283. break;
  9284. }
  9285. case ssCrossCircle:
  9286. {
  9287. painter->drawEllipse(QPointF(x, y), w, w);
  9288. painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670));
  9289. painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707));
  9290. break;
  9291. }
  9292. case ssPlusCircle:
  9293. {
  9294. painter->drawEllipse(QPointF(x, y), w, w);
  9295. painter->drawLine(QLineF(x-w, y, x+w, y));
  9296. painter->drawLine(QLineF( x, y+w, x, y-w));
  9297. break;
  9298. }
  9299. case ssPeace:
  9300. {
  9301. painter->drawEllipse(QPointF(x, y), w, w);
  9302. painter->drawLine(QLineF(x, y-w, x, y+w));
  9303. painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707));
  9304. painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707));
  9305. break;
  9306. }
  9307. case ssPixmap:
  9308. {
  9309. const double widthHalf = mPixmap.width()*0.5;
  9310. const double heightHalf = mPixmap.height()*0.5;
  9311. #if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
  9312. const QRectF clipRect = painter->clipRegion().boundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
  9313. #else
  9314. const QRectF clipRect = painter->clipBoundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
  9315. #endif
  9316. if (clipRect.contains(x, y))
  9317. painter->drawPixmap(qRound(x-widthHalf), qRound(y-heightHalf), mPixmap);
  9318. break;
  9319. }
  9320. case ssCustom:
  9321. {
  9322. QTransform oldTransform = painter->transform();
  9323. painter->translate(x, y);
  9324. painter->scale(mSize/6.0, mSize/6.0);
  9325. painter->drawPath(mCustomPath);
  9326. painter->setTransform(oldTransform);
  9327. break;
  9328. }
  9329. }
  9330. }
  9331. /* end of 'src/scatterstyle.cpp' */
  9332. /* including file 'src/plottable.cpp' */
  9333. /* modified 2021-03-29T02:30:44, size 38818 */
  9334. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9335. //////////////////// QCPSelectionDecorator
  9336. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9337. /*! \class QCPSelectionDecorator
  9338. \brief Controls how a plottable's data selection is drawn
  9339. Each \ref QCPAbstractPlottable instance has one \ref QCPSelectionDecorator (accessible via \ref
  9340. QCPAbstractPlottable::selectionDecorator) and uses it when drawing selected segments of its data.
  9341. The selection decorator controls both pen (\ref setPen) and brush (\ref setBrush), as well as the
  9342. scatter style (\ref setScatterStyle) if the plottable draws scatters. Since a \ref
  9343. QCPScatterStyle is itself composed of different properties such as color shape and size, the
  9344. decorator allows specifying exactly which of those properties shall be used for the selected data
  9345. point, via \ref setUsedScatterProperties.
  9346. A \ref QCPSelectionDecorator subclass instance can be passed to a plottable via \ref
  9347. QCPAbstractPlottable::setSelectionDecorator, allowing greater customizability of the appearance
  9348. of selected segments.
  9349. Use \ref copyFrom to easily transfer the settings of one decorator to another one. This is
  9350. especially useful since plottables take ownership of the passed selection decorator, and thus the
  9351. same decorator instance can not be passed to multiple plottables.
  9352. Selection decorators can also themselves perform drawing operations by reimplementing \ref
  9353. drawDecoration, which is called by the plottable's draw method. The base class \ref
  9354. QCPSelectionDecorator does not make use of this however. For example, \ref
  9355. QCPSelectionDecoratorBracket draws brackets around selected data segments.
  9356. */
  9357. /*!
  9358. Creates a new QCPSelectionDecorator instance with default values
  9359. */
  9360. QCPSelectionDecorator::QCPSelectionDecorator() :
  9361. mPen(QColor(80, 80, 255), 2.5),
  9362. mBrush(Qt::NoBrush),
  9363. mUsedScatterProperties(QCPScatterStyle::spNone),
  9364. mPlottable(nullptr)
  9365. {
  9366. }
  9367. QCPSelectionDecorator::~QCPSelectionDecorator()
  9368. {
  9369. }
  9370. /*!
  9371. Sets the pen that will be used by the parent plottable to draw selected data segments.
  9372. */
  9373. void QCPSelectionDecorator::setPen(const QPen &pen)
  9374. {
  9375. mPen = pen;
  9376. }
  9377. /*!
  9378. Sets the brush that will be used by the parent plottable to draw selected data segments.
  9379. */
  9380. void QCPSelectionDecorator::setBrush(const QBrush &brush)
  9381. {
  9382. mBrush = brush;
  9383. }
  9384. /*!
  9385. Sets the scatter style that will be used by the parent plottable to draw scatters in selected
  9386. data segments.
  9387. \a usedProperties specifies which parts of the passed \a scatterStyle will be used by the
  9388. plottable. The used properties can also be changed via \ref setUsedScatterProperties.
  9389. */
  9390. void QCPSelectionDecorator::setScatterStyle(const QCPScatterStyle &scatterStyle, QCPScatterStyle::ScatterProperties usedProperties)
  9391. {
  9392. mScatterStyle = scatterStyle;
  9393. setUsedScatterProperties(usedProperties);
  9394. }
  9395. /*!
  9396. Use this method to define which properties of the scatter style (set via \ref setScatterStyle)
  9397. will be used for selected data segments. All properties of the scatter style that are not
  9398. specified in \a properties will remain as specified in the plottable's original scatter style.
  9399. \see QCPScatterStyle::ScatterProperty
  9400. */
  9401. void QCPSelectionDecorator::setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties)
  9402. {
  9403. mUsedScatterProperties = properties;
  9404. }
  9405. /*!
  9406. Sets the pen of \a painter to the pen of this selection decorator.
  9407. \see applyBrush, getFinalScatterStyle
  9408. */
  9409. void QCPSelectionDecorator::applyPen(QCPPainter *painter) const
  9410. {
  9411. painter->setPen(mPen);
  9412. }
  9413. /*!
  9414. Sets the brush of \a painter to the brush of this selection decorator.
  9415. \see applyPen, getFinalScatterStyle
  9416. */
  9417. void QCPSelectionDecorator::applyBrush(QCPPainter *painter) const
  9418. {
  9419. painter->setBrush(mBrush);
  9420. }
  9421. /*!
  9422. Returns the scatter style that the parent plottable shall use for selected scatter points. The
  9423. plottable's original (unselected) scatter style must be passed as \a unselectedStyle. Depending
  9424. on the setting of \ref setUsedScatterProperties, the returned scatter style is a mixture of this
  9425. selecion decorator's scatter style (\ref setScatterStyle), and \a unselectedStyle.
  9426. \see applyPen, applyBrush, setScatterStyle
  9427. */
  9428. QCPScatterStyle QCPSelectionDecorator::getFinalScatterStyle(const QCPScatterStyle &unselectedStyle) const
  9429. {
  9430. QCPScatterStyle result(unselectedStyle);
  9431. result.setFromOther(mScatterStyle, mUsedScatterProperties);
  9432. // if style shall inherit pen from plottable (has no own pen defined), give it the selected
  9433. // plottable pen explicitly, so it doesn't use the unselected plottable pen when used in the
  9434. // plottable:
  9435. if (!result.isPenDefined())
  9436. result.setPen(mPen);
  9437. return result;
  9438. }
  9439. /*!
  9440. Copies all properties (e.g. color, fill, scatter style) of the \a other selection decorator to
  9441. this selection decorator.
  9442. */
  9443. void QCPSelectionDecorator::copyFrom(const QCPSelectionDecorator *other)
  9444. {
  9445. setPen(other->pen());
  9446. setBrush(other->brush());
  9447. setScatterStyle(other->scatterStyle(), other->usedScatterProperties());
  9448. }
  9449. /*!
  9450. This method is called by all plottables' draw methods to allow custom selection decorations to be
  9451. drawn. Use the passed \a painter to perform the drawing operations. \a selection carries the data
  9452. selection for which the decoration shall be drawn.
  9453. The default base class implementation of \ref QCPSelectionDecorator has no special decoration, so
  9454. this method does nothing.
  9455. */
  9456. void QCPSelectionDecorator::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
  9457. {
  9458. Q_UNUSED(painter)
  9459. Q_UNUSED(selection)
  9460. }
  9461. /*! \internal
  9462. This method is called as soon as a selection decorator is associated with a plottable, by a call
  9463. to \ref QCPAbstractPlottable::setSelectionDecorator. This way the selection decorator can obtain a pointer to the plottable that uses it (e.g. to access
  9464. data points via the \ref QCPAbstractPlottable::interface1D interface).
  9465. If the selection decorator was already added to a different plottable before, this method aborts
  9466. the registration and returns false.
  9467. */
  9468. bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottable)
  9469. {
  9470. if (!mPlottable)
  9471. {
  9472. mPlottable = plottable;
  9473. return true;
  9474. } else
  9475. {
  9476. qDebug() << Q_FUNC_INFO << "This selection decorator is already registered with plottable:" << reinterpret_cast<quintptr>(mPlottable);
  9477. return false;
  9478. }
  9479. }
  9480. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9481. //////////////////// QCPAbstractPlottable
  9482. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9483. /*! \class QCPAbstractPlottable
  9484. \brief The abstract base class for all data representing objects in a plot.
  9485. It defines a very basic interface like name, pen, brush, visibility etc. Since this class is
  9486. abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to
  9487. create new ways of displaying data (see "Creating own plottables" below). Plottables that display
  9488. one-dimensional data (i.e. data points have a single key dimension and one or multiple values at
  9489. each key) are based off of the template subclass \ref QCPAbstractPlottable1D, see details
  9490. there.
  9491. All further specifics are in the subclasses, for example:
  9492. \li A normal graph with possibly a line and/or scatter points \ref QCPGraph
  9493. (typically created with \ref QCustomPlot::addGraph)
  9494. \li A parametric curve: \ref QCPCurve
  9495. \li A bar chart: \ref QCPBars
  9496. \li A statistical box plot: \ref QCPStatisticalBox
  9497. \li A color encoded two-dimensional map: \ref QCPColorMap
  9498. \li An OHLC/Candlestick chart: \ref QCPFinancial
  9499. \section plottables-subclassing Creating own plottables
  9500. Subclassing directly from QCPAbstractPlottable is only recommended if you wish to display
  9501. two-dimensional data like \ref QCPColorMap, i.e. two logical key dimensions and one (or more)
  9502. data dimensions. If you want to display data with only one logical key dimension, you should
  9503. rather derive from \ref QCPAbstractPlottable1D.
  9504. If subclassing QCPAbstractPlottable directly, these are the pure virtual functions you must
  9505. implement:
  9506. \li \ref selectTest
  9507. \li \ref draw
  9508. \li \ref drawLegendIcon
  9509. \li \ref getKeyRange
  9510. \li \ref getValueRange
  9511. See the documentation of those functions for what they need to do.
  9512. For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot
  9513. coordinates to pixel coordinates. This function is quite convenient, because it takes the
  9514. orientation of the key and value axes into account for you (x and y are swapped when the key axis
  9515. is vertical and the value axis horizontal). If you are worried about performance (i.e. you need
  9516. to translate many points in a loop like QCPGraph), you can directly use \ref
  9517. QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis
  9518. yourself.
  9519. Here are some important members you inherit from QCPAbstractPlottable:
  9520. <table>
  9521. <tr>
  9522. <td>QCustomPlot *\b mParentPlot</td>
  9523. <td>A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.</td>
  9524. </tr><tr>
  9525. <td>QString \b mName</td>
  9526. <td>The name of the plottable.</td>
  9527. </tr><tr>
  9528. <td>QPen \b mPen</td>
  9529. <td>The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable
  9530. (e.g QCPGraph uses this pen for its graph lines and scatters)</td>
  9531. </tr><tr>
  9532. <td>QBrush \b mBrush</td>
  9533. <td>The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable
  9534. (e.g. QCPGraph uses this brush to control filling under the graph)</td>
  9535. </tr><tr>
  9536. <td>QPointer<\ref QCPAxis> \b mKeyAxis, \b mValueAxis</td>
  9537. <td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates
  9538. to pixels in either the key or value dimension. Make sure to check whether the pointer is \c nullptr before using it. If one of
  9539. the axes is null, don't draw the plottable.</td>
  9540. </tr><tr>
  9541. <td>\ref QCPSelectionDecorator \b mSelectionDecorator</td>
  9542. <td>The currently set selection decorator which specifies how selected data of the plottable shall be drawn and decorated.
  9543. When drawing your data, you must consult this decorator for the appropriate pen/brush before drawing unselected/selected data segments.
  9544. Finally, you should call its \ref QCPSelectionDecorator::drawDecoration method at the end of your \ref draw implementation.</td>
  9545. </tr><tr>
  9546. <td>\ref QCP::SelectionType \b mSelectable</td>
  9547. <td>In which composition, if at all, this plottable's data may be selected. Enforcing this setting on the data selection is done
  9548. by QCPAbstractPlottable automatically.</td>
  9549. </tr><tr>
  9550. <td>\ref QCPDataSelection \b mSelection</td>
  9551. <td>Holds the current selection state of the plottable's data, i.e. the selected data ranges (\ref QCPDataRange).</td>
  9552. </tr>
  9553. </table>
  9554. */
  9555. /* start of documentation of inline functions */
  9556. /*! \fn QCPSelectionDecorator *QCPAbstractPlottable::selectionDecorator() const
  9557. Provides access to the selection decorator of this plottable. The selection decorator controls
  9558. how selected data ranges are drawn (e.g. their pen color and fill), see \ref
  9559. QCPSelectionDecorator for details.
  9560. If you wish to use an own \ref QCPSelectionDecorator subclass, pass an instance of it to \ref
  9561. setSelectionDecorator.
  9562. */
  9563. /*! \fn bool QCPAbstractPlottable::selected() const
  9564. Returns true if there are any data points of the plottable currently selected. Use \ref selection
  9565. to retrieve the current \ref QCPDataSelection.
  9566. */
  9567. /*! \fn QCPDataSelection QCPAbstractPlottable::selection() const
  9568. Returns a \ref QCPDataSelection encompassing all the data points that are currently selected on
  9569. this plottable.
  9570. \see selected, setSelection, setSelectable
  9571. */
  9572. /*! \fn virtual QCPPlottableInterface1D *QCPAbstractPlottable::interface1D()
  9573. If this plottable is a one-dimensional plottable, i.e. it implements the \ref
  9574. QCPPlottableInterface1D, returns the \a this pointer with that type. Otherwise (e.g. in the case
  9575. of a \ref QCPColorMap) returns zero.
  9576. You can use this method to gain read access to data coordinates while holding a pointer to the
  9577. abstract base class only.
  9578. */
  9579. /* end of documentation of inline functions */
  9580. /* start of documentation of pure virtual functions */
  9581. /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0
  9582. \internal
  9583. called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation
  9584. of this plottable inside \a rect, next to the plottable name.
  9585. The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't
  9586. appear outside the legend icon border.
  9587. */
  9588. /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const = 0
  9589. Returns the coordinate range that all data in this plottable span in the key axis dimension. For
  9590. logarithmic plots, one can set \a inSignDomain to either \ref QCP::sdNegative or \ref
  9591. QCP::sdPositive in order to restrict the returned range to that sign domain. E.g. when only
  9592. negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and all positive points
  9593. will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref
  9594. QCP::sdBoth (default). \a foundRange is an output parameter that indicates whether a range could
  9595. be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data).
  9596. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  9597. this function may have size zero (e.g. when there is only one data point). In this case \a
  9598. foundRange would return true, but the returned range is not a valid range in terms of \ref
  9599. QCPRange::validRange.
  9600. \see rescaleAxes, getValueRange
  9601. */
  9602. /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const = 0
  9603. Returns the coordinate range that the data points in the specified key range (\a inKeyRange) span
  9604. in the value axis dimension. For logarithmic plots, one can set \a inSignDomain to either \ref
  9605. QCP::sdNegative or \ref QCP::sdPositive in order to restrict the returned range to that sign
  9606. domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref QCP::sdNegative and
  9607. all positive points will be ignored for range calculation. For no restriction, just set \a
  9608. inSignDomain to \ref QCP::sdBoth (default). \a foundRange is an output parameter that indicates
  9609. whether a range could be found or not. If this is false, you shouldn't use the returned range
  9610. (e.g. no points in data).
  9611. If \a inKeyRange has both lower and upper bound set to zero (is equal to <tt>QCPRange()</tt>),
  9612. all data points are considered, without any restriction on the keys.
  9613. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  9614. this function may have size zero (e.g. when there is only one data point). In this case \a
  9615. foundRange would return true, but the returned range is not a valid range in terms of \ref
  9616. QCPRange::validRange.
  9617. \see rescaleAxes, getKeyRange
  9618. */
  9619. /* end of documentation of pure virtual functions */
  9620. /* start of documentation of signals */
  9621. /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected)
  9622. This signal is emitted when the selection state of this plottable has changed, either by user
  9623. interaction or by a direct call to \ref setSelection. The parameter \a selected indicates whether
  9624. there are any points selected or not.
  9625. \see selectionChanged(const QCPDataSelection &selection)
  9626. */
  9627. /*! \fn void QCPAbstractPlottable::selectionChanged(const QCPDataSelection &selection)
  9628. This signal is emitted when the selection state of this plottable has changed, either by user
  9629. interaction or by a direct call to \ref setSelection. The parameter \a selection holds the
  9630. currently selected data ranges.
  9631. \see selectionChanged(bool selected)
  9632. */
  9633. /*! \fn void QCPAbstractPlottable::selectableChanged(QCP::SelectionType selectable);
  9634. This signal is emitted when the selectability of this plottable has changed.
  9635. \see setSelectable
  9636. */
  9637. /* end of documentation of signals */
  9638. /*!
  9639. Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as
  9640. its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance
  9641. and have perpendicular orientations. If either of these restrictions is violated, a corresponding
  9642. message is printed to the debug output (qDebug), the construction is not aborted, though.
  9643. Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables,
  9644. it can't be directly instantiated.
  9645. You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead.
  9646. */
  9647. QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  9648. QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()),
  9649. mName(),
  9650. mAntialiasedFill(true),
  9651. mAntialiasedScatters(true),
  9652. mPen(Qt::black),
  9653. mBrush(Qt::NoBrush),
  9654. mKeyAxis(keyAxis),
  9655. mValueAxis(valueAxis),
  9656. mSelectable(QCP::stWhole),
  9657. mSelectionDecorator(nullptr)
  9658. {
  9659. if (keyAxis->parentPlot() != valueAxis->parentPlot())
  9660. qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
  9661. if (keyAxis->orientation() == valueAxis->orientation())
  9662. qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other.";
  9663. mParentPlot->registerPlottable(this);
  9664. setSelectionDecorator(new QCPSelectionDecorator);
  9665. }
  9666. QCPAbstractPlottable::~QCPAbstractPlottable()
  9667. {
  9668. if (mSelectionDecorator)
  9669. {
  9670. delete mSelectionDecorator;
  9671. mSelectionDecorator = nullptr;
  9672. }
  9673. }
  9674. /*!
  9675. The name is the textual representation of this plottable as it is displayed in the legend
  9676. (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
  9677. */
  9678. void QCPAbstractPlottable::setName(const QString &name)
  9679. {
  9680. mName = name;
  9681. }
  9682. /*!
  9683. Sets whether fills of this plottable are drawn antialiased or not.
  9684. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  9685. QCustomPlot::setNotAntialiasedElements.
  9686. */
  9687. void QCPAbstractPlottable::setAntialiasedFill(bool enabled)
  9688. {
  9689. mAntialiasedFill = enabled;
  9690. }
  9691. /*!
  9692. Sets whether the scatter symbols of this plottable are drawn antialiased or not.
  9693. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  9694. QCustomPlot::setNotAntialiasedElements.
  9695. */
  9696. void QCPAbstractPlottable::setAntialiasedScatters(bool enabled)
  9697. {
  9698. mAntialiasedScatters = enabled;
  9699. }
  9700. /*!
  9701. The pen is used to draw basic lines that make up the plottable representation in the
  9702. plot.
  9703. For example, the \ref QCPGraph subclass draws its graph lines with this pen.
  9704. \see setBrush
  9705. */
  9706. void QCPAbstractPlottable::setPen(const QPen &pen)
  9707. {
  9708. mPen = pen;
  9709. }
  9710. /*!
  9711. The brush is used to draw basic fills of the plottable representation in the
  9712. plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
  9713. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
  9714. it's not set to Qt::NoBrush.
  9715. \see setPen
  9716. */
  9717. void QCPAbstractPlottable::setBrush(const QBrush &brush)
  9718. {
  9719. mBrush = brush;
  9720. }
  9721. /*!
  9722. The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
  9723. to the plottable's value axis. This function performs no checks to make sure this is the case.
  9724. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
  9725. y-axis (QCustomPlot::yAxis) as value axis.
  9726. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  9727. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  9728. \see setValueAxis
  9729. */
  9730. void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis)
  9731. {
  9732. mKeyAxis = axis;
  9733. }
  9734. /*!
  9735. The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
  9736. orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
  9737. case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
  9738. the y-axis (QCustomPlot::yAxis) as value axis.
  9739. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  9740. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  9741. \see setKeyAxis
  9742. */
  9743. void QCPAbstractPlottable::setValueAxis(QCPAxis *axis)
  9744. {
  9745. mValueAxis = axis;
  9746. }
  9747. /*!
  9748. Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
  9749. (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
  9750. selectionDecorator).
  9751. The entire selection mechanism for plottables is handled automatically when \ref
  9752. QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
  9753. you wish to change the selection state programmatically.
  9754. Using \ref setSelectable you can further specify for each plottable whether and to which
  9755. granularity it is selectable. If \a selection is not compatible with the current \ref
  9756. QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
  9757. accordingly (see \ref QCPDataSelection::enforceType).
  9758. Q_EMITs the \ref selectionChanged signal when \a selected is different from the previous selection state.
  9759. \see setSelectable, selectTest
  9760. */
  9761. void QCPAbstractPlottable::setSelection(QCPDataSelection selection)
  9762. {
  9763. selection.enforceType(mSelectable);
  9764. if (mSelection != selection)
  9765. {
  9766. mSelection = selection;
  9767. Q_EMIT selectionChanged(selected());
  9768. Q_EMIT selectionChanged(mSelection);
  9769. }
  9770. }
  9771. /*!
  9772. Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
  9773. customize the visual representation of selected data ranges further than by using the default
  9774. QCPSelectionDecorator.
  9775. The plottable takes ownership of the \a decorator.
  9776. The currently set decorator can be accessed via \ref selectionDecorator.
  9777. */
  9778. void QCPAbstractPlottable::setSelectionDecorator(QCPSelectionDecorator *decorator)
  9779. {
  9780. if (decorator)
  9781. {
  9782. if (decorator->registerWithPlottable(this))
  9783. {
  9784. delete mSelectionDecorator; // delete old decorator if necessary
  9785. mSelectionDecorator = decorator;
  9786. }
  9787. } else if (mSelectionDecorator) // just clear decorator
  9788. {
  9789. delete mSelectionDecorator;
  9790. mSelectionDecorator = nullptr;
  9791. }
  9792. }
  9793. /*!
  9794. Sets whether and to which granularity this plottable can be selected.
  9795. A selection can happen by clicking on the QCustomPlot surface (When \ref
  9796. QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
  9797. (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
  9798. calling \ref setSelection.
  9799. \see setSelection, QCP::SelectionType
  9800. */
  9801. void QCPAbstractPlottable::setSelectable(QCP::SelectionType selectable)
  9802. {
  9803. if (mSelectable != selectable)
  9804. {
  9805. mSelectable = selectable;
  9806. QCPDataSelection oldSelection = mSelection;
  9807. mSelection.enforceType(mSelectable);
  9808. Q_EMIT selectableChanged(mSelectable);
  9809. if (mSelection != oldSelection)
  9810. {
  9811. Q_EMIT selectionChanged(selected());
  9812. Q_EMIT selectionChanged(mSelection);
  9813. }
  9814. }
  9815. }
  9816. /*!
  9817. Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
  9818. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  9819. represents x or y).
  9820. \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
  9821. \see pixelsToCoords, QCPAxis::coordToPixel
  9822. */
  9823. void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const
  9824. {
  9825. QCPAxis *keyAxis = mKeyAxis.data();
  9826. QCPAxis *valueAxis = mValueAxis.data();
  9827. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  9828. if (keyAxis->orientation() == Qt::Horizontal)
  9829. {
  9830. x = keyAxis->coordToPixel(key);
  9831. y = valueAxis->coordToPixel(value);
  9832. } else
  9833. {
  9834. y = keyAxis->coordToPixel(key);
  9835. x = valueAxis->coordToPixel(value);
  9836. }
  9837. }
  9838. /*! \overload
  9839. Transforms the given \a key and \a value to pixel coordinates and returns them in a QPointF.
  9840. */
  9841. const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
  9842. {
  9843. QCPAxis *keyAxis = mKeyAxis.data();
  9844. QCPAxis *valueAxis = mValueAxis.data();
  9845. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
  9846. if (keyAxis->orientation() == Qt::Horizontal)
  9847. return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
  9848. else
  9849. return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
  9850. }
  9851. /*!
  9852. Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates,
  9853. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  9854. represents x or y).
  9855. \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
  9856. \see coordsToPixels, QCPAxis::coordToPixel
  9857. */
  9858. void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const
  9859. {
  9860. QCPAxis *keyAxis = mKeyAxis.data();
  9861. QCPAxis *valueAxis = mValueAxis.data();
  9862. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  9863. if (keyAxis->orientation() == Qt::Horizontal)
  9864. {
  9865. key = keyAxis->pixelToCoord(x);
  9866. value = valueAxis->pixelToCoord(y);
  9867. } else
  9868. {
  9869. key = keyAxis->pixelToCoord(y);
  9870. value = valueAxis->pixelToCoord(x);
  9871. }
  9872. }
  9873. /*! \overload
  9874. Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
  9875. */
  9876. void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
  9877. {
  9878. pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
  9879. }
  9880. /*!
  9881. Rescales the key and value axes associated with this plottable to contain all displayed data, so
  9882. the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make
  9883. sure not to rescale to an illegal range i.e. a range containing different signs and/or zero.
  9884. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie
  9885. outside of that domain.
  9886. \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show
  9887. multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has
  9888. \a onlyEnlarge set to false (the default), and all subsequent set to true.
  9889. \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale
  9890. */
  9891. void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const
  9892. {
  9893. rescaleKeyAxis(onlyEnlarge);
  9894. rescaleValueAxis(onlyEnlarge);
  9895. }
  9896. /*!
  9897. Rescales the key axis of the plottable so the whole plottable is visible.
  9898. See \ref rescaleAxes for detailed behaviour.
  9899. */
  9900. void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
  9901. {
  9902. QCPAxis *keyAxis = mKeyAxis.data();
  9903. if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  9904. QCP::SignDomain signDomain = QCP::sdBoth;
  9905. if (keyAxis->scaleType() == QCPAxis::stLogarithmic)
  9906. signDomain = (keyAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  9907. bool foundRange;
  9908. QCPRange newRange = getKeyRange(foundRange, signDomain);
  9909. if (foundRange)
  9910. {
  9911. if (onlyEnlarge)
  9912. newRange.expand(keyAxis->range());
  9913. if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
  9914. {
  9915. double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
  9916. if (keyAxis->scaleType() == QCPAxis::stLinear)
  9917. {
  9918. newRange.lower = center-keyAxis->range().size()/2.0;
  9919. newRange.upper = center+keyAxis->range().size()/2.0;
  9920. } else // scaleType() == stLogarithmic
  9921. {
  9922. newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower);
  9923. newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower);
  9924. }
  9925. }
  9926. keyAxis->setRange(newRange);
  9927. }
  9928. }
  9929. /*!
  9930. Rescales the value axis of the plottable so the whole plottable is visible. If \a inKeyRange is
  9931. set to true, only the data points which are in the currently visible key axis range are
  9932. considered.
  9933. Returns true if the axis was actually scaled. This might not be the case if this plottable has an
  9934. invalid range, e.g. because it has no data points.
  9935. See \ref rescaleAxes for detailed behaviour.
  9936. */
  9937. void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
  9938. {
  9939. QCPAxis *keyAxis = mKeyAxis.data();
  9940. QCPAxis *valueAxis = mValueAxis.data();
  9941. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  9942. QCP::SignDomain signDomain = QCP::sdBoth;
  9943. if (valueAxis->scaleType() == QCPAxis::stLogarithmic)
  9944. signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  9945. bool foundRange;
  9946. QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
  9947. if (foundRange)
  9948. {
  9949. if (onlyEnlarge)
  9950. newRange.expand(valueAxis->range());
  9951. if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
  9952. {
  9953. double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
  9954. if (valueAxis->scaleType() == QCPAxis::stLinear)
  9955. {
  9956. newRange.lower = center-valueAxis->range().size()/2.0;
  9957. newRange.upper = center+valueAxis->range().size()/2.0;
  9958. } else // scaleType() == stLogarithmic
  9959. {
  9960. newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  9961. newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  9962. }
  9963. }
  9964. valueAxis->setRange(newRange);
  9965. }
  9966. }
  9967. /*! \overload
  9968. Adds this plottable to the specified \a legend.
  9969. Creates a QCPPlottableLegendItem which is inserted into the legend. Returns true on success, i.e.
  9970. when the legend exists and a legend item associated with this plottable isn't already in the
  9971. legend.
  9972. If the plottable needs a more specialized representation in the legend, you can create a
  9973. corresponding subclass of \ref QCPPlottableLegendItem and add it to the legend manually instead
  9974. of calling this method.
  9975. \see removeFromLegend, QCPLegend::addItem
  9976. */
  9977. bool QCPAbstractPlottable::addToLegend(QCPLegend *legend)
  9978. {
  9979. if (!legend)
  9980. {
  9981. qDebug() << Q_FUNC_INFO << "passed legend is null";
  9982. return false;
  9983. }
  9984. if (legend->parentPlot() != mParentPlot)
  9985. {
  9986. qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
  9987. return false;
  9988. }
  9989. if (!legend->hasItemWithPlottable(this))
  9990. {
  9991. legend->addItem(new QCPPlottableLegendItem(legend, this));
  9992. return true;
  9993. } else
  9994. return false;
  9995. }
  9996. /*! \overload
  9997. Adds this plottable to the legend of the parent QCustomPlot (\ref QCustomPlot::legend).
  9998. \see removeFromLegend
  9999. */
  10000. bool QCPAbstractPlottable::addToLegend()
  10001. {
  10002. if (!mParentPlot || !mParentPlot->legend)
  10003. return false;
  10004. else
  10005. return addToLegend(mParentPlot->legend);
  10006. }
  10007. /*! \overload
  10008. Removes the plottable from the specifed \a legend. This means the \ref QCPPlottableLegendItem
  10009. that is associated with this plottable is removed.
  10010. Returns true on success, i.e. if the legend exists and a legend item associated with this
  10011. plottable was found and removed.
  10012. \see addToLegend, QCPLegend::removeItem
  10013. */
  10014. bool QCPAbstractPlottable::removeFromLegend(QCPLegend *legend) const
  10015. {
  10016. if (!legend)
  10017. {
  10018. qDebug() << Q_FUNC_INFO << "passed legend is null";
  10019. return false;
  10020. }
  10021. if (QCPPlottableLegendItem *lip = legend->itemWithPlottable(this))
  10022. return legend->removeItem(lip);
  10023. else
  10024. return false;
  10025. }
  10026. /*! \overload
  10027. Removes the plottable from the legend of the parent QCustomPlot.
  10028. \see addToLegend
  10029. */
  10030. bool QCPAbstractPlottable::removeFromLegend() const
  10031. {
  10032. if (!mParentPlot || !mParentPlot->legend)
  10033. return false;
  10034. else
  10035. return removeFromLegend(mParentPlot->legend);
  10036. }
  10037. /* inherits documentation from base class */
  10038. QRect QCPAbstractPlottable::clipRect() const
  10039. {
  10040. if (mKeyAxis && mValueAxis)
  10041. return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
  10042. else
  10043. return {};
  10044. }
  10045. /* inherits documentation from base class */
  10046. QCP::Interaction QCPAbstractPlottable::selectionCategory() const
  10047. {
  10048. return QCP::iSelectPlottables;
  10049. }
  10050. /*! \internal
  10051. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  10052. before drawing plottable lines.
  10053. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  10054. This function takes into account the local setting of the antialiasing flag as well as the
  10055. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  10056. QCustomPlot::setNotAntialiasedElements.
  10057. \seebaseclassmethod
  10058. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint
  10059. */
  10060. void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const
  10061. {
  10062. applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
  10063. }
  10064. /*! \internal
  10065. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  10066. before drawing plottable fills.
  10067. This function takes into account the local setting of the antialiasing flag as well as the
  10068. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  10069. QCustomPlot::setNotAntialiasedElements.
  10070. \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint
  10071. */
  10072. void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const
  10073. {
  10074. applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
  10075. }
  10076. /*! \internal
  10077. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  10078. before drawing plottable scatter points.
  10079. This function takes into account the local setting of the antialiasing flag as well as the
  10080. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  10081. QCustomPlot::setNotAntialiasedElements.
  10082. \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint
  10083. */
  10084. void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const
  10085. {
  10086. applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
  10087. }
  10088. /* inherits documentation from base class */
  10089. void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  10090. {
  10091. Q_UNUSED(event)
  10092. if (mSelectable != QCP::stNone)
  10093. {
  10094. QCPDataSelection newSelection = details.value<QCPDataSelection>();
  10095. QCPDataSelection selectionBefore = mSelection;
  10096. if (additive)
  10097. {
  10098. if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
  10099. {
  10100. if (selected())
  10101. setSelection(QCPDataSelection());
  10102. else
  10103. setSelection(newSelection);
  10104. } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
  10105. {
  10106. if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
  10107. setSelection(mSelection-newSelection);
  10108. else
  10109. setSelection(mSelection+newSelection);
  10110. }
  10111. } else
  10112. setSelection(newSelection);
  10113. if (selectionStateChanged)
  10114. *selectionStateChanged = mSelection != selectionBefore;
  10115. }
  10116. }
  10117. /* inherits documentation from base class */
  10118. void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged)
  10119. {
  10120. if (mSelectable != QCP::stNone)
  10121. {
  10122. QCPDataSelection selectionBefore = mSelection;
  10123. setSelection(QCPDataSelection());
  10124. if (selectionStateChanged)
  10125. *selectionStateChanged = mSelection != selectionBefore;
  10126. }
  10127. }
  10128. /* end of 'src/plottable.cpp' */
  10129. /* including file 'src/item.cpp' */
  10130. /* modified 2021-03-29T02:30:44, size 49486 */
  10131. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10132. //////////////////// QCPItemAnchor
  10133. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10134. /*! \class QCPItemAnchor
  10135. \brief An anchor of an item to which positions can be attached to.
  10136. An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't
  10137. control anything on its item, but provides a way to tie other items via their positions to the
  10138. anchor.
  10139. For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight.
  10140. Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can
  10141. attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by
  10142. calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the
  10143. QCPItemRect. This way the start of the line will now always follow the respective anchor location
  10144. on the rect item.
  10145. Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an
  10146. anchor to other positions.
  10147. To learn how to provide anchors in your own item subclasses, see the subclassing section of the
  10148. QCPAbstractItem documentation.
  10149. */
  10150. /* start documentation of inline functions */
  10151. /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition()
  10152. Returns \c nullptr if this instance is merely a QCPItemAnchor, and a valid pointer of type
  10153. QCPItemPosition* if it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor).
  10154. This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids
  10155. dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with
  10156. gcc compiler).
  10157. */
  10158. /* end documentation of inline functions */
  10159. /*!
  10160. Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if
  10161. you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as
  10162. explained in the subclassing section of the QCPAbstractItem documentation.
  10163. */
  10164. QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId) :
  10165. mName(name),
  10166. mParentPlot(parentPlot),
  10167. mParentItem(parentItem),
  10168. mAnchorId(anchorId)
  10169. {
  10170. }
  10171. QCPItemAnchor::~QCPItemAnchor()
  10172. {
  10173. // unregister as parent at children:
  10174. foreach (QCPItemPosition *child, mChildrenX.values())
  10175. {
  10176. if (child->parentAnchorX() == this)
  10177. child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX
  10178. }
  10179. foreach (QCPItemPosition *child, mChildrenY.values())
  10180. {
  10181. if (child->parentAnchorY() == this)
  10182. child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY
  10183. }
  10184. }
  10185. /*!
  10186. Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface.
  10187. The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the
  10188. parent item, QCPItemAnchor is just an intermediary.
  10189. */
  10190. QPointF QCPItemAnchor::pixelPosition() const
  10191. {
  10192. if (mParentItem)
  10193. {
  10194. if (mAnchorId > -1)
  10195. {
  10196. return mParentItem->anchorPixelPosition(mAnchorId);
  10197. } else
  10198. {
  10199. qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId;
  10200. return {};
  10201. }
  10202. } else
  10203. {
  10204. qDebug() << Q_FUNC_INFO << "no parent item set";
  10205. return {};
  10206. }
  10207. }
  10208. /*! \internal
  10209. Adds \a pos to the childX list of this anchor, which keeps track of which children use this
  10210. anchor as parent anchor for the respective coordinate. This is necessary to notify the children
  10211. prior to destruction of the anchor.
  10212. Note that this function does not change the parent setting in \a pos.
  10213. */
  10214. void QCPItemAnchor::addChildX(QCPItemPosition *pos)
  10215. {
  10216. if (!mChildrenX.contains(pos))
  10217. mChildrenX.insert(pos);
  10218. else
  10219. qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
  10220. }
  10221. /*! \internal
  10222. Removes \a pos from the childX list of this anchor.
  10223. Note that this function does not change the parent setting in \a pos.
  10224. */
  10225. void QCPItemAnchor::removeChildX(QCPItemPosition *pos)
  10226. {
  10227. if (!mChildrenX.remove(pos))
  10228. qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
  10229. }
  10230. /*! \internal
  10231. Adds \a pos to the childY list of this anchor, which keeps track of which children use this
  10232. anchor as parent anchor for the respective coordinate. This is necessary to notify the children
  10233. prior to destruction of the anchor.
  10234. Note that this function does not change the parent setting in \a pos.
  10235. */
  10236. void QCPItemAnchor::addChildY(QCPItemPosition *pos)
  10237. {
  10238. if (!mChildrenY.contains(pos))
  10239. mChildrenY.insert(pos);
  10240. else
  10241. qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
  10242. }
  10243. /*! \internal
  10244. Removes \a pos from the childY list of this anchor.
  10245. Note that this function does not change the parent setting in \a pos.
  10246. */
  10247. void QCPItemAnchor::removeChildY(QCPItemPosition *pos)
  10248. {
  10249. if (!mChildrenY.remove(pos))
  10250. qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
  10251. }
  10252. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10253. //////////////////// QCPItemPosition
  10254. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10255. /*! \class QCPItemPosition
  10256. \brief Manages the position of an item.
  10257. Every item has at least one public QCPItemPosition member pointer which provides ways to position the
  10258. item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two:
  10259. \a topLeft and \a bottomRight.
  10260. QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type
  10261. defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel
  10262. coordinates, as plot coordinates of certain axes (\ref QCPItemPosition::setAxes), as fractions of
  10263. the axis rect (\ref QCPItemPosition::setAxisRect), etc. For more advanced plots it is also
  10264. possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref
  10265. setTypeY). This way an item could be positioned for example at a fixed pixel distance from the
  10266. top in the Y direction, while following a plot coordinate in the X direction.
  10267. A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie
  10268. multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords)
  10269. are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0)
  10270. means directly ontop of the parent anchor. For example, You could attach the \a start position of
  10271. a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line
  10272. always be centered under the text label, no matter where the text is moved to. For more advanced
  10273. plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see
  10274. \ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X
  10275. direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B
  10276. in Y.
  10277. Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent
  10278. anchor for other positions.
  10279. To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPosition. This
  10280. works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref
  10281. setPixelPosition transforms the coordinates appropriately, to make the position appear at the specified
  10282. pixel values.
  10283. */
  10284. /* start documentation of inline functions */
  10285. /*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const
  10286. Returns the current position type.
  10287. If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the
  10288. type of the X coordinate. In that case rather use \a typeX() and \a typeY().
  10289. \see setType
  10290. */
  10291. /*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const
  10292. Returns the current parent anchor.
  10293. If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY),
  10294. this method returns the parent anchor of the Y coordinate. In that case rather use \a
  10295. parentAnchorX() and \a parentAnchorY().
  10296. \see setParentAnchor
  10297. */
  10298. /* end documentation of inline functions */
  10299. /*!
  10300. Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if
  10301. you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as
  10302. explained in the subclassing section of the QCPAbstractItem documentation.
  10303. */
  10304. QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name) :
  10305. QCPItemAnchor(parentPlot, parentItem, name),
  10306. mPositionTypeX(ptAbsolute),
  10307. mPositionTypeY(ptAbsolute),
  10308. mKey(0),
  10309. mValue(0),
  10310. mParentAnchorX(nullptr),
  10311. mParentAnchorY(nullptr)
  10312. {
  10313. }
  10314. QCPItemPosition::~QCPItemPosition()
  10315. {
  10316. // unregister as parent at children:
  10317. // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then
  10318. // the setParentAnchor(0) call the correct QCPItemPosition::pixelPosition function instead of QCPItemAnchor::pixelPosition
  10319. foreach (QCPItemPosition *child, mChildrenX.values())
  10320. {
  10321. if (child->parentAnchorX() == this)
  10322. child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX
  10323. }
  10324. foreach (QCPItemPosition *child, mChildrenY.values())
  10325. {
  10326. if (child->parentAnchorY() == this)
  10327. child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY
  10328. }
  10329. // unregister as child in parent:
  10330. if (mParentAnchorX)
  10331. mParentAnchorX->removeChildX(this);
  10332. if (mParentAnchorY)
  10333. mParentAnchorY->removeChildY(this);
  10334. }
  10335. /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
  10336. QCPAxisRect *QCPItemPosition::axisRect() const
  10337. {
  10338. return mAxisRect.data();
  10339. }
  10340. /*!
  10341. Sets the type of the position. The type defines how the coordinates passed to \ref setCoords
  10342. should be handled and how the QCPItemPosition should behave in the plot.
  10343. The possible values for \a type can be separated in two main categories:
  10344. \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords
  10345. and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes.
  10346. By default, the QCustomPlot's x- and yAxis are used.
  10347. \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This
  10348. corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref
  10349. ptAxisRectRatio. They differ only in the way the absolute position is described, see the
  10350. documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify
  10351. the axis rect with \ref setAxisRect. By default this is set to the main axis rect.
  10352. Note that the position type \ref ptPlotCoords is only available (and sensible) when the position
  10353. has no parent anchor (\ref setParentAnchor).
  10354. If the type is changed, the apparent pixel position on the plot is preserved. This means
  10355. the coordinates as retrieved with coords() and set with \ref setCoords may change in the process.
  10356. This method sets the type for both X and Y directions. It is also possible to set different types
  10357. for X and Y, see \ref setTypeX, \ref setTypeY.
  10358. */
  10359. void QCPItemPosition::setType(QCPItemPosition::PositionType type)
  10360. {
  10361. setTypeX(type);
  10362. setTypeY(type);
  10363. }
  10364. /*!
  10365. This method sets the position type of the X coordinate to \a type.
  10366. For a detailed description of what a position type is, see the documentation of \ref setType.
  10367. \see setType, setTypeY
  10368. */
  10369. void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type)
  10370. {
  10371. if (mPositionTypeX != type)
  10372. {
  10373. // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
  10374. // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
  10375. bool retainPixelPosition = true;
  10376. if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
  10377. retainPixelPosition = false;
  10378. if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
  10379. retainPixelPosition = false;
  10380. QPointF pixel;
  10381. if (retainPixelPosition)
  10382. pixel = pixelPosition();
  10383. mPositionTypeX = type;
  10384. if (retainPixelPosition)
  10385. setPixelPosition(pixel);
  10386. }
  10387. }
  10388. /*!
  10389. This method sets the position type of the Y coordinate to \a type.
  10390. For a detailed description of what a position type is, see the documentation of \ref setType.
  10391. \see setType, setTypeX
  10392. */
  10393. void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type)
  10394. {
  10395. if (mPositionTypeY != type)
  10396. {
  10397. // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
  10398. // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
  10399. bool retainPixelPosition = true;
  10400. if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis))
  10401. retainPixelPosition = false;
  10402. if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect))
  10403. retainPixelPosition = false;
  10404. QPointF pixel;
  10405. if (retainPixelPosition)
  10406. pixel = pixelPosition();
  10407. mPositionTypeY = type;
  10408. if (retainPixelPosition)
  10409. setPixelPosition(pixel);
  10410. }
  10411. }
  10412. /*!
  10413. Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now
  10414. follow any position changes of the anchor. The local coordinate system of positions with a parent
  10415. anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence
  10416. the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.)
  10417. if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved
  10418. during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position
  10419. will be exactly on top of the parent anchor.
  10420. To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to \c nullptr.
  10421. If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is
  10422. set to \ref ptAbsolute, to keep the position in a valid state.
  10423. This method sets the parent anchor for both X and Y directions. It is also possible to set
  10424. different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY.
  10425. */
  10426. bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  10427. {
  10428. bool successX = setParentAnchorX(parentAnchor, keepPixelPosition);
  10429. bool successY = setParentAnchorY(parentAnchor, keepPixelPosition);
  10430. return successX && successY;
  10431. }
  10432. /*!
  10433. This method sets the parent anchor of the X coordinate to \a parentAnchor.
  10434. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
  10435. \see setParentAnchor, setParentAnchorY
  10436. */
  10437. bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  10438. {
  10439. // make sure self is not assigned as parent:
  10440. if (parentAnchor == this)
  10441. {
  10442. qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
  10443. return false;
  10444. }
  10445. // make sure no recursive parent-child-relationships are created:
  10446. QCPItemAnchor *currentParent = parentAnchor;
  10447. while (currentParent)
  10448. {
  10449. if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
  10450. {
  10451. // is a QCPItemPosition, might have further parent, so keep iterating
  10452. if (currentParentPos == this)
  10453. {
  10454. qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
  10455. return false;
  10456. }
  10457. currentParent = currentParentPos->parentAnchorX();
  10458. } else
  10459. {
  10460. // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
  10461. // same, to prevent a position being child of an anchor which itself depends on the position,
  10462. // because they're both on the same item:
  10463. if (currentParent->mParentItem == mParentItem)
  10464. {
  10465. qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
  10466. return false;
  10467. }
  10468. break;
  10469. }
  10470. }
  10471. // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
  10472. if (!mParentAnchorX && mPositionTypeX == ptPlotCoords)
  10473. setTypeX(ptAbsolute);
  10474. // save pixel position:
  10475. QPointF pixelP;
  10476. if (keepPixelPosition)
  10477. pixelP = pixelPosition();
  10478. // unregister at current parent anchor:
  10479. if (mParentAnchorX)
  10480. mParentAnchorX->removeChildX(this);
  10481. // register at new parent anchor:
  10482. if (parentAnchor)
  10483. parentAnchor->addChildX(this);
  10484. mParentAnchorX = parentAnchor;
  10485. // restore pixel position under new parent:
  10486. if (keepPixelPosition)
  10487. setPixelPosition(pixelP);
  10488. else
  10489. setCoords(0, coords().y());
  10490. return true;
  10491. }
  10492. /*!
  10493. This method sets the parent anchor of the Y coordinate to \a parentAnchor.
  10494. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
  10495. \see setParentAnchor, setParentAnchorX
  10496. */
  10497. bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  10498. {
  10499. // make sure self is not assigned as parent:
  10500. if (parentAnchor == this)
  10501. {
  10502. qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
  10503. return false;
  10504. }
  10505. // make sure no recursive parent-child-relationships are created:
  10506. QCPItemAnchor *currentParent = parentAnchor;
  10507. while (currentParent)
  10508. {
  10509. if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
  10510. {
  10511. // is a QCPItemPosition, might have further parent, so keep iterating
  10512. if (currentParentPos == this)
  10513. {
  10514. qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
  10515. return false;
  10516. }
  10517. currentParent = currentParentPos->parentAnchorY();
  10518. } else
  10519. {
  10520. // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
  10521. // same, to prevent a position being child of an anchor which itself depends on the position,
  10522. // because they're both on the same item:
  10523. if (currentParent->mParentItem == mParentItem)
  10524. {
  10525. qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
  10526. return false;
  10527. }
  10528. break;
  10529. }
  10530. }
  10531. // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
  10532. if (!mParentAnchorY && mPositionTypeY == ptPlotCoords)
  10533. setTypeY(ptAbsolute);
  10534. // save pixel position:
  10535. QPointF pixelP;
  10536. if (keepPixelPosition)
  10537. pixelP = pixelPosition();
  10538. // unregister at current parent anchor:
  10539. if (mParentAnchorY)
  10540. mParentAnchorY->removeChildY(this);
  10541. // register at new parent anchor:
  10542. if (parentAnchor)
  10543. parentAnchor->addChildY(this);
  10544. mParentAnchorY = parentAnchor;
  10545. // restore pixel position under new parent:
  10546. if (keepPixelPosition)
  10547. setPixelPosition(pixelP);
  10548. else
  10549. setCoords(coords().x(), 0);
  10550. return true;
  10551. }
  10552. /*!
  10553. Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type
  10554. (\ref setType, \ref setTypeX, \ref setTypeY).
  10555. For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position
  10556. on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the
  10557. QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the
  10558. plot coordinate system defined by the axes set by \ref setAxes. By default those are the
  10559. QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available
  10560. coordinate types and their meaning.
  10561. If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a
  10562. value must also be provided in the different coordinate systems. Here, the X type refers to \a
  10563. key, and the Y type refers to \a value.
  10564. \see setPixelPosition
  10565. */
  10566. void QCPItemPosition::setCoords(double key, double value)
  10567. {
  10568. mKey = key;
  10569. mValue = value;
  10570. }
  10571. /*! \overload
  10572. Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the
  10573. meaning of \a value of the \ref setCoords(double key, double value) method.
  10574. */
  10575. void QCPItemPosition::setCoords(const QPointF &pos)
  10576. {
  10577. setCoords(pos.x(), pos.y());
  10578. }
  10579. /*!
  10580. Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It
  10581. includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor).
  10582. \see setPixelPosition
  10583. */
  10584. QPointF QCPItemPosition::pixelPosition() const
  10585. {
  10586. QPointF result;
  10587. // determine X:
  10588. switch (mPositionTypeX)
  10589. {
  10590. case ptAbsolute:
  10591. {
  10592. result.rx() = mKey;
  10593. if (mParentAnchorX)
  10594. result.rx() += mParentAnchorX->pixelPosition().x();
  10595. break;
  10596. }
  10597. case ptViewportRatio:
  10598. {
  10599. result.rx() = mKey*mParentPlot->viewport().width();
  10600. if (mParentAnchorX)
  10601. result.rx() += mParentAnchorX->pixelPosition().x();
  10602. else
  10603. result.rx() += mParentPlot->viewport().left();
  10604. break;
  10605. }
  10606. case ptAxisRectRatio:
  10607. {
  10608. if (mAxisRect)
  10609. {
  10610. result.rx() = mKey*mAxisRect.data()->width();
  10611. if (mParentAnchorX)
  10612. result.rx() += mParentAnchorX->pixelPosition().x();
  10613. else
  10614. result.rx() += mAxisRect.data()->left();
  10615. } else
  10616. qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
  10617. break;
  10618. }
  10619. case ptPlotCoords:
  10620. {
  10621. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
  10622. result.rx() = mKeyAxis.data()->coordToPixel(mKey);
  10623. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
  10624. result.rx() = mValueAxis.data()->coordToPixel(mValue);
  10625. else
  10626. qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
  10627. break;
  10628. }
  10629. }
  10630. // determine Y:
  10631. switch (mPositionTypeY)
  10632. {
  10633. case ptAbsolute:
  10634. {
  10635. result.ry() = mValue;
  10636. if (mParentAnchorY)
  10637. result.ry() += mParentAnchorY->pixelPosition().y();
  10638. break;
  10639. }
  10640. case ptViewportRatio:
  10641. {
  10642. result.ry() = mValue*mParentPlot->viewport().height();
  10643. if (mParentAnchorY)
  10644. result.ry() += mParentAnchorY->pixelPosition().y();
  10645. else
  10646. result.ry() += mParentPlot->viewport().top();
  10647. break;
  10648. }
  10649. case ptAxisRectRatio:
  10650. {
  10651. if (mAxisRect)
  10652. {
  10653. result.ry() = mValue*mAxisRect.data()->height();
  10654. if (mParentAnchorY)
  10655. result.ry() += mParentAnchorY->pixelPosition().y();
  10656. else
  10657. result.ry() += mAxisRect.data()->top();
  10658. } else
  10659. qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
  10660. break;
  10661. }
  10662. case ptPlotCoords:
  10663. {
  10664. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
  10665. result.ry() = mKeyAxis.data()->coordToPixel(mKey);
  10666. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
  10667. result.ry() = mValueAxis.data()->coordToPixel(mValue);
  10668. else
  10669. qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
  10670. break;
  10671. }
  10672. }
  10673. return result;
  10674. }
  10675. /*!
  10676. When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the
  10677. coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and
  10678. yAxis of the QCustomPlot.
  10679. */
  10680. void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis)
  10681. {
  10682. mKeyAxis = keyAxis;
  10683. mValueAxis = valueAxis;
  10684. }
  10685. /*!
  10686. When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the
  10687. coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of
  10688. the QCustomPlot.
  10689. */
  10690. void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect)
  10691. {
  10692. mAxisRect = axisRect;
  10693. }
  10694. /*!
  10695. Sets the apparent pixel position. This works no matter what type (\ref setType) this
  10696. QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed
  10697. appropriately, to make the position finally appear at the specified pixel values.
  10698. Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is
  10699. identical to that of \ref setCoords.
  10700. \see pixelPosition, setCoords
  10701. */
  10702. void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition)
  10703. {
  10704. double x = pixelPosition.x();
  10705. double y = pixelPosition.y();
  10706. switch (mPositionTypeX)
  10707. {
  10708. case ptAbsolute:
  10709. {
  10710. if (mParentAnchorX)
  10711. x -= mParentAnchorX->pixelPosition().x();
  10712. break;
  10713. }
  10714. case ptViewportRatio:
  10715. {
  10716. if (mParentAnchorX)
  10717. x -= mParentAnchorX->pixelPosition().x();
  10718. else
  10719. x -= mParentPlot->viewport().left();
  10720. x /= double(mParentPlot->viewport().width());
  10721. break;
  10722. }
  10723. case ptAxisRectRatio:
  10724. {
  10725. if (mAxisRect)
  10726. {
  10727. if (mParentAnchorX)
  10728. x -= mParentAnchorX->pixelPosition().x();
  10729. else
  10730. x -= mAxisRect.data()->left();
  10731. x /= double(mAxisRect.data()->width());
  10732. } else
  10733. qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
  10734. break;
  10735. }
  10736. case ptPlotCoords:
  10737. {
  10738. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
  10739. x = mKeyAxis.data()->pixelToCoord(x);
  10740. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
  10741. y = mValueAxis.data()->pixelToCoord(x);
  10742. else
  10743. qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
  10744. break;
  10745. }
  10746. }
  10747. switch (mPositionTypeY)
  10748. {
  10749. case ptAbsolute:
  10750. {
  10751. if (mParentAnchorY)
  10752. y -= mParentAnchorY->pixelPosition().y();
  10753. break;
  10754. }
  10755. case ptViewportRatio:
  10756. {
  10757. if (mParentAnchorY)
  10758. y -= mParentAnchorY->pixelPosition().y();
  10759. else
  10760. y -= mParentPlot->viewport().top();
  10761. y /= double(mParentPlot->viewport().height());
  10762. break;
  10763. }
  10764. case ptAxisRectRatio:
  10765. {
  10766. if (mAxisRect)
  10767. {
  10768. if (mParentAnchorY)
  10769. y -= mParentAnchorY->pixelPosition().y();
  10770. else
  10771. y -= mAxisRect.data()->top();
  10772. y /= double(mAxisRect.data()->height());
  10773. } else
  10774. qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
  10775. break;
  10776. }
  10777. case ptPlotCoords:
  10778. {
  10779. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
  10780. x = mKeyAxis.data()->pixelToCoord(y);
  10781. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
  10782. y = mValueAxis.data()->pixelToCoord(y);
  10783. else
  10784. qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
  10785. break;
  10786. }
  10787. }
  10788. setCoords(x, y);
  10789. }
  10790. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10791. //////////////////// QCPAbstractItem
  10792. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10793. /*! \class QCPAbstractItem
  10794. \brief The abstract base class for all items in a plot.
  10795. In QCustomPlot, items are supplemental graphical elements that are neither plottables
  10796. (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus
  10797. plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each
  10798. specific item has at least one QCPItemPosition member which controls the positioning. Some items
  10799. are defined by more than one coordinate and thus have two or more QCPItemPosition members (For
  10800. example, QCPItemRect has \a topLeft and \a bottomRight).
  10801. This abstract base class defines a very basic interface like visibility and clipping. Since this
  10802. class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass
  10803. yourself to create new items.
  10804. The built-in items are:
  10805. <table>
  10806. <tr><td>QCPItemLine</td><td>A line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).</td></tr>
  10807. <tr><td>QCPItemStraightLine</td><td>A straight line defined by a start and a direction point. Unlike QCPItemLine, the straight line is infinitely long and has no endings.</td></tr>
  10808. <tr><td>QCPItemCurve</td><td>A curve defined by start, end and two intermediate control points. May have different ending styles on each side (e.g. arrows).</td></tr>
  10809. <tr><td>QCPItemRect</td><td>A rectangle</td></tr>
  10810. <tr><td>QCPItemEllipse</td><td>An ellipse</td></tr>
  10811. <tr><td>QCPItemPixmap</td><td>An arbitrary pixmap</td></tr>
  10812. <tr><td>QCPItemText</td><td>A text label</td></tr>
  10813. <tr><td>QCPItemBracket</td><td>A bracket which may be used to reference/highlight certain parts in the plot.</td></tr>
  10814. <tr><td>QCPItemTracer</td><td>An item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.</td></tr>
  10815. </table>
  10816. \section items-clipping Clipping
  10817. Items are by default clipped to the main axis rect (they are only visible inside the axis rect).
  10818. To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect
  10819. "setClipToAxisRect(false)".
  10820. On the other hand if you want the item to be clipped to a different axis rect, specify it via
  10821. \ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour, and
  10822. in principle is independent of the coordinate axes the item might be tied to via its position
  10823. members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping
  10824. also contains the axes used for the item positions.
  10825. \section items-using Using items
  10826. First you instantiate the item you want to use and add it to the plot:
  10827. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1
  10828. by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just
  10829. set the plot coordinates where the line should start/end:
  10830. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-2
  10831. If we don't want the line to be positioned in plot coordinates but a different coordinate system,
  10832. e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this:
  10833. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-3
  10834. Then we can set the coordinates, this time in pixels:
  10835. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4
  10836. and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect:
  10837. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5
  10838. For more advanced plots, it is even possible to set different types and parent anchors per X/Y
  10839. coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref
  10840. QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition.
  10841. \section items-subclassing Creating own items
  10842. To create an own item, you implement a subclass of QCPAbstractItem. These are the pure
  10843. virtual functions, you must implement:
  10844. \li \ref selectTest
  10845. \li \ref draw
  10846. See the documentation of those functions for what they need to do.
  10847. \subsection items-positioning Allowing the item to be positioned
  10848. As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall
  10849. have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add
  10850. a public member of type QCPItemPosition like so:
  10851. \code QCPItemPosition * const myPosition;\endcode
  10852. the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition
  10853. instance it points to, can be modified, of course).
  10854. The initialization of this pointer is made easy with the \ref createPosition function. Just assign
  10855. the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition
  10856. takes a string which is the name of the position, typically this is identical to the variable name.
  10857. For example, the constructor of QCPItemExample could look like this:
  10858. \code
  10859. QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) :
  10860. QCPAbstractItem(parentPlot),
  10861. myPosition(createPosition("myPosition"))
  10862. {
  10863. // other constructor code
  10864. }
  10865. \endcode
  10866. \subsection items-drawing The draw function
  10867. To give your item a visual representation, reimplement the \ref draw function and use the passed
  10868. QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the
  10869. position member(s) via \ref QCPItemPosition::pixelPosition.
  10870. To optimize performance you should calculate a bounding rect first (don't forget to take the pen
  10871. width into account), check whether it intersects the \ref clipRect, and only draw the item at all
  10872. if this is the case.
  10873. \subsection items-selection The selectTest function
  10874. Your implementation of the \ref selectTest function may use the helpers \ref
  10875. QCPVector2D::distanceSquaredToLine and \ref rectDistance. With these, the implementation of the
  10876. selection test becomes significantly simpler for most items. See the documentation of \ref
  10877. selectTest for what the function parameters mean and what the function should return.
  10878. \subsection anchors Providing anchors
  10879. Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public
  10880. member, e.g.
  10881. \code QCPItemAnchor * const bottom;\endcode
  10882. and create it in the constructor with the \ref createAnchor function, assigning it a name and an
  10883. anchor id (an integer enumerating all anchors on the item, you may create an own enum for this).
  10884. Since anchors can be placed anywhere, relative to the item's position(s), your item needs to
  10885. provide the position of every anchor with the reimplementation of the \ref anchorPixelPosition(int
  10886. anchorId) function.
  10887. In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel
  10888. position when anything attached to the anchor needs to know the coordinates.
  10889. */
  10890. /* start of documentation of inline functions */
  10891. /*! \fn QList<QCPItemPosition*> QCPAbstractItem::positions() const
  10892. Returns all positions of the item in a list.
  10893. \see anchors, position
  10894. */
  10895. /*! \fn QList<QCPItemAnchor*> QCPAbstractItem::anchors() const
  10896. Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always
  10897. also an anchor, the list will also contain the positions of this item.
  10898. \see positions, anchor
  10899. */
  10900. /* end of documentation of inline functions */
  10901. /* start documentation of pure virtual functions */
  10902. /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0
  10903. \internal
  10904. Draws this item with the provided \a painter.
  10905. The cliprect of the provided painter is set to the rect returned by \ref clipRect before this
  10906. function is called. The clipRect depends on the clipping settings defined by \ref
  10907. setClipToAxisRect and \ref setClipAxisRect.
  10908. */
  10909. /* end documentation of pure virtual functions */
  10910. /* start documentation of signals */
  10911. /*! \fn void QCPAbstractItem::selectionChanged(bool selected)
  10912. This signal is emitted when the selection state of this item has changed, either by user interaction
  10913. or by a direct call to \ref setSelected.
  10914. */
  10915. /* end documentation of signals */
  10916. /*!
  10917. Base class constructor which initializes base class members.
  10918. */
  10919. QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) :
  10920. QCPLayerable(parentPlot),
  10921. mClipToAxisRect(false),
  10922. mSelectable(true),
  10923. mSelected(false)
  10924. {
  10925. parentPlot->registerItem(this);
  10926. QList<QCPAxisRect*> rects = parentPlot->axisRects();
  10927. if (!rects.isEmpty())
  10928. {
  10929. setClipToAxisRect(true);
  10930. setClipAxisRect(rects.first());
  10931. }
  10932. }
  10933. QCPAbstractItem::~QCPAbstractItem()
  10934. {
  10935. // don't delete mPositions because every position is also an anchor and thus in mAnchors
  10936. qDeleteAll(mAnchors);
  10937. }
  10938. /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
  10939. QCPAxisRect *QCPAbstractItem::clipAxisRect() const
  10940. {
  10941. return mClipAxisRect.data();
  10942. }
  10943. /*!
  10944. Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the
  10945. entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect.
  10946. \see setClipAxisRect
  10947. */
  10948. void QCPAbstractItem::setClipToAxisRect(bool clip)
  10949. {
  10950. mClipToAxisRect = clip;
  10951. if (mClipToAxisRect)
  10952. setParentLayerable(mClipAxisRect.data());
  10953. }
  10954. /*!
  10955. Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref
  10956. setClipToAxisRect is set to true.
  10957. \see setClipToAxisRect
  10958. */
  10959. void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect)
  10960. {
  10961. mClipAxisRect = rect;
  10962. if (mClipToAxisRect)
  10963. setParentLayerable(mClipAxisRect.data());
  10964. }
  10965. /*!
  10966. Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface.
  10967. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.)
  10968. However, even when \a selectable was set to false, it is possible to set the selection manually,
  10969. by calling \ref setSelected.
  10970. \see QCustomPlot::setInteractions, setSelected
  10971. */
  10972. void QCPAbstractItem::setSelectable(bool selectable)
  10973. {
  10974. if (mSelectable != selectable)
  10975. {
  10976. mSelectable = selectable;
  10977. Q_EMIT selectableChanged(mSelectable);
  10978. }
  10979. }
  10980. /*!
  10981. Sets whether this item is selected or not. When selected, it might use a different visual
  10982. appearance (e.g. pen and brush), this depends on the specific item though.
  10983. The entire selection mechanism for items is handled automatically when \ref
  10984. QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this
  10985. function when you wish to change the selection state manually.
  10986. This function can change the selection state even when \ref setSelectable was set to false.
  10987. Q_EMITs the \ref selectionChanged signal when \a selected is different from the previous selection state.
  10988. \see setSelectable, selectTest
  10989. */
  10990. void QCPAbstractItem::setSelected(bool selected)
  10991. {
  10992. if (mSelected != selected)
  10993. {
  10994. mSelected = selected;
  10995. Q_EMIT selectionChanged(mSelected);
  10996. }
  10997. }
  10998. /*!
  10999. Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by
  11000. that name, returns \c nullptr.
  11001. This function provides an alternative way to access item positions. Normally, you access
  11002. positions direcly by their member pointers (which typically have the same variable name as \a
  11003. name).
  11004. \see positions, anchor
  11005. */
  11006. QCPItemPosition *QCPAbstractItem::position(const QString &name) const
  11007. {
  11008. foreach (QCPItemPosition *position, mPositions)
  11009. {
  11010. if (position->name() == name)
  11011. return position;
  11012. }
  11013. qDebug() << Q_FUNC_INFO << "position with name not found:" << name;
  11014. return nullptr;
  11015. }
  11016. /*!
  11017. Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by
  11018. that name, returns \c nullptr.
  11019. This function provides an alternative way to access item anchors. Normally, you access
  11020. anchors direcly by their member pointers (which typically have the same variable name as \a
  11021. name).
  11022. \see anchors, position
  11023. */
  11024. QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const
  11025. {
  11026. foreach (QCPItemAnchor *anchor, mAnchors)
  11027. {
  11028. if (anchor->name() == name)
  11029. return anchor;
  11030. }
  11031. qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name;
  11032. return nullptr;
  11033. }
  11034. /*!
  11035. Returns whether this item has an anchor with the specified \a name.
  11036. Note that you can check for positions with this function, too. This is because every position is
  11037. also an anchor (QCPItemPosition inherits from QCPItemAnchor).
  11038. \see anchor, position
  11039. */
  11040. bool QCPAbstractItem::hasAnchor(const QString &name) const
  11041. {
  11042. foreach (QCPItemAnchor *anchor, mAnchors)
  11043. {
  11044. if (anchor->name() == name)
  11045. return true;
  11046. }
  11047. return false;
  11048. }
  11049. /*! \internal
  11050. Returns the rect the visual representation of this item is clipped to. This depends on the
  11051. current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect.
  11052. If the item is not clipped to an axis rect, QCustomPlot's viewport rect is returned.
  11053. \see draw
  11054. */
  11055. QRect QCPAbstractItem::clipRect() const
  11056. {
  11057. if (mClipToAxisRect && mClipAxisRect)
  11058. return mClipAxisRect.data()->rect();
  11059. else
  11060. return mParentPlot->viewport();
  11061. }
  11062. /*! \internal
  11063. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  11064. before drawing item lines.
  11065. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  11066. This function takes into account the local setting of the antialiasing flag as well as the
  11067. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  11068. QCustomPlot::setNotAntialiasedElements.
  11069. \see setAntialiased
  11070. */
  11071. void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
  11072. {
  11073. applyAntialiasingHint(painter, mAntialiased, QCP::aeItems);
  11074. }
  11075. /*! \internal
  11076. A convenience function which returns the selectTest value for a specified \a rect and a specified
  11077. click position \a pos. \a filledRect defines whether a click inside the rect should also be
  11078. considered a hit or whether only the rect border is sensitive to hits.
  11079. This function may be used to help with the implementation of the \ref selectTest function for
  11080. specific items.
  11081. For example, if your item consists of four rects, call this function four times, once for each
  11082. rect, in your \ref selectTest reimplementation. Finally, return the minimum (non -1) of all four
  11083. returned values.
  11084. */
  11085. double QCPAbstractItem::rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const
  11086. {
  11087. double result = -1;
  11088. // distance to border:
  11089. const QList<QLineF> lines = QList<QLineF>() << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight())
  11090. << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight());
  11091. const QCPVector2D posVec(pos);
  11092. double minDistSqr = (std::numeric_limits<double>::max)();
  11093. foreach (const QLineF &line, lines)
  11094. {
  11095. double distSqr = posVec.distanceSquaredToLine(line.p1(), line.p2());
  11096. if (distSqr < minDistSqr)
  11097. minDistSqr = distSqr;
  11098. }
  11099. result = qSqrt(minDistSqr);
  11100. // filled rect, allow click inside to count as hit:
  11101. if (filledRect && result > mParentPlot->selectionTolerance()*0.99)
  11102. {
  11103. if (rect.contains(pos))
  11104. result = mParentPlot->selectionTolerance()*0.99;
  11105. }
  11106. return result;
  11107. }
  11108. /*! \internal
  11109. Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in
  11110. item subclasses if they want to provide anchors (QCPItemAnchor).
  11111. For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor
  11112. ids and returns the respective pixel points of the specified anchor.
  11113. \see createAnchor
  11114. */
  11115. QPointF QCPAbstractItem::anchorPixelPosition(int anchorId) const
  11116. {
  11117. qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId;
  11118. return {};
  11119. }
  11120. /*! \internal
  11121. Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified
  11122. \a name must be a unique string that is usually identical to the variable name of the position
  11123. member (This is needed to provide the name-based \ref position access to positions).
  11124. Don't delete positions created by this function manually, as the item will take care of it.
  11125. Use this function in the constructor (initialization list) of the specific item subclass to
  11126. create each position member. Don't create QCPItemPositions with \b new yourself, because they
  11127. won't be registered with the item properly.
  11128. \see createAnchor
  11129. */
  11130. QCPItemPosition *QCPAbstractItem::createPosition(const QString &name)
  11131. {
  11132. if (hasAnchor(name))
  11133. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  11134. QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name);
  11135. mPositions.append(newPosition);
  11136. mAnchors.append(newPosition); // every position is also an anchor
  11137. newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis);
  11138. newPosition->setType(QCPItemPosition::ptPlotCoords);
  11139. if (mParentPlot->axisRect())
  11140. newPosition->setAxisRect(mParentPlot->axisRect());
  11141. newPosition->setCoords(0, 0);
  11142. return newPosition;
  11143. }
  11144. /*! \internal
  11145. Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified
  11146. \a name must be a unique string that is usually identical to the variable name of the anchor
  11147. member (This is needed to provide the name based \ref anchor access to anchors).
  11148. The \a anchorId must be a number identifying the created anchor. It is recommended to create an
  11149. enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor
  11150. to identify itself when it calls QCPAbstractItem::anchorPixelPosition. That function then returns
  11151. the correct pixel coordinates for the passed anchor id.
  11152. Don't delete anchors created by this function manually, as the item will take care of it.
  11153. Use this function in the constructor (initialization list) of the specific item subclass to
  11154. create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they
  11155. won't be registered with the item properly.
  11156. \see createPosition
  11157. */
  11158. QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId)
  11159. {
  11160. if (hasAnchor(name))
  11161. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  11162. QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId);
  11163. mAnchors.append(newAnchor);
  11164. return newAnchor;
  11165. }
  11166. /* inherits documentation from base class */
  11167. void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  11168. {
  11169. Q_UNUSED(event)
  11170. Q_UNUSED(details)
  11171. if (mSelectable)
  11172. {
  11173. bool selBefore = mSelected;
  11174. setSelected(additive ? !mSelected : true);
  11175. if (selectionStateChanged)
  11176. *selectionStateChanged = mSelected != selBefore;
  11177. }
  11178. }
  11179. /* inherits documentation from base class */
  11180. void QCPAbstractItem::deselectEvent(bool *selectionStateChanged)
  11181. {
  11182. if (mSelectable)
  11183. {
  11184. bool selBefore = mSelected;
  11185. setSelected(false);
  11186. if (selectionStateChanged)
  11187. *selectionStateChanged = mSelected != selBefore;
  11188. }
  11189. }
  11190. /* inherits documentation from base class */
  11191. QCP::Interaction QCPAbstractItem::selectionCategory() const
  11192. {
  11193. return QCP::iSelectItems;
  11194. }
  11195. /* end of 'src/item.cpp' */
  11196. /* including file 'src/core.cpp' */
  11197. /* modified 2021-03-29T02:30:44, size 127198 */
  11198. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11199. //////////////////// QCustomPlot
  11200. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11201. /*! \class QCustomPlot
  11202. \brief The central class of the library. This is the QWidget which displays the plot and
  11203. interacts with the user.
  11204. For tutorials on how to use QCustomPlot, see the website\n
  11205. http://www.qcustomplot.com/
  11206. */
  11207. /* start of documentation of inline functions */
  11208. /*! \fn QCPSelectionRect *QCustomPlot::selectionRect() const
  11209. Allows access to the currently used QCPSelectionRect instance (or subclass thereof), that is used
  11210. to handle and draw selection rect interactions (see \ref setSelectionRectMode).
  11211. \see setSelectionRect
  11212. */
  11213. /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const
  11214. Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just
  11215. one cell with the main QCPAxisRect inside.
  11216. */
  11217. /* end of documentation of inline functions */
  11218. /* start of documentation of signals */
  11219. /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event)
  11220. This signal is emitted when the QCustomPlot receives a mouse double click event.
  11221. */
  11222. /*! \fn void QCustomPlot::mousePress(QMouseEvent *event)
  11223. This signal is emitted when the QCustomPlot receives a mouse press event.
  11224. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  11225. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
  11226. QCPAxisRect::setRangeDragAxes.
  11227. */
  11228. /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event)
  11229. This signal is emitted when the QCustomPlot receives a mouse move event.
  11230. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  11231. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
  11232. QCPAxisRect::setRangeDragAxes.
  11233. \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here,
  11234. because the dragging starting point was saved the moment the mouse was pressed. Thus it only has
  11235. a meaning for the range drag axes that were set at that moment. If you want to change the drag
  11236. axes, consider doing this in the \ref mousePress signal instead.
  11237. */
  11238. /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event)
  11239. This signal is emitted when the QCustomPlot receives a mouse release event.
  11240. It is emitted before QCustomPlot handles any other mechanisms like object selection. So a
  11241. slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or
  11242. \ref QCPAbstractPlottable::setSelectable.
  11243. */
  11244. /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event)
  11245. This signal is emitted when the QCustomPlot receives a mouse wheel event.
  11246. It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot
  11247. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref
  11248. QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor.
  11249. */
  11250. /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
  11251. This signal is emitted when a plottable is clicked.
  11252. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  11253. the click. The parameter \a dataIndex indicates the data point that was closest to the click
  11254. position.
  11255. \see plottableDoubleClick
  11256. */
  11257. /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
  11258. This signal is emitted when a plottable is double clicked.
  11259. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  11260. the click. The parameter \a dataIndex indicates the data point that was closest to the click
  11261. position.
  11262. \see plottableClick
  11263. */
  11264. /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event)
  11265. This signal is emitted when an item is clicked.
  11266. \a event is the mouse event that caused the click and \a item is the item that received the
  11267. click.
  11268. \see itemDoubleClick
  11269. */
  11270. /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event)
  11271. This signal is emitted when an item is double clicked.
  11272. \a event is the mouse event that caused the click and \a item is the item that received the
  11273. click.
  11274. \see itemClick
  11275. */
  11276. /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  11277. This signal is emitted when an axis is clicked.
  11278. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  11279. \a part indicates the part of the axis that was clicked.
  11280. \see axisDoubleClick
  11281. */
  11282. /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  11283. This signal is emitted when an axis is double clicked.
  11284. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  11285. \a part indicates the part of the axis that was clicked.
  11286. \see axisClick
  11287. */
  11288. /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
  11289. This signal is emitted when a legend (item) is clicked.
  11290. \a event is the mouse event that caused the click, \a legend is the legend that received the
  11291. click and \a item is the legend item that received the click. If only the legend and no item is
  11292. clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space
  11293. between two items.
  11294. \see legendDoubleClick
  11295. */
  11296. /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
  11297. This signal is emitted when a legend (item) is double clicked.
  11298. \a event is the mouse event that caused the click, \a legend is the legend that received the
  11299. click and \a item is the legend item that received the click. If only the legend and no item is
  11300. clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space
  11301. between two items.
  11302. \see legendClick
  11303. */
  11304. /*! \fn void QCustomPlot::selectionChangedByUser()
  11305. This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by
  11306. clicking. It is not emitted when the selection state of an object has changed programmatically by
  11307. a direct call to <tt>setSelected()</tt>/<tt>setSelection()</tt> on an object or by calling \ref
  11308. deselectAll.
  11309. In addition to this signal, selectable objects also provide individual signals, for example \ref
  11310. QCPAxis::selectionChanged or \ref QCPAbstractPlottable::selectionChanged. Note that those signals
  11311. are emitted even if the selection state is changed programmatically.
  11312. See the documentation of \ref setInteractions for details about the selection mechanism.
  11313. \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends
  11314. */
  11315. /*! \fn void QCustomPlot::beforeReplot()
  11316. This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref
  11317. replot).
  11318. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  11319. replot synchronously, it won't cause an infinite recursion.
  11320. \see replot, afterReplot, afterLayout
  11321. */
  11322. /*! \fn void QCustomPlot::afterLayout()
  11323. This signal is emitted immediately after the layout step has been completed, which occurs right
  11324. before drawing the plot. This is typically during a call to \ref replot, and in such cases this
  11325. signal is emitted in between the signals \ref beforeReplot and \ref afterReplot. Unlike those
  11326. signals however, this signal is also emitted during off-screen painting, such as when calling
  11327. \ref toPixmap or \ref savePdf.
  11328. The layout step queries all layouts and layout elements in the plot for their proposed size and
  11329. arranges the objects accordingly as preparation for the subsequent drawing step. Through this
  11330. signal, you have the opportunity to update certain things in your plot that depend crucially on
  11331. the exact dimensions/positioning of layout elements such as axes and axis rects.
  11332. \warning However, changing any parameters of this QCustomPlot instance which would normally
  11333. affect the layouting (e.g. axis range order of magnitudes, tick label sizes, etc.) will not issue
  11334. a second run of the layout step. It will propagate directly to the draw step and may cause
  11335. graphical inconsistencies such as overlapping objects, if sizes or positions have changed.
  11336. \see updateLayout, beforeReplot, afterReplot
  11337. */
  11338. /*! \fn void QCustomPlot::afterReplot()
  11339. This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref
  11340. replot).
  11341. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  11342. replot synchronously, it won't cause an infinite recursion.
  11343. \see replot, beforeReplot, afterLayout
  11344. */
  11345. /* end of documentation of signals */
  11346. /* start of documentation of public members */
  11347. /*! \var QCPAxis *QCustomPlot::xAxis
  11348. A pointer to the primary x Axis (bottom) of the main axis rect of the plot.
  11349. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11350. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11351. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11352. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11353. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11354. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11355. axis rect), the corresponding pointers become \c nullptr.
  11356. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11357. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11358. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11359. is added after the main legend was removed before.
  11360. */
  11361. /*! \var QCPAxis *QCustomPlot::yAxis
  11362. A pointer to the primary y Axis (left) of the main axis rect of the plot.
  11363. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11364. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11365. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11366. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11367. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11368. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11369. axis rect), the corresponding pointers become \c nullptr.
  11370. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11371. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11372. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11373. is added after the main legend was removed before.
  11374. */
  11375. /*! \var QCPAxis *QCustomPlot::xAxis2
  11376. A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are
  11377. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  11378. QCPAxisRect::setupFullAxesBox).
  11379. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11380. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11381. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11382. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11383. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11384. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11385. axis rect), the corresponding pointers become \c nullptr.
  11386. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11387. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11388. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11389. is added after the main legend was removed before.
  11390. */
  11391. /*! \var QCPAxis *QCustomPlot::yAxis2
  11392. A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are
  11393. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  11394. QCPAxisRect::setupFullAxesBox).
  11395. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11396. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11397. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11398. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11399. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11400. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11401. axis rect), the corresponding pointers become \c nullptr.
  11402. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11403. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11404. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11405. is added after the main legend was removed before.
  11406. */
  11407. /*! \var QCPLegend *QCustomPlot::legend
  11408. A pointer to the default legend of the main axis rect. The legend is invisible by default. Use
  11409. QCPLegend::setVisible to change this.
  11410. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11411. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11412. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11413. layout system\endlink to add multiple legends to the plot, use the layout system interface to
  11414. access the new legend. For example, legends can be placed inside an axis rect's \ref
  11415. QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If
  11416. the default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11417. axis rect), the corresponding pointer becomes \c nullptr.
  11418. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11419. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11420. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11421. is added after the main legend was removed before.
  11422. */
  11423. /* end of documentation of public members */
  11424. /*!
  11425. Constructs a QCustomPlot and sets reasonable default values.
  11426. */
  11427. QCustomPlot::QCustomPlot(QWidget *parent) :
  11428. QWidget(parent),
  11429. xAxis(nullptr),
  11430. yAxis(nullptr),
  11431. xAxis2(nullptr),
  11432. yAxis2(nullptr),
  11433. legend(nullptr),
  11434. mBufferDevicePixelRatio(1.0), // will be adapted to primary screen below
  11435. mPlotLayout(nullptr),
  11436. mAutoAddPlottableToLegend(true),
  11437. mAntialiasedElements(QCP::aeNone),
  11438. mNotAntialiasedElements(QCP::aeNone),
  11439. mInteractions(QCP::iNone),
  11440. mSelectionTolerance(8),
  11441. mNoAntialiasingOnDrag(false),
  11442. mBackgroundBrush(Qt::white, Qt::SolidPattern),
  11443. mBackgroundScaled(true),
  11444. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  11445. mCurrentLayer(nullptr),
  11446. mPlottingHints(QCP::phCacheLabels|QCP::phImmediateRefresh),
  11447. mMultiSelectModifier(Qt::ControlModifier),
  11448. mSelectionRectMode(QCP::srmNone),
  11449. mSelectionRect(nullptr),
  11450. mOpenGl(false),
  11451. mMouseHasMoved(false),
  11452. mMouseEventLayerable(nullptr),
  11453. mMouseSignalLayerable(nullptr),
  11454. mReplotting(false),
  11455. mReplotQueued(false),
  11456. mReplotTime(0),
  11457. mReplotTimeAverage(0),
  11458. mOpenGlMultisamples(16),
  11459. mOpenGlAntialiasedElementsBackup(QCP::aeNone),
  11460. mOpenGlCacheLabelsBackup(true)
  11461. {
  11462. setAttribute(Qt::WA_NoMousePropagation);
  11463. setAttribute(Qt::WA_OpaquePaintEvent);
  11464. setFocusPolicy(Qt::ClickFocus);
  11465. setMouseTracking(true);
  11466. QLocale currentLocale = locale();
  11467. currentLocale.setNumberOptions(QLocale::OmitGroupSeparator);
  11468. setLocale(currentLocale);
  11469. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  11470. # ifdef QCP_DEVICEPIXELRATIO_FLOAT
  11471. setBufferDevicePixelRatio(QWidget::devicePixelRatioF());
  11472. # else
  11473. setBufferDevicePixelRatio(QWidget::devicePixelRatio());
  11474. # endif
  11475. #endif
  11476. mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
  11477. mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
  11478. // create initial layers:
  11479. mLayers.append(new QCPLayer(this, QLatin1String("background")));
  11480. mLayers.append(new QCPLayer(this, QLatin1String("grid")));
  11481. mLayers.append(new QCPLayer(this, QLatin1String("main")));
  11482. mLayers.append(new QCPLayer(this, QLatin1String("axes")));
  11483. mLayers.append(new QCPLayer(this, QLatin1String("legend")));
  11484. mLayers.append(new QCPLayer(this, QLatin1String("overlay")));
  11485. updateLayerIndices();
  11486. setCurrentLayer(QLatin1String("main"));
  11487. layer(QLatin1String("overlay"))->setMode(QCPLayer::lmBuffered);
  11488. // create initial layout, axis rect and legend:
  11489. mPlotLayout = new QCPLayoutGrid;
  11490. mPlotLayout->initializeParentPlot(this);
  11491. mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry
  11492. mPlotLayout->setLayer(QLatin1String("main"));
  11493. QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true);
  11494. mPlotLayout->addElement(0, 0, defaultAxisRect);
  11495. xAxis = defaultAxisRect->axis(QCPAxis::atBottom);
  11496. yAxis = defaultAxisRect->axis(QCPAxis::atLeft);
  11497. xAxis2 = defaultAxisRect->axis(QCPAxis::atTop);
  11498. yAxis2 = defaultAxisRect->axis(QCPAxis::atRight);
  11499. legend = new QCPLegend;
  11500. legend->setVisible(false);
  11501. defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop);
  11502. defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12));
  11503. defaultAxisRect->setLayer(QLatin1String("background"));
  11504. xAxis->setLayer(QLatin1String("axes"));
  11505. yAxis->setLayer(QLatin1String("axes"));
  11506. xAxis2->setLayer(QLatin1String("axes"));
  11507. yAxis2->setLayer(QLatin1String("axes"));
  11508. xAxis->grid()->setLayer(QLatin1String("grid"));
  11509. yAxis->grid()->setLayer(QLatin1String("grid"));
  11510. xAxis2->grid()->setLayer(QLatin1String("grid"));
  11511. yAxis2->grid()->setLayer(QLatin1String("grid"));
  11512. legend->setLayer(QLatin1String("legend"));
  11513. // create selection rect instance:
  11514. mSelectionRect = new QCPSelectionRect(this);
  11515. mSelectionRect->setLayer(QLatin1String("overlay"));
  11516. setViewport(rect()); // needs to be called after mPlotLayout has been created
  11517. replot(rpQueuedReplot);
  11518. }
  11519. QCustomPlot::~QCustomPlot()
  11520. {
  11521. clearPlottables();
  11522. clearItems();
  11523. if (mPlotLayout)
  11524. {
  11525. delete mPlotLayout;
  11526. mPlotLayout = nullptr;
  11527. }
  11528. mCurrentLayer = nullptr;
  11529. qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed
  11530. mLayers.clear();
  11531. }
  11532. /*!
  11533. Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement.
  11534. This overrides the antialiasing settings for whole element groups, normally controlled with the
  11535. \a setAntialiasing function on the individual elements. If an element is neither specified in
  11536. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  11537. each individual element instance is used.
  11538. For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be
  11539. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  11540. to.
  11541. if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is
  11542. removed from there.
  11543. \see setNotAntialiasedElements
  11544. */
  11545. void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements)
  11546. {
  11547. mAntialiasedElements = antialiasedElements;
  11548. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11549. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11550. mNotAntialiasedElements |= ~mAntialiasedElements;
  11551. }
  11552. /*!
  11553. Sets whether the specified \a antialiasedElement is forcibly drawn antialiased.
  11554. See \ref setAntialiasedElements for details.
  11555. \see setNotAntialiasedElement
  11556. */
  11557. void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled)
  11558. {
  11559. if (!enabled && mAntialiasedElements.testFlag(antialiasedElement))
  11560. mAntialiasedElements &= ~antialiasedElement;
  11561. else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement))
  11562. mAntialiasedElements |= antialiasedElement;
  11563. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11564. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11565. mNotAntialiasedElements |= ~mAntialiasedElements;
  11566. }
  11567. /*!
  11568. Sets which elements are forcibly drawn not antialiased as an \a or combination of
  11569. QCP::AntialiasedElement.
  11570. This overrides the antialiasing settings for whole element groups, normally controlled with the
  11571. \a setAntialiasing function on the individual elements. If an element is neither specified in
  11572. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  11573. each individual element instance is used.
  11574. For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be
  11575. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  11576. to.
  11577. if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is
  11578. removed from there.
  11579. \see setAntialiasedElements
  11580. */
  11581. void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements &notAntialiasedElements)
  11582. {
  11583. mNotAntialiasedElements = notAntialiasedElements;
  11584. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11585. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11586. mAntialiasedElements |= ~mNotAntialiasedElements;
  11587. }
  11588. /*!
  11589. Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased.
  11590. See \ref setNotAntialiasedElements for details.
  11591. \see setAntialiasedElement
  11592. */
  11593. void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled)
  11594. {
  11595. if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement))
  11596. mNotAntialiasedElements &= ~notAntialiasedElement;
  11597. else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement))
  11598. mNotAntialiasedElements |= notAntialiasedElement;
  11599. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11600. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11601. mAntialiasedElements |= ~mNotAntialiasedElements;
  11602. }
  11603. /*!
  11604. If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the
  11605. plottable to the legend (QCustomPlot::legend).
  11606. \see addGraph, QCPLegend::addItem
  11607. */
  11608. void QCustomPlot::setAutoAddPlottableToLegend(bool on)
  11609. {
  11610. mAutoAddPlottableToLegend = on;
  11611. }
  11612. /*!
  11613. Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction
  11614. enums. There are the following types of interactions:
  11615. <b>Axis range manipulation</b> is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the
  11616. respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel.
  11617. For details how to control which axes the user may drag/zoom and in what orientations, see \ref
  11618. QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes,
  11619. \ref QCPAxisRect::setRangeZoomAxes.
  11620. <b>Plottable data selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref
  11621. QCP::iSelectPlottables is set, the user may select plottables (graphs, curves, bars,...) and
  11622. their data by clicking on them or in their vicinity (\ref setSelectionTolerance). Whether the
  11623. user can actually select a plottable and its data can further be restricted with the \ref
  11624. QCPAbstractPlottable::setSelectable method on the specific plottable. For details, see the
  11625. special page about the \ref dataselection "data selection mechanism". To retrieve a list of all
  11626. currently selected plottables, call \ref selectedPlottables. If you're only interested in
  11627. QCPGraphs, you may use the convenience function \ref selectedGraphs.
  11628. <b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user
  11629. may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find
  11630. out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of
  11631. all currently selected items, call \ref selectedItems.
  11632. <b>Axis selection</b> is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user
  11633. may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick
  11634. labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for
  11635. each axis. To retrieve a list of all axes that currently contain selected parts, call \ref
  11636. selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts().
  11637. <b>Legend selection</b> is controlled with \ref QCP::iSelectLegend. If this is set, the user may
  11638. select the legend itself or individual items by clicking on them. What parts exactly are
  11639. selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the
  11640. legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To
  11641. find out which child items are selected, call \ref QCPLegend::selectedItems.
  11642. <b>All other selectable elements</b> The selection of all other selectable objects (e.g.
  11643. QCPTextElement, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the
  11644. user may select those objects by clicking on them. To find out which are currently selected, you
  11645. need to check their selected state explicitly.
  11646. If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is
  11647. Q_EMITted. Each selectable object additionally Q_EMITs an individual selectionChanged signal whenever
  11648. their selection state has changed, i.e. not only by user interaction.
  11649. To allow multiple objects to be selected by holding the selection modifier (\ref
  11650. setMultiSelectModifier), set the flag \ref QCP::iMultiSelect.
  11651. \note In addition to the selection mechanism presented here, QCustomPlot always emits
  11652. corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and
  11653. \ref plottableDoubleClick for example.
  11654. \see setInteraction, setSelectionTolerance
  11655. */
  11656. void QCustomPlot::setInteractions(const QCP::Interactions &interactions)
  11657. {
  11658. mInteractions = interactions;
  11659. }
  11660. /*!
  11661. Sets the single \a interaction of this QCustomPlot to \a enabled.
  11662. For details about the interaction system, see \ref setInteractions.
  11663. \see setInteractions
  11664. */
  11665. void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled)
  11666. {
  11667. if (!enabled && mInteractions.testFlag(interaction))
  11668. mInteractions &= ~interaction;
  11669. else if (enabled && !mInteractions.testFlag(interaction))
  11670. mInteractions |= interaction;
  11671. }
  11672. /*!
  11673. Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or
  11674. not.
  11675. If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a
  11676. potential selection when the minimum distance between the click position and the graph line is
  11677. smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks
  11678. directly inside the area and ignore this selection tolerance. In other words, it only has meaning
  11679. for parts of objects that are too thin to exactly hit with a click and thus need such a
  11680. tolerance.
  11681. \see setInteractions, QCPLayerable::selectTest
  11682. */
  11683. void QCustomPlot::setSelectionTolerance(int pixels)
  11684. {
  11685. mSelectionTolerance = pixels;
  11686. }
  11687. /*!
  11688. Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes
  11689. ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves
  11690. performance during dragging. Thus it creates a more responsive user experience. As soon as the
  11691. user stops dragging, the last replot is done with normal antialiasing, to restore high image
  11692. quality.
  11693. \see setAntialiasedElements, setNotAntialiasedElements
  11694. */
  11695. void QCustomPlot::setNoAntialiasingOnDrag(bool enabled)
  11696. {
  11697. mNoAntialiasingOnDrag = enabled;
  11698. }
  11699. /*!
  11700. Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint.
  11701. \see setPlottingHint
  11702. */
  11703. void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints)
  11704. {
  11705. mPlottingHints = hints;
  11706. }
  11707. /*!
  11708. Sets the specified plotting \a hint to \a enabled.
  11709. \see setPlottingHints
  11710. */
  11711. void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled)
  11712. {
  11713. QCP::PlottingHints newHints = mPlottingHints;
  11714. if (!enabled)
  11715. newHints &= ~hint;
  11716. else
  11717. newHints |= hint;
  11718. if (newHints != mPlottingHints)
  11719. setPlottingHints(newHints);
  11720. }
  11721. /*!
  11722. Sets the keyboard modifier that will be recognized as multi-select-modifier.
  11723. If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple
  11724. objects (or data points) by clicking on them one after the other while holding down \a modifier.
  11725. By default the multi-select-modifier is set to Qt::ControlModifier.
  11726. \see setInteractions
  11727. */
  11728. void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier)
  11729. {
  11730. mMultiSelectModifier = modifier;
  11731. }
  11732. /*!
  11733. Sets how QCustomPlot processes mouse click-and-drag interactions by the user.
  11734. If \a mode is \ref QCP::srmNone, the mouse drag is forwarded to the underlying objects. For
  11735. example, QCPAxisRect may process a mouse drag by dragging axis ranges, see \ref
  11736. QCPAxisRect::setRangeDrag. If \a mode is not \ref QCP::srmNone, the current selection rect (\ref
  11737. selectionRect) becomes activated and allows e.g. rect zooming and data point selection.
  11738. If you wish to provide your user both with axis range dragging and data selection/range zooming,
  11739. use this method to switch between the modes just before the interaction is processed, e.g. in
  11740. reaction to the \ref mousePress or \ref mouseMove signals. For example you could check whether
  11741. the user is holding a certain keyboard modifier, and then decide which \a mode shall be set.
  11742. If a selection rect interaction is currently active, and \a mode is set to \ref QCP::srmNone, the
  11743. interaction is canceled (\ref QCPSelectionRect::cancel). Switching between any of the other modes
  11744. will keep the selection rect active. Upon completion of the interaction, the behaviour is as
  11745. defined by the currently set \a mode, not the mode that was set when the interaction started.
  11746. \see setInteractions, setSelectionRect, QCPSelectionRect
  11747. */
  11748. void QCustomPlot::setSelectionRectMode(QCP::SelectionRectMode mode)
  11749. {
  11750. if (mSelectionRect)
  11751. {
  11752. if (mode == QCP::srmNone)
  11753. mSelectionRect->cancel(); // when switching to none, we immediately want to abort a potentially active selection rect
  11754. // disconnect old connections:
  11755. if (mSelectionRectMode == QCP::srmSelect)
  11756. disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11757. else if (mSelectionRectMode == QCP::srmZoom)
  11758. disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11759. // establish new ones:
  11760. if (mode == QCP::srmSelect)
  11761. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11762. else if (mode == QCP::srmZoom)
  11763. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11764. }
  11765. mSelectionRectMode = mode;
  11766. }
  11767. /*!
  11768. Sets the \ref QCPSelectionRect instance that QCustomPlot will use if \a mode is not \ref
  11769. QCP::srmNone and the user performs a click-and-drag interaction. QCustomPlot takes ownership of
  11770. the passed \a selectionRect. It can be accessed later via \ref selectionRect.
  11771. This method is useful if you wish to replace the default QCPSelectionRect instance with an
  11772. instance of a QCPSelectionRect subclass, to introduce custom behaviour of the selection rect.
  11773. \see setSelectionRectMode
  11774. */
  11775. void QCustomPlot::setSelectionRect(QCPSelectionRect *selectionRect)
  11776. {
  11777. delete mSelectionRect;
  11778. mSelectionRect = selectionRect;
  11779. if (mSelectionRect)
  11780. {
  11781. // establish connections with new selection rect:
  11782. if (mSelectionRectMode == QCP::srmSelect)
  11783. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11784. else if (mSelectionRectMode == QCP::srmZoom)
  11785. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11786. }
  11787. }
  11788. /*!
  11789. \warning This is still an experimental feature and its performance depends on the system that it
  11790. runs on. Having multiple QCustomPlot widgets in one application with enabled OpenGL rendering
  11791. might cause context conflicts on some systems.
  11792. This method allows to enable OpenGL plot rendering, for increased plotting performance of
  11793. graphically demanding plots (thick lines, translucent fills, etc.).
  11794. If \a enabled is set to true, QCustomPlot will try to initialize OpenGL and, if successful,
  11795. continue plotting with hardware acceleration. The parameter \a multisampling controls how many
  11796. samples will be used per pixel, it essentially controls the antialiasing quality. If \a
  11797. multisampling is set too high for the current graphics hardware, the maximum allowed value will
  11798. be used.
  11799. You can test whether switching to OpenGL rendering was successful by checking whether the
  11800. according getter \a QCustomPlot::openGl() returns true. If the OpenGL initialization fails,
  11801. rendering continues with the regular software rasterizer, and an according qDebug output is
  11802. generated.
  11803. If switching to OpenGL was successful, this method disables label caching (\ref setPlottingHint
  11804. "setPlottingHint(QCP::phCacheLabels, false)") and turns on QCustomPlot's antialiasing override
  11805. for all elements (\ref setAntialiasedElements "setAntialiasedElements(QCP::aeAll)"), leading to a
  11806. higher quality output. The antialiasing override allows for pixel-grid aligned drawing in the
  11807. OpenGL paint device. As stated before, in OpenGL rendering the actual antialiasing of the plot is
  11808. controlled with \a multisampling. If \a enabled is set to false, the antialiasing/label caching
  11809. settings are restored to what they were before OpenGL was enabled, if they weren't altered in the
  11810. meantime.
  11811. \note OpenGL support is only enabled if QCustomPlot is compiled with the macro \c QCUSTOMPLOT_USE_OPENGL
  11812. defined. This define must be set before including the QCustomPlot header both during compilation
  11813. of the QCustomPlot library as well as when compiling your application. It is best to just include
  11814. the line <tt>DEFINES += QCUSTOMPLOT_USE_OPENGL</tt> in the respective qmake project files.
  11815. \note If you are using a Qt version before 5.0, you must also add the module "opengl" to your \c
  11816. QT variable in the qmake project files. For Qt versions 5.0 and higher, QCustomPlot switches to a
  11817. newer OpenGL interface which is already in the "gui" module.
  11818. */
  11819. void QCustomPlot::setOpenGl(bool enabled, int multisampling)
  11820. {
  11821. mOpenGlMultisamples = qMax(0, multisampling);
  11822. #ifdef QCUSTOMPLOT_USE_OPENGL
  11823. mOpenGl = enabled;
  11824. if (mOpenGl)
  11825. {
  11826. if (setupOpenGl())
  11827. {
  11828. // backup antialiasing override and labelcaching setting so we can restore upon disabling OpenGL
  11829. mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
  11830. mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
  11831. // set antialiasing override to antialias all (aligns gl pixel grid properly), and disable label caching (would use software rasterizer for pixmap caches):
  11832. setAntialiasedElements(QCP::aeAll);
  11833. setPlottingHint(QCP::phCacheLabels, false);
  11834. } else
  11835. {
  11836. qDebug() << Q_FUNC_INFO << "Failed to enable OpenGL, continuing plotting without hardware acceleration.";
  11837. mOpenGl = false;
  11838. }
  11839. } else
  11840. {
  11841. // restore antialiasing override and labelcaching to what it was before enabling OpenGL, if nobody changed it in the meantime:
  11842. if (mAntialiasedElements == QCP::aeAll)
  11843. setAntialiasedElements(mOpenGlAntialiasedElementsBackup);
  11844. if (!mPlottingHints.testFlag(QCP::phCacheLabels))
  11845. setPlottingHint(QCP::phCacheLabels, mOpenGlCacheLabelsBackup);
  11846. freeOpenGl();
  11847. }
  11848. // recreate all paint buffers:
  11849. mPaintBuffers.clear();
  11850. setupPaintBuffers();
  11851. #else
  11852. Q_UNUSED(enabled)
  11853. qDebug() << Q_FUNC_INFO << "QCustomPlot can't use OpenGL because QCUSTOMPLOT_USE_OPENGL was not defined during compilation (add 'DEFINES += QCUSTOMPLOT_USE_OPENGL' to your qmake .pro file)";
  11854. #endif
  11855. }
  11856. /*!
  11857. Sets the viewport of this QCustomPlot. Usually users of QCustomPlot don't need to change the
  11858. viewport manually.
  11859. The viewport is the area in which the plot is drawn. All mechanisms, e.g. margin calculation take
  11860. the viewport to be the outer border of the plot. The viewport normally is the rect() of the
  11861. QCustomPlot widget, i.e. a rect with top left (0, 0) and size of the QCustomPlot widget.
  11862. Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
  11863. an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
  11864. and contains also the axes themselves, their tick numbers, their labels, or even additional axis
  11865. rects, color scales and other layout elements.
  11866. This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref
  11867. savePdf, etc. by temporarily changing the viewport size.
  11868. */
  11869. void QCustomPlot::setViewport(const QRect &rect)
  11870. {
  11871. mViewport = rect;
  11872. if (mPlotLayout)
  11873. mPlotLayout->setOuterRect(mViewport);
  11874. }
  11875. /*!
  11876. Sets the device pixel ratio used by the paint buffers of this QCustomPlot instance.
  11877. Normally, this doesn't need to be set manually, because it is initialized with the regular \a
  11878. QWidget::devicePixelRatio which is configured by Qt to fit the display device (e.g. 1 for normal
  11879. displays, 2 for High-DPI displays).
  11880. Device pixel ratios are supported by Qt only for Qt versions since 5.4. If this method is called
  11881. when QCustomPlot is being used with older Qt versions, outputs an according qDebug message and
  11882. leaves the internal buffer device pixel ratio at 1.0.
  11883. */
  11884. void QCustomPlot::setBufferDevicePixelRatio(double ratio)
  11885. {
  11886. if (!qFuzzyCompare(ratio, mBufferDevicePixelRatio))
  11887. {
  11888. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  11889. mBufferDevicePixelRatio = ratio;
  11890. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  11891. buffer->setDevicePixelRatio(mBufferDevicePixelRatio);
  11892. // Note: axis label cache has devicePixelRatio as part of cache hash, so no need to manually clear cache here
  11893. #else
  11894. qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
  11895. mBufferDevicePixelRatio = 1.0;
  11896. #endif
  11897. }
  11898. }
  11899. /*!
  11900. Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn
  11901. below all other objects in the plot.
  11902. For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be
  11903. enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is
  11904. preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  11905. consider using the overloaded version of this function.
  11906. If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will
  11907. first be filled with that brush, before drawing the background pixmap. This can be useful for
  11908. background pixmaps with translucent areas.
  11909. \see setBackgroundScaled, setBackgroundScaledMode
  11910. */
  11911. void QCustomPlot::setBackground(const QPixmap &pm)
  11912. {
  11913. mBackgroundPixmap = pm;
  11914. mScaledBackgroundPixmap = QPixmap();
  11915. }
  11916. /*!
  11917. Sets the background brush of the viewport (see \ref setViewport).
  11918. Before drawing everything else, the background is filled with \a brush. If a background pixmap
  11919. was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport
  11920. before the background pixmap is drawn. This can be useful for background pixmaps with translucent
  11921. areas.
  11922. Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be
  11923. useful for exporting to image formats which support transparency, e.g. \ref savePng.
  11924. \see setBackgroundScaled, setBackgroundScaledMode
  11925. */
  11926. void QCustomPlot::setBackground(const QBrush &brush)
  11927. {
  11928. mBackgroundBrush = brush;
  11929. }
  11930. /*! \overload
  11931. Allows setting the background pixmap of the viewport, whether it shall be scaled and how it
  11932. shall be scaled in one call.
  11933. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  11934. */
  11935. void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  11936. {
  11937. mBackgroundPixmap = pm;
  11938. mScaledBackgroundPixmap = QPixmap();
  11939. mBackgroundScaled = scaled;
  11940. mBackgroundScaledMode = mode;
  11941. }
  11942. /*!
  11943. Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is
  11944. set to true, control whether and how the aspect ratio of the original pixmap is preserved with
  11945. \ref setBackgroundScaledMode.
  11946. Note that the scaled version of the original pixmap is buffered, so there is no performance
  11947. penalty on replots. (Except when the viewport dimensions are changed continuously.)
  11948. \see setBackground, setBackgroundScaledMode
  11949. */
  11950. void QCustomPlot::setBackgroundScaled(bool scaled)
  11951. {
  11952. mBackgroundScaled = scaled;
  11953. }
  11954. /*!
  11955. If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this
  11956. function to define whether and how the aspect ratio of the original pixmap is preserved.
  11957. \see setBackground, setBackgroundScaled
  11958. */
  11959. void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  11960. {
  11961. mBackgroundScaledMode = mode;
  11962. }
  11963. /*!
  11964. Returns the plottable with \a index. If the index is invalid, returns \c nullptr.
  11965. There is an overloaded version of this function with no parameter which returns the last added
  11966. plottable, see QCustomPlot::plottable()
  11967. \see plottableCount
  11968. */
  11969. QCPAbstractPlottable *QCustomPlot::plottable(int index)
  11970. {
  11971. if (index >= 0 && index < mPlottables.size())
  11972. {
  11973. return mPlottables.at(index);
  11974. } else
  11975. {
  11976. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  11977. return nullptr;
  11978. }
  11979. }
  11980. /*! \overload
  11981. Returns the last plottable that was added to the plot. If there are no plottables in the plot,
  11982. returns \c nullptr.
  11983. \see plottableCount
  11984. */
  11985. QCPAbstractPlottable *QCustomPlot::plottable()
  11986. {
  11987. if (!mPlottables.isEmpty())
  11988. {
  11989. return mPlottables.last();
  11990. } else
  11991. return nullptr;
  11992. }
  11993. /*!
  11994. Removes the specified plottable from the plot and deletes it. If necessary, the corresponding
  11995. legend item is also removed from the default legend (QCustomPlot::legend).
  11996. Returns true on success.
  11997. \see clearPlottables
  11998. */
  11999. bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable)
  12000. {
  12001. if (!mPlottables.contains(plottable))
  12002. {
  12003. qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast<quintptr>(plottable);
  12004. return false;
  12005. }
  12006. // remove plottable from legend:
  12007. plottable->removeFromLegend();
  12008. // special handling for QCPGraphs to maintain the simple graph interface:
  12009. if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
  12010. mGraphs.removeOne(graph);
  12011. // remove plottable:
  12012. delete plottable;
  12013. mPlottables.removeOne(plottable);
  12014. return true;
  12015. }
  12016. /*! \overload
  12017. Removes and deletes the plottable by its \a index.
  12018. */
  12019. bool QCustomPlot::removePlottable(int index)
  12020. {
  12021. if (index >= 0 && index < mPlottables.size())
  12022. return removePlottable(mPlottables[index]);
  12023. else
  12024. {
  12025. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12026. return false;
  12027. }
  12028. }
  12029. /*!
  12030. Removes all plottables from the plot and deletes them. Corresponding legend items are also
  12031. removed from the default legend (QCustomPlot::legend).
  12032. Returns the number of plottables removed.
  12033. \see removePlottable
  12034. */
  12035. int QCustomPlot::clearPlottables()
  12036. {
  12037. int c = mPlottables.size();
  12038. for (int i=c-1; i >= 0; --i)
  12039. removePlottable(mPlottables[i]);
  12040. return c;
  12041. }
  12042. /*!
  12043. Returns the number of currently existing plottables in the plot
  12044. \see plottable
  12045. */
  12046. int QCustomPlot::plottableCount() const
  12047. {
  12048. return mPlottables.size();
  12049. }
  12050. /*!
  12051. Returns a list of the selected plottables. If no plottables are currently selected, the list is empty.
  12052. There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs.
  12053. \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
  12054. */
  12055. QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const
  12056. {
  12057. QList<QCPAbstractPlottable*> result;
  12058. foreach (QCPAbstractPlottable *plottable, mPlottables)
  12059. {
  12060. if (plottable->selected())
  12061. result.append(plottable);
  12062. }
  12063. return result;
  12064. }
  12065. /*!
  12066. Returns any plottable at the pixel position \a pos. Since it can capture all plottables, the
  12067. return type is the abstract base class of all plottables, QCPAbstractPlottable.
  12068. For details, and if you wish to specify a certain plottable type (e.g. QCPGraph), see the
  12069. template method plottableAt<PlottableType>()
  12070. \see plottableAt<PlottableType>(), itemAt, layoutElementAt
  12071. */
  12072. QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable, int *dataIndex) const
  12073. {
  12074. return plottableAt<QCPAbstractPlottable>(pos, onlySelectable, dataIndex);
  12075. }
  12076. /*!
  12077. Returns whether this QCustomPlot instance contains the \a plottable.
  12078. */
  12079. bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const
  12080. {
  12081. return mPlottables.contains(plottable);
  12082. }
  12083. /*!
  12084. Returns the graph with \a index. If the index is invalid, returns \c nullptr.
  12085. There is an overloaded version of this function with no parameter which returns the last created
  12086. graph, see QCustomPlot::graph()
  12087. \see graphCount, addGraph
  12088. */
  12089. QCPGraph *QCustomPlot::graph(int index) const
  12090. {
  12091. if (index >= 0 && index < mGraphs.size())
  12092. {
  12093. return mGraphs.at(index);
  12094. } else
  12095. {
  12096. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12097. return nullptr;
  12098. }
  12099. }
  12100. /*! \overload
  12101. Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot,
  12102. returns \c nullptr.
  12103. \see graphCount, addGraph
  12104. */
  12105. QCPGraph *QCustomPlot::graph() const
  12106. {
  12107. if (!mGraphs.isEmpty())
  12108. {
  12109. return mGraphs.last();
  12110. } else
  12111. return nullptr;
  12112. }
  12113. /*!
  12114. Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the
  12115. bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a
  12116. keyAxis and \a valueAxis must reside in this QCustomPlot.
  12117. \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically
  12118. "y") for the graph.
  12119. Returns a pointer to the newly created graph, or \c nullptr if adding the graph failed.
  12120. \see graph, graphCount, removeGraph, clearGraphs
  12121. */
  12122. QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
  12123. {
  12124. if (!keyAxis) keyAxis = xAxis;
  12125. if (!valueAxis) valueAxis = yAxis;
  12126. if (!keyAxis || !valueAxis)
  12127. {
  12128. qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)";
  12129. return nullptr;
  12130. }
  12131. if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this)
  12132. {
  12133. qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent";
  12134. return nullptr;
  12135. }
  12136. QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis);
  12137. newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size()));
  12138. return newGraph;
  12139. }
  12140. /*!
  12141. Removes the specified \a graph from the plot and deletes it. If necessary, the corresponding
  12142. legend item is also removed from the default legend (QCustomPlot::legend). If any other graphs in
  12143. the plot have a channel fill set towards the removed graph, the channel fill property of those
  12144. graphs is reset to \c nullptr (no channel fill).
  12145. Returns true on success.
  12146. \see clearGraphs
  12147. */
  12148. bool QCustomPlot::removeGraph(QCPGraph *graph)
  12149. {
  12150. return removePlottable(graph);
  12151. }
  12152. /*! \overload
  12153. Removes and deletes the graph by its \a index.
  12154. */
  12155. bool QCustomPlot::removeGraph(int index)
  12156. {
  12157. if (index >= 0 && index < mGraphs.size())
  12158. return removeGraph(mGraphs[index]);
  12159. else
  12160. return false;
  12161. }
  12162. /*!
  12163. Removes all graphs from the plot and deletes them. Corresponding legend items are also removed
  12164. from the default legend (QCustomPlot::legend).
  12165. Returns the number of graphs removed.
  12166. \see removeGraph
  12167. */
  12168. int QCustomPlot::clearGraphs()
  12169. {
  12170. int c = mGraphs.size();
  12171. for (int i=c-1; i >= 0; --i)
  12172. removeGraph(mGraphs[i]);
  12173. return c;
  12174. }
  12175. /*!
  12176. Returns the number of currently existing graphs in the plot
  12177. \see graph, addGraph
  12178. */
  12179. int QCustomPlot::graphCount() const
  12180. {
  12181. return mGraphs.size();
  12182. }
  12183. /*!
  12184. Returns a list of the selected graphs. If no graphs are currently selected, the list is empty.
  12185. If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars,
  12186. etc., use \ref selectedPlottables.
  12187. \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
  12188. */
  12189. QList<QCPGraph*> QCustomPlot::selectedGraphs() const
  12190. {
  12191. QList<QCPGraph*> result;
  12192. foreach (QCPGraph *graph, mGraphs)
  12193. {
  12194. if (graph->selected())
  12195. result.append(graph);
  12196. }
  12197. return result;
  12198. }
  12199. /*!
  12200. Returns the item with \a index. If the index is invalid, returns \c nullptr.
  12201. There is an overloaded version of this function with no parameter which returns the last added
  12202. item, see QCustomPlot::item()
  12203. \see itemCount
  12204. */
  12205. QCPAbstractItem *QCustomPlot::item(int index) const
  12206. {
  12207. if (index >= 0 && index < mItems.size())
  12208. {
  12209. return mItems.at(index);
  12210. } else
  12211. {
  12212. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12213. return nullptr;
  12214. }
  12215. }
  12216. /*! \overload
  12217. Returns the last item that was added to this plot. If there are no items in the plot,
  12218. returns \c nullptr.
  12219. \see itemCount
  12220. */
  12221. QCPAbstractItem *QCustomPlot::item() const
  12222. {
  12223. if (!mItems.isEmpty())
  12224. {
  12225. return mItems.last();
  12226. } else
  12227. return nullptr;
  12228. }
  12229. /*!
  12230. Removes the specified item from the plot and deletes it.
  12231. Returns true on success.
  12232. \see clearItems
  12233. */
  12234. bool QCustomPlot::removeItem(QCPAbstractItem *item)
  12235. {
  12236. if (mItems.contains(item))
  12237. {
  12238. delete item;
  12239. mItems.removeOne(item);
  12240. return true;
  12241. } else
  12242. {
  12243. qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast<quintptr>(item);
  12244. return false;
  12245. }
  12246. }
  12247. /*! \overload
  12248. Removes and deletes the item by its \a index.
  12249. */
  12250. bool QCustomPlot::removeItem(int index)
  12251. {
  12252. if (index >= 0 && index < mItems.size())
  12253. return removeItem(mItems[index]);
  12254. else
  12255. {
  12256. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12257. return false;
  12258. }
  12259. }
  12260. /*!
  12261. Removes all items from the plot and deletes them.
  12262. Returns the number of items removed.
  12263. \see removeItem
  12264. */
  12265. int QCustomPlot::clearItems()
  12266. {
  12267. int c = mItems.size();
  12268. for (int i=c-1; i >= 0; --i)
  12269. removeItem(mItems[i]);
  12270. return c;
  12271. }
  12272. /*!
  12273. Returns the number of currently existing items in the plot
  12274. \see item
  12275. */
  12276. int QCustomPlot::itemCount() const
  12277. {
  12278. return mItems.size();
  12279. }
  12280. /*!
  12281. Returns a list of the selected items. If no items are currently selected, the list is empty.
  12282. \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected
  12283. */
  12284. QList<QCPAbstractItem*> QCustomPlot::selectedItems() const
  12285. {
  12286. QList<QCPAbstractItem*> result;
  12287. foreach (QCPAbstractItem *item, mItems)
  12288. {
  12289. if (item->selected())
  12290. result.append(item);
  12291. }
  12292. return result;
  12293. }
  12294. /*!
  12295. Returns the item at the pixel position \a pos. Since it can capture all items, the
  12296. return type is the abstract base class of all items, QCPAbstractItem.
  12297. For details, and if you wish to specify a certain item type (e.g. QCPItemLine), see the
  12298. template method itemAt<ItemType>()
  12299. \see itemAt<ItemType>(), plottableAt, layoutElementAt
  12300. */
  12301. QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const
  12302. {
  12303. return itemAt<QCPAbstractItem>(pos, onlySelectable);
  12304. }
  12305. /*!
  12306. Returns whether this QCustomPlot contains the \a item.
  12307. \see item
  12308. */
  12309. bool QCustomPlot::hasItem(QCPAbstractItem *item) const
  12310. {
  12311. return mItems.contains(item);
  12312. }
  12313. /*!
  12314. Returns the layer with the specified \a name. If there is no layer with the specified name, \c
  12315. nullptr is returned.
  12316. Layer names are case-sensitive.
  12317. \see addLayer, moveLayer, removeLayer
  12318. */
  12319. QCPLayer *QCustomPlot::layer(const QString &name) const
  12320. {
  12321. foreach (QCPLayer *layer, mLayers)
  12322. {
  12323. if (layer->name() == name)
  12324. return layer;
  12325. }
  12326. return nullptr;
  12327. }
  12328. /*! \overload
  12329. Returns the layer by \a index. If the index is invalid, \c nullptr is returned.
  12330. \see addLayer, moveLayer, removeLayer
  12331. */
  12332. QCPLayer *QCustomPlot::layer(int index) const
  12333. {
  12334. if (index >= 0 && index < mLayers.size())
  12335. {
  12336. return mLayers.at(index);
  12337. } else
  12338. {
  12339. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12340. return nullptr;
  12341. }
  12342. }
  12343. /*!
  12344. Returns the layer that is set as current layer (see \ref setCurrentLayer).
  12345. */
  12346. QCPLayer *QCustomPlot::currentLayer() const
  12347. {
  12348. return mCurrentLayer;
  12349. }
  12350. /*!
  12351. Sets the layer with the specified \a name to be the current layer. All layerables (\ref
  12352. QCPLayerable), e.g. plottables and items, are created on the current layer.
  12353. Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot.
  12354. Layer names are case-sensitive.
  12355. \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer
  12356. */
  12357. bool QCustomPlot::setCurrentLayer(const QString &name)
  12358. {
  12359. if (QCPLayer *newCurrentLayer = layer(name))
  12360. {
  12361. return setCurrentLayer(newCurrentLayer);
  12362. } else
  12363. {
  12364. qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name;
  12365. return false;
  12366. }
  12367. }
  12368. /*! \overload
  12369. Sets the provided \a layer to be the current layer.
  12370. Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot.
  12371. \see addLayer, moveLayer, removeLayer
  12372. */
  12373. bool QCustomPlot::setCurrentLayer(QCPLayer *layer)
  12374. {
  12375. if (!mLayers.contains(layer))
  12376. {
  12377. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  12378. return false;
  12379. }
  12380. mCurrentLayer = layer;
  12381. return true;
  12382. }
  12383. /*!
  12384. Returns the number of currently existing layers in the plot
  12385. \see layer, addLayer
  12386. */
  12387. int QCustomPlot::layerCount() const
  12388. {
  12389. return mLayers.size();
  12390. }
  12391. /*!
  12392. Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which
  12393. must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer.
  12394. Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a
  12395. valid layer inside this QCustomPlot.
  12396. If \a otherLayer is 0, the highest layer in the QCustomPlot will be used.
  12397. For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer.
  12398. \see layer, moveLayer, removeLayer
  12399. */
  12400. bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
  12401. {
  12402. if (!otherLayer)
  12403. otherLayer = mLayers.last();
  12404. if (!mLayers.contains(otherLayer))
  12405. {
  12406. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
  12407. return false;
  12408. }
  12409. if (layer(name))
  12410. {
  12411. qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name;
  12412. return false;
  12413. }
  12414. QCPLayer *newLayer = new QCPLayer(this, name);
  12415. mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer);
  12416. updateLayerIndices();
  12417. setupPaintBuffers(); // associates new layer with the appropriate paint buffer
  12418. return true;
  12419. }
  12420. /*!
  12421. Removes the specified \a layer and returns true on success.
  12422. All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below
  12423. \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both
  12424. cases, the total rendering order of all layerables in the QCustomPlot is preserved.
  12425. If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom
  12426. layer) becomes the new current layer.
  12427. It is not possible to remove the last layer of the plot.
  12428. \see layer, addLayer, moveLayer
  12429. */
  12430. bool QCustomPlot::removeLayer(QCPLayer *layer)
  12431. {
  12432. if (!mLayers.contains(layer))
  12433. {
  12434. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  12435. return false;
  12436. }
  12437. if (mLayers.size() < 2)
  12438. {
  12439. qDebug() << Q_FUNC_INFO << "can't remove last layer";
  12440. return false;
  12441. }
  12442. // append all children of this layer to layer below (if this is lowest layer, prepend to layer above)
  12443. int removedIndex = layer->index();
  12444. bool isFirstLayer = removedIndex==0;
  12445. QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1);
  12446. QList<QCPLayerable*> children = layer->children();
  12447. if (isFirstLayer) // prepend in reverse order (such that relative order stays the same)
  12448. std::reverse(children.begin(), children.end());
  12449. foreach (QCPLayerable *child, children)
  12450. child->moveToLayer(targetLayer, isFirstLayer); // prepend if isFirstLayer, otherwise append
  12451. // if removed layer is current layer, change current layer to layer below/above:
  12452. if (layer == mCurrentLayer)
  12453. setCurrentLayer(targetLayer);
  12454. // invalidate the paint buffer that was responsible for this layer:
  12455. if (QSharedPointer<QCPAbstractPaintBuffer> pb = layer->mPaintBuffer.toStrongRef())
  12456. pb->setInvalidated();
  12457. // remove layer:
  12458. delete layer;
  12459. mLayers.removeOne(layer);
  12460. updateLayerIndices();
  12461. return true;
  12462. }
  12463. /*!
  12464. Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or
  12465. below is controlled with \a insertMode.
  12466. Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the
  12467. QCustomPlot.
  12468. \see layer, addLayer, moveLayer
  12469. */
  12470. bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
  12471. {
  12472. if (!mLayers.contains(layer))
  12473. {
  12474. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  12475. return false;
  12476. }
  12477. if (!mLayers.contains(otherLayer))
  12478. {
  12479. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
  12480. return false;
  12481. }
  12482. if (layer->index() > otherLayer->index())
  12483. mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0));
  12484. else if (layer->index() < otherLayer->index())
  12485. mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 0:-1));
  12486. // invalidate the paint buffers that are responsible for the layers:
  12487. if (QSharedPointer<QCPAbstractPaintBuffer> pb = layer->mPaintBuffer.toStrongRef())
  12488. pb->setInvalidated();
  12489. if (QSharedPointer<QCPAbstractPaintBuffer> pb = otherLayer->mPaintBuffer.toStrongRef())
  12490. pb->setInvalidated();
  12491. updateLayerIndices();
  12492. return true;
  12493. }
  12494. /*!
  12495. Returns the number of axis rects in the plot.
  12496. All axis rects can be accessed via QCustomPlot::axisRect().
  12497. Initially, only one axis rect exists in the plot.
  12498. \see axisRect, axisRects
  12499. */
  12500. int QCustomPlot::axisRectCount() const
  12501. {
  12502. return axisRects().size();
  12503. }
  12504. /*!
  12505. Returns the axis rect with \a index.
  12506. Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were
  12507. added, all of them may be accessed with this function in a linear fashion (even when they are
  12508. nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout).
  12509. The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding
  12510. them. For example, if the axis rects are in the top level grid layout (accessible via \ref
  12511. QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's
  12512. default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst
  12513. "foColumnsFirst" wasn't changed.
  12514. If you want to access axis rects by their row and column index, use the layout interface. For
  12515. example, use \ref QCPLayoutGrid::element of the top level grid layout, and \c qobject_cast the
  12516. returned layout element to \ref QCPAxisRect. (See also \ref thelayoutsystem.)
  12517. \see axisRectCount, axisRects, QCPLayoutGrid::setFillOrder
  12518. */
  12519. QCPAxisRect *QCustomPlot::axisRect(int index) const
  12520. {
  12521. const QList<QCPAxisRect*> rectList = axisRects();
  12522. if (index >= 0 && index < rectList.size())
  12523. {
  12524. return rectList.at(index);
  12525. } else
  12526. {
  12527. qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index;
  12528. return nullptr;
  12529. }
  12530. }
  12531. /*!
  12532. Returns all axis rects in the plot.
  12533. The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding
  12534. them. For example, if the axis rects are in the top level grid layout (accessible via \ref
  12535. QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's
  12536. default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst
  12537. "foColumnsFirst" wasn't changed.
  12538. \see axisRectCount, axisRect, QCPLayoutGrid::setFillOrder
  12539. */
  12540. QList<QCPAxisRect*> QCustomPlot::axisRects() const
  12541. {
  12542. QList<QCPAxisRect*> result;
  12543. QStack<QCPLayoutElement*> elementStack;
  12544. if (mPlotLayout)
  12545. elementStack.push(mPlotLayout);
  12546. while (!elementStack.isEmpty())
  12547. {
  12548. foreach (QCPLayoutElement *element, elementStack.pop()->elements(false))
  12549. {
  12550. if (element)
  12551. {
  12552. elementStack.push(element);
  12553. if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(element))
  12554. result.append(ar);
  12555. }
  12556. }
  12557. }
  12558. return result;
  12559. }
  12560. /*!
  12561. Returns the layout element at pixel position \a pos. If there is no element at that position,
  12562. returns \c nullptr.
  12563. Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on
  12564. any of its parent elements is set to false, it will not be considered.
  12565. \see itemAt, plottableAt
  12566. */
  12567. QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const
  12568. {
  12569. QCPLayoutElement *currentElement = mPlotLayout;
  12570. bool searchSubElements = true;
  12571. while (searchSubElements && currentElement)
  12572. {
  12573. searchSubElements = false;
  12574. foreach (QCPLayoutElement *subElement, currentElement->elements(false))
  12575. {
  12576. if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
  12577. {
  12578. currentElement = subElement;
  12579. searchSubElements = true;
  12580. break;
  12581. }
  12582. }
  12583. }
  12584. return currentElement;
  12585. }
  12586. /*!
  12587. Returns the layout element of type \ref QCPAxisRect at pixel position \a pos. This method ignores
  12588. other layout elements even if they are visually in front of the axis rect (e.g. a \ref
  12589. QCPLegend). If there is no axis rect at that position, returns \c nullptr.
  12590. Only visible axis rects are used. If \ref QCPLayoutElement::setVisible on the axis rect itself or
  12591. on any of its parent elements is set to false, it will not be considered.
  12592. \see layoutElementAt
  12593. */
  12594. QCPAxisRect *QCustomPlot::axisRectAt(const QPointF &pos) const
  12595. {
  12596. QCPAxisRect *result = nullptr;
  12597. QCPLayoutElement *currentElement = mPlotLayout;
  12598. bool searchSubElements = true;
  12599. while (searchSubElements && currentElement)
  12600. {
  12601. searchSubElements = false;
  12602. foreach (QCPLayoutElement *subElement, currentElement->elements(false))
  12603. {
  12604. if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
  12605. {
  12606. currentElement = subElement;
  12607. searchSubElements = true;
  12608. if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(currentElement))
  12609. result = ar;
  12610. break;
  12611. }
  12612. }
  12613. }
  12614. return result;
  12615. }
  12616. /*!
  12617. Returns the axes that currently have selected parts, i.e. whose selection state is not \ref
  12618. QCPAxis::spNone.
  12619. \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts,
  12620. QCPAxis::setSelectableParts
  12621. */
  12622. QList<QCPAxis*> QCustomPlot::selectedAxes() const
  12623. {
  12624. QList<QCPAxis*> result, allAxes;
  12625. foreach (QCPAxisRect *rect, axisRects())
  12626. allAxes << rect->axes();
  12627. foreach (QCPAxis *axis, allAxes)
  12628. {
  12629. if (axis->selectedParts() != QCPAxis::spNone)
  12630. result.append(axis);
  12631. }
  12632. return result;
  12633. }
  12634. /*!
  12635. Returns the legends that currently have selected parts, i.e. whose selection state is not \ref
  12636. QCPLegend::spNone.
  12637. \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts,
  12638. QCPLegend::setSelectableParts, QCPLegend::selectedItems
  12639. */
  12640. QList<QCPLegend*> QCustomPlot::selectedLegends() const
  12641. {
  12642. QList<QCPLegend*> result;
  12643. QStack<QCPLayoutElement*> elementStack;
  12644. if (mPlotLayout)
  12645. elementStack.push(mPlotLayout);
  12646. while (!elementStack.isEmpty())
  12647. {
  12648. foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false))
  12649. {
  12650. if (subElement)
  12651. {
  12652. elementStack.push(subElement);
  12653. if (QCPLegend *leg = qobject_cast<QCPLegend*>(subElement))
  12654. {
  12655. if (leg->selectedParts() != QCPLegend::spNone)
  12656. result.append(leg);
  12657. }
  12658. }
  12659. }
  12660. }
  12661. return result;
  12662. }
  12663. /*!
  12664. Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot.
  12665. Since calling this function is not a user interaction, this does not emit the \ref
  12666. selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the
  12667. objects were previously selected.
  12668. \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends
  12669. */
  12670. void QCustomPlot::deselectAll()
  12671. {
  12672. foreach (QCPLayer *layer, mLayers)
  12673. {
  12674. foreach (QCPLayerable *layerable, layer->children())
  12675. layerable->deselectEvent(nullptr);
  12676. }
  12677. }
  12678. /*!
  12679. Causes a complete replot into the internal paint buffer(s). Finally, the widget surface is
  12680. refreshed with the new buffer contents. This is the method that must be called to make changes to
  12681. the plot, e.g. on the axis ranges or data points of graphs, visible.
  12682. The parameter \a refreshPriority can be used to fine-tune the timing of the replot. For example
  12683. if your application calls \ref replot very quickly in succession (e.g. multiple independent
  12684. functions change some aspects of the plot and each wants to make sure the change gets replotted),
  12685. it is advisable to set \a refreshPriority to \ref QCustomPlot::rpQueuedReplot. This way, the
  12686. actual replotting is deferred to the next event loop iteration. Multiple successive calls of \ref
  12687. replot with this priority will only cause a single replot, avoiding redundant replots and
  12688. improving performance.
  12689. Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the
  12690. QCustomPlot widget and user interactions (object selection and range dragging/zooming).
  12691. Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref
  12692. afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two
  12693. signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite
  12694. recursion.
  12695. If a layer is in mode \ref QCPLayer::lmBuffered (\ref QCPLayer::setMode), it is also possible to
  12696. replot only that specific layer via \ref QCPLayer::replot. See the documentation there for
  12697. details.
  12698. \see replotTime
  12699. */
  12700. void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority)
  12701. {
  12702. if (refreshPriority == QCustomPlot::rpQueuedReplot)
  12703. {
  12704. if (!mReplotQueued)
  12705. {
  12706. mReplotQueued = true;
  12707. QTimer::singleShot(0, this, SLOT(replot()));
  12708. }
  12709. return;
  12710. }
  12711. if (mReplotting) // incase signals loop back to replot slot
  12712. return;
  12713. mReplotting = true;
  12714. mReplotQueued = false;
  12715. Q_EMIT beforeReplot();
  12716. # if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
  12717. QTime replotTimer;
  12718. replotTimer.start();
  12719. # else
  12720. QElapsedTimer replotTimer;
  12721. replotTimer.start();
  12722. # endif
  12723. updateLayout();
  12724. // draw all layered objects (grid, axes, plottables, items, legend,...) into their buffers:
  12725. setupPaintBuffers();
  12726. foreach (QCPLayer *layer, mLayers)
  12727. layer->drawToPaintBuffer();
  12728. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  12729. buffer->setInvalidated(false);
  12730. if ((refreshPriority == rpRefreshHint && mPlottingHints.testFlag(QCP::phImmediateRefresh)) || refreshPriority==rpImmediateRefresh)
  12731. repaint();
  12732. else
  12733. update();
  12734. # if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
  12735. mReplotTime = replotTimer.elapsed();
  12736. # else
  12737. mReplotTime = replotTimer.nsecsElapsed()*1e-6;
  12738. # endif
  12739. if (!qFuzzyIsNull(mReplotTimeAverage))
  12740. mReplotTimeAverage = mReplotTimeAverage*0.9 + mReplotTime*0.1; // exponential moving average with a time constant of 10 last replots
  12741. else
  12742. mReplotTimeAverage = mReplotTime; // no previous replots to average with, so initialize with replot time
  12743. Q_EMIT afterReplot();
  12744. mReplotting = false;
  12745. }
  12746. /*!
  12747. Returns the time in milliseconds that the last replot took. If \a average is set to true, an
  12748. exponential moving average over the last couple of replots is returned.
  12749. \see replot
  12750. */
  12751. double QCustomPlot::replotTime(bool average) const
  12752. {
  12753. return average ? mReplotTimeAverage : mReplotTime;
  12754. }
  12755. /*!
  12756. Rescales the axes such that all plottables (like graphs) in the plot are fully visible.
  12757. if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true
  12758. (QCPLayerable::setVisible), will be used to rescale the axes.
  12759. \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale
  12760. */
  12761. void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
  12762. {
  12763. QList<QCPAxis*> allAxes;
  12764. foreach (QCPAxisRect *rect, axisRects())
  12765. allAxes << rect->axes();
  12766. foreach (QCPAxis *axis, allAxes)
  12767. axis->rescale(onlyVisiblePlottables);
  12768. }
  12769. /*!
  12770. Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale
  12771. of texts and lines will be derived from the specified \a width and \a height. This means, the
  12772. output will look like the normal on-screen output of a QCustomPlot widget with the corresponding
  12773. pixel width and height. If either \a width or \a height is zero, the exported image will have the
  12774. same dimensions as the QCustomPlot widget currently has.
  12775. Setting \a exportPen to \ref QCP::epNoCosmetic allows to disable the use of cosmetic pens when
  12776. drawing to the PDF file. Cosmetic pens are pens with numerical width 0, which are always drawn as
  12777. a one pixel wide line, no matter what zoom factor is set in the PDF-Viewer. For more information
  12778. about cosmetic pens, see the QPainter and QPen documentation.
  12779. The objects of the plot will appear in the current selection state. If you don't want any
  12780. selected objects to be painted in their selected look, deselect everything with \ref deselectAll
  12781. before calling this function.
  12782. Returns true on success.
  12783. \warning
  12784. \li If you plan on editing the exported PDF file with a vector graphics editor like Inkscape, it
  12785. is advised to set \a exportPen to \ref QCP::epNoCosmetic to avoid losing those cosmetic lines
  12786. (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks).
  12787. \li If calling this function inside the constructor of the parent of the QCustomPlot widget
  12788. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12789. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12790. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12791. aren't defined yet inside the constructor, so you would get an image that has strange
  12792. widths/heights.
  12793. \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting
  12794. PDF file.
  12795. \note On Android systems, this method does nothing and issues an according qDebug warning
  12796. message. This is also the case if for other reasons the define flag \c QT_NO_PRINTER is set.
  12797. \see savePng, saveBmp, saveJpg, saveRastered
  12798. */
  12799. bool QCustomPlot::savePdf(const QString &fileName, int width, int height, QCP::ExportPen exportPen, const QString &pdfCreator, const QString &pdfTitle)
  12800. {
  12801. bool success = false;
  12802. #ifdef QT_NO_PRINTER
  12803. Q_UNUSED(fileName)
  12804. Q_UNUSED(exportPen)
  12805. Q_UNUSED(width)
  12806. Q_UNUSED(height)
  12807. Q_UNUSED(pdfCreator)
  12808. Q_UNUSED(pdfTitle)
  12809. qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created.";
  12810. #else
  12811. int newWidth, newHeight;
  12812. if (width == 0 || height == 0)
  12813. {
  12814. newWidth = this->width();
  12815. newHeight = this->height();
  12816. } else
  12817. {
  12818. newWidth = width;
  12819. newHeight = height;
  12820. }
  12821. QPrinter printer(QPrinter::ScreenResolution);
  12822. printer.setOutputFileName(fileName);
  12823. printer.setOutputFormat(QPrinter::PdfFormat);
  12824. printer.setColorMode(QPrinter::Color);
  12825. printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator);
  12826. printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle);
  12827. QRect oldViewport = viewport();
  12828. setViewport(QRect(0, 0, newWidth, newHeight));
  12829. #if QT_VERSION < QT_VERSION_CHECK(5, 3, 0)
  12830. printer.setFullPage(true);
  12831. printer.setPaperSize(viewport().size(), QPrinter::DevicePixel);
  12832. #else
  12833. QPageLayout pageLayout;
  12834. pageLayout.setMode(QPageLayout::FullPageMode);
  12835. pageLayout.setOrientation(QPageLayout::Portrait);
  12836. pageLayout.setMargins(QMarginsF(0, 0, 0, 0));
  12837. pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch));
  12838. printer.setPageLayout(pageLayout);
  12839. #endif
  12840. QCPPainter printpainter;
  12841. if (printpainter.begin(&printer))
  12842. {
  12843. printpainter.setMode(QCPPainter::pmVectorized);
  12844. printpainter.setMode(QCPPainter::pmNoCaching);
  12845. printpainter.setMode(QCPPainter::pmNonCosmetic, exportPen==QCP::epNoCosmetic);
  12846. printpainter.setWindow(mViewport);
  12847. if (mBackgroundBrush.style() != Qt::NoBrush &&
  12848. mBackgroundBrush.color() != Qt::white &&
  12849. mBackgroundBrush.color() != Qt::transparent &&
  12850. mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent
  12851. printpainter.fillRect(viewport(), mBackgroundBrush);
  12852. draw(&printpainter);
  12853. printpainter.end();
  12854. success = true;
  12855. }
  12856. setViewport(oldViewport);
  12857. #endif // QT_NO_PRINTER
  12858. return success;
  12859. }
  12860. /*!
  12861. Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width
  12862. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12863. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12864. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12865. parameter.
  12866. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12867. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12868. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12869. 200*200 pixel resolution.
  12870. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12871. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12872. QCustomPlot to place objects with sub-pixel accuracy.
  12873. image compression can be controlled with the \a quality parameter which must be between 0 and 100
  12874. or -1 to use the default setting.
  12875. The \a resolution will be written to the image file header and has no direct consequence for the
  12876. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12877. it will be able to scale the image to match either a given size in real units of length (inch,
  12878. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12879. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12880. resolution unit internally.
  12881. Returns true on success. If this function fails, most likely the PNG format isn't supported by
  12882. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12883. The objects of the plot will appear in the current selection state. If you don't want any selected
  12884. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12885. this function.
  12886. If you want the PNG to have a transparent background, call \ref setBackground(const QBrush &brush)
  12887. with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
  12888. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12889. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12890. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12891. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12892. aren't defined yet inside the constructor, so you would get an image that has strange
  12893. widths/heights.
  12894. \see savePdf, saveBmp, saveJpg, saveRastered
  12895. */
  12896. bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  12897. {
  12898. return saveRastered(fileName, width, height, scale, "PNG", quality, resolution, resolutionUnit);
  12899. }
  12900. /*!
  12901. Saves a JPEG image file to \a fileName on disc. The output plot will have the dimensions \a width
  12902. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12903. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12904. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12905. parameter.
  12906. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12907. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12908. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12909. 200*200 pixel resolution.
  12910. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12911. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12912. QCustomPlot to place objects with sub-pixel accuracy.
  12913. image compression can be controlled with the \a quality parameter which must be between 0 and 100
  12914. or -1 to use the default setting.
  12915. The \a resolution will be written to the image file header and has no direct consequence for the
  12916. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12917. it will be able to scale the image to match either a given size in real units of length (inch,
  12918. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12919. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12920. resolution unit internally.
  12921. Returns true on success. If this function fails, most likely the JPEG format isn't supported by
  12922. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12923. The objects of the plot will appear in the current selection state. If you don't want any selected
  12924. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12925. this function.
  12926. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12927. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12928. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12929. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12930. aren't defined yet inside the constructor, so you would get an image that has strange
  12931. widths/heights.
  12932. \see savePdf, savePng, saveBmp, saveRastered
  12933. */
  12934. bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  12935. {
  12936. return saveRastered(fileName, width, height, scale, "JPG", quality, resolution, resolutionUnit);
  12937. }
  12938. /*!
  12939. Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width
  12940. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12941. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12942. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12943. parameter.
  12944. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12945. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12946. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12947. 200*200 pixel resolution.
  12948. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12949. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12950. QCustomPlot to place objects with sub-pixel accuracy.
  12951. The \a resolution will be written to the image file header and has no direct consequence for the
  12952. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12953. it will be able to scale the image to match either a given size in real units of length (inch,
  12954. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12955. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12956. resolution unit internally.
  12957. Returns true on success. If this function fails, most likely the BMP format isn't supported by
  12958. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12959. The objects of the plot will appear in the current selection state. If you don't want any selected
  12960. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12961. this function.
  12962. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12963. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12964. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12965. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12966. aren't defined yet inside the constructor, so you would get an image that has strange
  12967. widths/heights.
  12968. \see savePdf, savePng, saveJpg, saveRastered
  12969. */
  12970. bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale, int resolution, QCP::ResolutionUnit resolutionUnit)
  12971. {
  12972. return saveRastered(fileName, width, height, scale, "BMP", -1, resolution, resolutionUnit);
  12973. }
  12974. /*! \internal
  12975. Returns a minimum size hint that corresponds to the minimum size of the top level layout
  12976. (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum
  12977. size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot.
  12978. This is especially important, when placed in a QLayout where other components try to take in as
  12979. much space as possible (e.g. QMdiArea).
  12980. */
  12981. QSize QCustomPlot::minimumSizeHint() const
  12982. {
  12983. return mPlotLayout->minimumOuterSizeHint();
  12984. }
  12985. /*! \internal
  12986. Returns a size hint that is the same as \ref minimumSizeHint.
  12987. */
  12988. QSize QCustomPlot::sizeHint() const
  12989. {
  12990. return mPlotLayout->minimumOuterSizeHint();
  12991. }
  12992. /*! \internal
  12993. Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but
  12994. draws the internal buffer on the widget surface.
  12995. */
  12996. void QCustomPlot::paintEvent(QPaintEvent *event)
  12997. {
  12998. Q_UNUSED(event)
  12999. QCPPainter painter(this);
  13000. if (painter.isActive())
  13001. {
  13002. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  13003. painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem
  13004. #endif
  13005. if (mBackgroundBrush.style() != Qt::NoBrush)
  13006. painter.fillRect(mViewport, mBackgroundBrush);
  13007. drawBackground(&painter);
  13008. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  13009. buffer->draw(&painter);
  13010. }
  13011. }
  13012. /*! \internal
  13013. Event handler for a resize of the QCustomPlot widget. The viewport (which becomes the outer rect
  13014. of mPlotLayout) is resized appropriately. Finally a \ref replot is performed.
  13015. */
  13016. void QCustomPlot::resizeEvent(QResizeEvent *event)
  13017. {
  13018. Q_UNUSED(event)
  13019. // resize and repaint the buffer:
  13020. setViewport(rect());
  13021. replot(rpQueuedRefresh); // queued refresh is important here, to prevent painting issues in some contexts (e.g. MDI subwindow)
  13022. }
  13023. /*! \internal
  13024. Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then
  13025. determines the layerable under the cursor and forwards the event to it. Finally, emits the
  13026. specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
  13027. axisDoubleClick, etc.).
  13028. \see mousePressEvent, mouseReleaseEvent
  13029. */
  13030. void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event)
  13031. {
  13032. Q_EMIT mouseDoubleClick(event);
  13033. mMouseHasMoved = false;
  13034. mMousePressPos = event->pos();
  13035. // determine layerable under the cursor (this event is called instead of the second press event in a double-click):
  13036. QList<QVariant> details;
  13037. QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
  13038. for (int i=0; i<candidates.size(); ++i)
  13039. {
  13040. event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
  13041. candidates.at(i)->mouseDoubleClickEvent(event, details.at(i));
  13042. if (event->isAccepted())
  13043. {
  13044. mMouseEventLayerable = candidates.at(i);
  13045. mMouseEventLayerableDetails = details.at(i);
  13046. break;
  13047. }
  13048. }
  13049. // emit specialized object double click signals:
  13050. if (!candidates.isEmpty())
  13051. {
  13052. if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(candidates.first()))
  13053. {
  13054. int dataIndex = 0;
  13055. if (!details.first().value<QCPDataSelection>().isEmpty())
  13056. dataIndex = details.first().value<QCPDataSelection>().dataRange().begin();
  13057. Q_EMIT plottableDoubleClick(ap, dataIndex, event);
  13058. } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(candidates.first()))
  13059. Q_EMIT axisDoubleClick(ax, details.first().value<QCPAxis::SelectablePart>(), event);
  13060. else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(candidates.first()))
  13061. Q_EMIT itemDoubleClick(ai, event);
  13062. else if (QCPLegend *lg = qobject_cast<QCPLegend*>(candidates.first()))
  13063. Q_EMIT legendDoubleClick(lg, nullptr, event);
  13064. else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(candidates.first()))
  13065. Q_EMIT legendDoubleClick(li->parentLegend(), li, event);
  13066. }
  13067. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13068. }
  13069. /*! \internal
  13070. Event handler for when a mouse button is pressed. Emits the mousePress signal.
  13071. If the current \ref setSelectionRectMode is not \ref QCP::srmNone, passes the event to the
  13072. selection rect. Otherwise determines the layerable under the cursor and forwards the event to it.
  13073. \see mouseMoveEvent, mouseReleaseEvent
  13074. */
  13075. void QCustomPlot::mousePressEvent(QMouseEvent *event)
  13076. {
  13077. Q_EMIT mousePress(event);
  13078. // save some state to tell in releaseEvent whether it was a click:
  13079. mMouseHasMoved = false;
  13080. mMousePressPos = event->pos();
  13081. if (mSelectionRect && mSelectionRectMode != QCP::srmNone)
  13082. {
  13083. if (mSelectionRectMode != QCP::srmZoom || qobject_cast<QCPAxisRect*>(axisRectAt(mMousePressPos))) // in zoom mode only activate selection rect if on an axis rect
  13084. mSelectionRect->startSelection(event);
  13085. } else
  13086. {
  13087. // no selection rect interaction, prepare for click signal emission and forward event to layerable under the cursor:
  13088. QList<QVariant> details;
  13089. QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
  13090. if (!candidates.isEmpty())
  13091. {
  13092. mMouseSignalLayerable = candidates.first(); // candidate for signal emission is always topmost hit layerable (signal emitted in release event)
  13093. mMouseSignalLayerableDetails = details.first();
  13094. }
  13095. // forward event to topmost candidate which accepts the event:
  13096. for (int i=0; i<candidates.size(); ++i)
  13097. {
  13098. event->accept(); // default impl of QCPLayerable's mouse events call ignore() on the event, in that case propagate to next candidate in list
  13099. candidates.at(i)->mousePressEvent(event, details.at(i));
  13100. if (event->isAccepted())
  13101. {
  13102. mMouseEventLayerable = candidates.at(i);
  13103. mMouseEventLayerableDetails = details.at(i);
  13104. break;
  13105. }
  13106. }
  13107. }
  13108. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13109. }
  13110. /*! \internal
  13111. Event handler for when the cursor is moved. Emits the \ref mouseMove signal.
  13112. If the selection rect (\ref setSelectionRect) is currently active, the event is forwarded to it
  13113. in order to update the rect geometry.
  13114. Otherwise, if a layout element has mouse capture focus (a mousePressEvent happened on top of the
  13115. layout element before), the mouseMoveEvent is forwarded to that element.
  13116. \see mousePressEvent, mouseReleaseEvent
  13117. */
  13118. void QCustomPlot::mouseMoveEvent(QMouseEvent *event)
  13119. {
  13120. Q_EMIT mouseMove(event);
  13121. if (!mMouseHasMoved && (mMousePressPos-event->pos()).manhattanLength() > 3)
  13122. mMouseHasMoved = true; // moved too far from mouse press position, don't handle as click on mouse release
  13123. if (mSelectionRect && mSelectionRect->isActive())
  13124. mSelectionRect->moveSelection(event);
  13125. else if (mMouseEventLayerable) // call event of affected layerable:
  13126. mMouseEventLayerable->mouseMoveEvent(event, mMousePressPos);
  13127. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13128. }
  13129. /*! \internal
  13130. Event handler for when a mouse button is released. Emits the \ref mouseRelease signal.
  13131. If the mouse was moved less than a certain threshold in any direction since the \ref
  13132. mousePressEvent, it is considered a click which causes the selection mechanism (if activated via
  13133. \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse
  13134. click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.)
  13135. If a layerable is the mouse capturer (a \ref mousePressEvent happened on top of the layerable
  13136. before), the \ref mouseReleaseEvent is forwarded to that element.
  13137. \see mousePressEvent, mouseMoveEvent
  13138. */
  13139. void QCustomPlot::mouseReleaseEvent(QMouseEvent *event)
  13140. {
  13141. Q_EMIT mouseRelease(event);
  13142. if (!mMouseHasMoved) // mouse hasn't moved (much) between press and release, so handle as click
  13143. {
  13144. if (mSelectionRect && mSelectionRect->isActive()) // a simple click shouldn't successfully finish a selection rect, so cancel it here
  13145. mSelectionRect->cancel();
  13146. if (event->button() == Qt::LeftButton)
  13147. processPointSelection(event);
  13148. // emit specialized click signals of QCustomPlot instance:
  13149. if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(mMouseSignalLayerable))
  13150. {
  13151. int dataIndex = 0;
  13152. if (!mMouseSignalLayerableDetails.value<QCPDataSelection>().isEmpty())
  13153. dataIndex = mMouseSignalLayerableDetails.value<QCPDataSelection>().dataRange().begin();
  13154. Q_EMIT plottableClick(ap, dataIndex, event);
  13155. } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(mMouseSignalLayerable))
  13156. Q_EMIT axisClick(ax, mMouseSignalLayerableDetails.value<QCPAxis::SelectablePart>(), event);
  13157. else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(mMouseSignalLayerable))
  13158. Q_EMIT itemClick(ai, event);
  13159. else if (QCPLegend *lg = qobject_cast<QCPLegend*>(mMouseSignalLayerable))
  13160. Q_EMIT legendClick(lg, nullptr, event);
  13161. else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(mMouseSignalLayerable))
  13162. Q_EMIT legendClick(li->parentLegend(), li, event);
  13163. mMouseSignalLayerable = nullptr;
  13164. }
  13165. if (mSelectionRect && mSelectionRect->isActive()) // Note: if a click was detected above, the selection rect is canceled there
  13166. {
  13167. // finish selection rect, the appropriate action will be taken via signal-slot connection:
  13168. mSelectionRect->endSelection(event);
  13169. } else
  13170. {
  13171. // call event of affected layerable:
  13172. if (mMouseEventLayerable)
  13173. {
  13174. mMouseEventLayerable->mouseReleaseEvent(event, mMousePressPos);
  13175. mMouseEventLayerable = nullptr;
  13176. }
  13177. }
  13178. if (noAntialiasingOnDrag())
  13179. replot(rpQueuedReplot);
  13180. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13181. }
  13182. /*! \internal
  13183. Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then
  13184. determines the affected layerable and forwards the event to it.
  13185. */
  13186. void QCustomPlot::wheelEvent(QWheelEvent *event)
  13187. {
  13188. Q_EMIT mouseWheel(event);
  13189. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  13190. const QPointF pos = event->pos();
  13191. #else
  13192. const QPointF pos = event->position();
  13193. #endif
  13194. // forward event to layerable under cursor:
  13195. foreach (QCPLayerable *candidate, layerableListAt(pos, false))
  13196. {
  13197. event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
  13198. candidate->wheelEvent(event);
  13199. if (event->isAccepted())
  13200. break;
  13201. }
  13202. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13203. }
  13204. /*! \internal
  13205. This function draws the entire plot, including background pixmap, with the specified \a painter.
  13206. It does not make use of the paint buffers like \ref replot, so this is the function typically
  13207. used by saving/exporting methods such as \ref savePdf or \ref toPainter.
  13208. Note that it does not fill the background with the background brush (as the user may specify with
  13209. \ref setBackground(const QBrush &brush)), this is up to the respective functions calling this
  13210. method.
  13211. */
  13212. void QCustomPlot::draw(QCPPainter *painter)
  13213. {
  13214. updateLayout();
  13215. // draw viewport background pixmap:
  13216. drawBackground(painter);
  13217. // draw all layered objects (grid, axes, plottables, items, legend,...):
  13218. foreach (QCPLayer *layer, mLayers)
  13219. layer->draw(painter);
  13220. /* Debug code to draw all layout element rects
  13221. foreach (QCPLayoutElement *el, findChildren<QCPLayoutElement*>())
  13222. {
  13223. painter->setBrush(Qt::NoBrush);
  13224. painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine));
  13225. painter->drawRect(el->rect());
  13226. painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine));
  13227. painter->drawRect(el->outerRect());
  13228. }
  13229. */
  13230. }
  13231. /*! \internal
  13232. Performs the layout update steps defined by \ref QCPLayoutElement::UpdatePhase, by calling \ref
  13233. QCPLayoutElement::update on the main plot layout.
  13234. Here, the layout elements calculate their positions and margins, and prepare for the following
  13235. draw call.
  13236. */
  13237. void QCustomPlot::updateLayout()
  13238. {
  13239. // run through layout phases:
  13240. mPlotLayout->update(QCPLayoutElement::upPreparation);
  13241. mPlotLayout->update(QCPLayoutElement::upMargins);
  13242. mPlotLayout->update(QCPLayoutElement::upLayout);
  13243. Q_EMIT afterLayout();
  13244. }
  13245. /*! \internal
  13246. Draws the viewport background pixmap of the plot.
  13247. If a pixmap was provided via \ref setBackground, this function buffers the scaled version
  13248. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  13249. the viewport with the provided \a painter. The scaled version is buffered in
  13250. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  13251. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  13252. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  13253. set.
  13254. Note that this function does not draw a fill with the background brush
  13255. (\ref setBackground(const QBrush &brush)) beneath the pixmap.
  13256. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  13257. */
  13258. void QCustomPlot::drawBackground(QCPPainter *painter)
  13259. {
  13260. // Note: background color is handled in individual replot/save functions
  13261. // draw background pixmap (on top of fill, if brush specified):
  13262. if (!mBackgroundPixmap.isNull())
  13263. {
  13264. if (mBackgroundScaled)
  13265. {
  13266. // check whether mScaledBackground needs to be updated:
  13267. QSize scaledSize(mBackgroundPixmap.size());
  13268. scaledSize.scale(mViewport.size(), mBackgroundScaledMode);
  13269. if (mScaledBackgroundPixmap.size() != scaledSize)
  13270. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  13271. painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect());
  13272. } else
  13273. {
  13274. painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()));
  13275. }
  13276. }
  13277. }
  13278. /*! \internal
  13279. Goes through the layers and makes sure this QCustomPlot instance holds the correct number of
  13280. paint buffers and that they have the correct configuration (size, pixel ratio, etc.).
  13281. Allocations, reallocations and deletions of paint buffers are performed as necessary. It also
  13282. associates the paint buffers with the layers, so they draw themselves into the right buffer when
  13283. \ref QCPLayer::drawToPaintBuffer is called. This means it associates adjacent \ref
  13284. QCPLayer::lmLogical layers to a mutual paint buffer and creates dedicated paint buffers for
  13285. layers in \ref QCPLayer::lmBuffered mode.
  13286. This method uses \ref createPaintBuffer to create new paint buffers.
  13287. After this method, the paint buffers are empty (filled with \c Qt::transparent) and invalidated
  13288. (so an attempt to replot only a single buffered layer causes a full replot).
  13289. This method is called in every \ref replot call, prior to actually drawing the layers (into their
  13290. associated paint buffer). If the paint buffers don't need changing/reallocating, this method
  13291. basically leaves them alone and thus finishes very fast.
  13292. */
  13293. void QCustomPlot::setupPaintBuffers()
  13294. {
  13295. int bufferIndex = 0;
  13296. if (mPaintBuffers.isEmpty())
  13297. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  13298. for (int layerIndex = 0; layerIndex < mLayers.size(); ++layerIndex)
  13299. {
  13300. QCPLayer *layer = mLayers.at(layerIndex);
  13301. if (layer->mode() == QCPLayer::lmLogical)
  13302. {
  13303. layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
  13304. } else if (layer->mode() == QCPLayer::lmBuffered)
  13305. {
  13306. ++bufferIndex;
  13307. if (bufferIndex >= mPaintBuffers.size())
  13308. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  13309. layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
  13310. if (layerIndex < mLayers.size()-1 && mLayers.at(layerIndex+1)->mode() == QCPLayer::lmLogical) // not last layer, and next one is logical, so prepare another buffer for next layerables
  13311. {
  13312. ++bufferIndex;
  13313. if (bufferIndex >= mPaintBuffers.size())
  13314. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  13315. }
  13316. }
  13317. }
  13318. // remove unneeded buffers:
  13319. while (mPaintBuffers.size()-1 > bufferIndex)
  13320. mPaintBuffers.removeLast();
  13321. // resize buffers to viewport size and clear contents:
  13322. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  13323. {
  13324. buffer->setSize(viewport().size()); // won't do anything if already correct size
  13325. buffer->clear(Qt::transparent);
  13326. buffer->setInvalidated();
  13327. }
  13328. }
  13329. /*! \internal
  13330. This method is used by \ref setupPaintBuffers when it needs to create new paint buffers.
  13331. Depending on the current setting of \ref setOpenGl, and the current Qt version, different
  13332. backends (subclasses of \ref QCPAbstractPaintBuffer) are created, initialized with the proper
  13333. size and device pixel ratio, and returned.
  13334. */
  13335. QCPAbstractPaintBuffer *QCustomPlot::createPaintBuffer()
  13336. {
  13337. if (mOpenGl)
  13338. {
  13339. #if defined(QCP_OPENGL_FBO)
  13340. return new QCPPaintBufferGlFbo(viewport().size(), mBufferDevicePixelRatio, mGlContext, mGlPaintDevice);
  13341. #elif defined(QCP_OPENGL_PBUFFER)
  13342. return new QCPPaintBufferGlPbuffer(viewport().size(), mBufferDevicePixelRatio, mOpenGlMultisamples);
  13343. #else
  13344. qDebug() << Q_FUNC_INFO << "OpenGL enabled even though no support for it compiled in, this shouldn't have happened. Falling back to pixmap paint buffer.";
  13345. return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
  13346. #endif
  13347. } else
  13348. return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
  13349. }
  13350. /*!
  13351. This method returns whether any of the paint buffers held by this QCustomPlot instance are
  13352. invalidated.
  13353. If any buffer is invalidated, a partial replot (\ref QCPLayer::replot) is not allowed and always
  13354. causes a full replot (\ref QCustomPlot::replot) of all layers. This is the case when for example
  13355. the layer order has changed, new layers were added or removed, layer modes were changed (\ref
  13356. QCPLayer::setMode), or layerables were added or removed.
  13357. \see QCPAbstractPaintBuffer::setInvalidated
  13358. */
  13359. bool QCustomPlot::hasInvalidatedPaintBuffers()
  13360. {
  13361. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  13362. {
  13363. if (buffer->invalidated())
  13364. return true;
  13365. }
  13366. return false;
  13367. }
  13368. /*! \internal
  13369. When \ref setOpenGl is set to true, this method is used to initialize OpenGL (create a context,
  13370. surface, paint device).
  13371. Returns true on success.
  13372. If this method is successful, all paint buffers should be deleted and then reallocated by calling
  13373. \ref setupPaintBuffers, so the OpenGL-based paint buffer subclasses (\ref
  13374. QCPPaintBufferGlPbuffer, \ref QCPPaintBufferGlFbo) are used for subsequent replots.
  13375. \see freeOpenGl
  13376. */
  13377. bool QCustomPlot::setupOpenGl()
  13378. {
  13379. #ifdef QCP_OPENGL_FBO
  13380. freeOpenGl();
  13381. QSurfaceFormat proposedSurfaceFormat;
  13382. proposedSurfaceFormat.setSamples(mOpenGlMultisamples);
  13383. #ifdef QCP_OPENGL_OFFSCREENSURFACE
  13384. QOffscreenSurface *surface = new QOffscreenSurface;
  13385. #else
  13386. QWindow *surface = new QWindow;
  13387. surface->setSurfaceType(QSurface::OpenGLSurface);
  13388. #endif
  13389. surface->setFormat(proposedSurfaceFormat);
  13390. surface->create();
  13391. mGlSurface = QSharedPointer<QSurface>(surface);
  13392. mGlContext = QSharedPointer<QOpenGLContext>(new QOpenGLContext);
  13393. mGlContext->setFormat(mGlSurface->format());
  13394. if (!mGlContext->create())
  13395. {
  13396. qDebug() << Q_FUNC_INFO << "Failed to create OpenGL context";
  13397. mGlContext.clear();
  13398. mGlSurface.clear();
  13399. return false;
  13400. }
  13401. if (!mGlContext->makeCurrent(mGlSurface.data())) // context needs to be current to create paint device
  13402. {
  13403. qDebug() << Q_FUNC_INFO << "Failed to make opengl context current";
  13404. mGlContext.clear();
  13405. mGlSurface.clear();
  13406. return false;
  13407. }
  13408. if (!QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
  13409. {
  13410. qDebug() << Q_FUNC_INFO << "OpenGL of this system doesn't support frame buffer objects";
  13411. mGlContext.clear();
  13412. mGlSurface.clear();
  13413. return false;
  13414. }
  13415. mGlPaintDevice = QSharedPointer<QOpenGLPaintDevice>(new QOpenGLPaintDevice);
  13416. return true;
  13417. #elif defined(QCP_OPENGL_PBUFFER)
  13418. return QGLFormat::hasOpenGL();
  13419. #else
  13420. return false;
  13421. #endif
  13422. }
  13423. /*! \internal
  13424. When \ref setOpenGl is set to false, this method is used to deinitialize OpenGL (releases the
  13425. context and frees resources).
  13426. After OpenGL is disabled, all paint buffers should be deleted and then reallocated by calling
  13427. \ref setupPaintBuffers, so the standard software rendering paint buffer subclass (\ref
  13428. QCPPaintBufferPixmap) is used for subsequent replots.
  13429. \see setupOpenGl
  13430. */
  13431. void QCustomPlot::freeOpenGl()
  13432. {
  13433. #ifdef QCP_OPENGL_FBO
  13434. mGlPaintDevice.clear();
  13435. mGlContext.clear();
  13436. mGlSurface.clear();
  13437. #endif
  13438. }
  13439. /*! \internal
  13440. This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot
  13441. so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly.
  13442. */
  13443. void QCustomPlot::axisRemoved(QCPAxis *axis)
  13444. {
  13445. if (xAxis == axis)
  13446. xAxis = nullptr;
  13447. if (xAxis2 == axis)
  13448. xAxis2 = nullptr;
  13449. if (yAxis == axis)
  13450. yAxis = nullptr;
  13451. if (yAxis2 == axis)
  13452. yAxis2 = nullptr;
  13453. // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers
  13454. }
  13455. /*! \internal
  13456. This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so
  13457. it may clear its QCustomPlot::legend member accordingly.
  13458. */
  13459. void QCustomPlot::legendRemoved(QCPLegend *legend)
  13460. {
  13461. if (this->legend == legend)
  13462. this->legend = nullptr;
  13463. }
  13464. /*! \internal
  13465. This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
  13466. setSelectionRectMode is set to \ref QCP::srmSelect.
  13467. First, it determines which axis rect was the origin of the selection rect judging by the starting
  13468. point of the selection. Then it goes through the plottables (\ref QCPAbstractPlottable1D to be
  13469. precise) associated with that axis rect and finds the data points that are in \a rect. It does
  13470. this by querying their \ref QCPAbstractPlottable1D::selectTestRect method.
  13471. Then, the actual selection is done by calling the plottables' \ref
  13472. QCPAbstractPlottable::selectEvent, placing the found selected data points in the \a details
  13473. parameter as <tt>QVariant(\ref QCPDataSelection)</tt>. All plottables that weren't touched by \a
  13474. rect receive a \ref QCPAbstractPlottable::deselectEvent.
  13475. \see processRectZoom
  13476. */
  13477. void QCustomPlot::processRectSelection(QRect rect, QMouseEvent *event)
  13478. {
  13479. typedef QPair<QCPAbstractPlottable*, QCPDataSelection> SelectionCandidate;
  13480. typedef QMultiMap<int, SelectionCandidate> SelectionCandidates; // map key is number of selected data points, so we have selections sorted by size
  13481. bool selectionStateChanged = false;
  13482. if (mInteractions.testFlag(QCP::iSelectPlottables))
  13483. {
  13484. SelectionCandidates potentialSelections;
  13485. QRectF rectF(rect.normalized());
  13486. if (QCPAxisRect *affectedAxisRect = axisRectAt(rectF.topLeft()))
  13487. {
  13488. // determine plottables that were hit by the rect and thus are candidates for selection:
  13489. foreach (QCPAbstractPlottable *plottable, affectedAxisRect->plottables())
  13490. {
  13491. if (QCPPlottableInterface1D *plottableInterface = plottable->interface1D())
  13492. {
  13493. QCPDataSelection dataSel = plottableInterface->selectTestRect(rectF, true);
  13494. if (!dataSel.isEmpty())
  13495. potentialSelections.insert(dataSel.dataPointCount(), SelectionCandidate(plottable, dataSel));
  13496. }
  13497. }
  13498. if (!mInteractions.testFlag(QCP::iMultiSelect))
  13499. {
  13500. // only leave plottable with most selected points in map, since we will only select a single plottable:
  13501. if (!potentialSelections.isEmpty())
  13502. {
  13503. SelectionCandidates::iterator it = potentialSelections.begin();
  13504. while (it != std::prev(potentialSelections.end())) // erase all except last element
  13505. it = potentialSelections.erase(it);
  13506. }
  13507. }
  13508. bool additive = event->modifiers().testFlag(mMultiSelectModifier);
  13509. // deselect all other layerables if not additive selection:
  13510. if (!additive)
  13511. {
  13512. // emit deselection except to those plottables who will be selected afterwards:
  13513. foreach (QCPLayer *layer, mLayers)
  13514. {
  13515. foreach (QCPLayerable *layerable, layer->children())
  13516. {
  13517. if ((potentialSelections.isEmpty() || potentialSelections.constBegin()->first != layerable) && mInteractions.testFlag(layerable->selectionCategory()))
  13518. {
  13519. bool selChanged = false;
  13520. layerable->deselectEvent(&selChanged);
  13521. selectionStateChanged |= selChanged;
  13522. }
  13523. }
  13524. }
  13525. }
  13526. // go through selections in reverse (largest selection first) and emit select events:
  13527. SelectionCandidates::const_iterator it = potentialSelections.constEnd();
  13528. while (it != potentialSelections.constBegin())
  13529. {
  13530. --it;
  13531. if (mInteractions.testFlag(it.value().first->selectionCategory()))
  13532. {
  13533. bool selChanged = false;
  13534. it.value().first->selectEvent(event, additive, QVariant::fromValue(it.value().second), &selChanged);
  13535. selectionStateChanged |= selChanged;
  13536. }
  13537. }
  13538. }
  13539. }
  13540. if (selectionStateChanged)
  13541. {
  13542. Q_EMIT selectionChangedByUser();
  13543. replot(rpQueuedReplot);
  13544. } else if (mSelectionRect)
  13545. mSelectionRect->layer()->replot();
  13546. }
  13547. /*! \internal
  13548. This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
  13549. setSelectionRectMode is set to \ref QCP::srmZoom.
  13550. It determines which axis rect was the origin of the selection rect judging by the starting point
  13551. of the selection, and then zooms the axes defined via \ref QCPAxisRect::setRangeZoomAxes to the
  13552. provided \a rect (see \ref QCPAxisRect::zoom).
  13553. \see processRectSelection
  13554. */
  13555. void QCustomPlot::processRectZoom(QRect rect, QMouseEvent *event)
  13556. {
  13557. Q_UNUSED(event)
  13558. if (QCPAxisRect *axisRect = axisRectAt(rect.topLeft()))
  13559. {
  13560. QList<QCPAxis*> affectedAxes = QList<QCPAxis*>() << axisRect->rangeZoomAxes(Qt::Horizontal) << axisRect->rangeZoomAxes(Qt::Vertical);
  13561. affectedAxes.removeAll(static_cast<QCPAxis*>(nullptr));
  13562. axisRect->zoom(QRectF(rect), affectedAxes);
  13563. }
  13564. replot(rpQueuedReplot); // always replot to make selection rect disappear
  13565. }
  13566. /*! \internal
  13567. This method is called when a simple left mouse click was detected on the QCustomPlot surface.
  13568. It first determines the layerable that was hit by the click, and then calls its \ref
  13569. QCPLayerable::selectEvent. All other layerables receive a QCPLayerable::deselectEvent (unless the
  13570. multi-select modifier was pressed, see \ref setMultiSelectModifier).
  13571. In this method the hit layerable is determined a second time using \ref layerableAt (after the
  13572. one in \ref mousePressEvent), because we want \a onlySelectable set to true this time. This
  13573. implies that the mouse event grabber (mMouseEventLayerable) may be a different one from the
  13574. clicked layerable determined here. For example, if a non-selectable layerable is in front of a
  13575. selectable layerable at the click position, the front layerable will receive mouse events but the
  13576. selectable one in the back will receive the \ref QCPLayerable::selectEvent.
  13577. \see processRectSelection, QCPLayerable::selectTest
  13578. */
  13579. void QCustomPlot::processPointSelection(QMouseEvent *event)
  13580. {
  13581. QVariant details;
  13582. QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details);
  13583. bool selectionStateChanged = false;
  13584. bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier);
  13585. // deselect all other layerables if not additive selection:
  13586. if (!additive)
  13587. {
  13588. foreach (QCPLayer *layer, mLayers)
  13589. {
  13590. foreach (QCPLayerable *layerable, layer->children())
  13591. {
  13592. if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory()))
  13593. {
  13594. bool selChanged = false;
  13595. layerable->deselectEvent(&selChanged);
  13596. selectionStateChanged |= selChanged;
  13597. }
  13598. }
  13599. }
  13600. }
  13601. if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory()))
  13602. {
  13603. // a layerable was actually clicked, call its selectEvent:
  13604. bool selChanged = false;
  13605. clickedLayerable->selectEvent(event, additive, details, &selChanged);
  13606. selectionStateChanged |= selChanged;
  13607. }
  13608. if (selectionStateChanged)
  13609. {
  13610. Q_EMIT selectionChangedByUser();
  13611. replot(rpQueuedReplot);
  13612. }
  13613. }
  13614. /*! \internal
  13615. Registers the specified plottable with this QCustomPlot and, if \ref setAutoAddPlottableToLegend
  13616. is enabled, adds it to the legend (QCustomPlot::legend). QCustomPlot takes ownership of the
  13617. plottable.
  13618. Returns true on success, i.e. when \a plottable isn't already in this plot and the parent plot of
  13619. \a plottable is this QCustomPlot.
  13620. This method is called automatically in the QCPAbstractPlottable base class constructor.
  13621. */
  13622. bool QCustomPlot::registerPlottable(QCPAbstractPlottable *plottable)
  13623. {
  13624. if (mPlottables.contains(plottable))
  13625. {
  13626. qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable);
  13627. return false;
  13628. }
  13629. if (plottable->parentPlot() != this)
  13630. {
  13631. qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable);
  13632. return false;
  13633. }
  13634. mPlottables.append(plottable);
  13635. // possibly add plottable to legend:
  13636. if (mAutoAddPlottableToLegend)
  13637. plottable->addToLegend();
  13638. if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
  13639. plottable->setLayer(currentLayer());
  13640. return true;
  13641. }
  13642. /*! \internal
  13643. In order to maintain the simplified graph interface of QCustomPlot, this method is called by the
  13644. QCPGraph constructor to register itself with this QCustomPlot's internal graph list. Returns true
  13645. on success, i.e. if \a graph is valid and wasn't already registered with this QCustomPlot.
  13646. This graph specific registration happens in addition to the call to \ref registerPlottable by the
  13647. QCPAbstractPlottable base class.
  13648. */
  13649. bool QCustomPlot::registerGraph(QCPGraph *graph)
  13650. {
  13651. if (!graph)
  13652. {
  13653. qDebug() << Q_FUNC_INFO << "passed graph is zero";
  13654. return false;
  13655. }
  13656. if (mGraphs.contains(graph))
  13657. {
  13658. qDebug() << Q_FUNC_INFO << "graph already registered with this QCustomPlot";
  13659. return false;
  13660. }
  13661. mGraphs.append(graph);
  13662. return true;
  13663. }
  13664. /*! \internal
  13665. Registers the specified item with this QCustomPlot. QCustomPlot takes ownership of the item.
  13666. Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
  13667. item is this QCustomPlot.
  13668. This method is called automatically in the QCPAbstractItem base class constructor.
  13669. */
  13670. bool QCustomPlot::registerItem(QCPAbstractItem *item)
  13671. {
  13672. if (mItems.contains(item))
  13673. {
  13674. qDebug() << Q_FUNC_INFO << "item already added to this QCustomPlot:" << reinterpret_cast<quintptr>(item);
  13675. return false;
  13676. }
  13677. if (item->parentPlot() != this)
  13678. {
  13679. qDebug() << Q_FUNC_INFO << "item not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item);
  13680. return false;
  13681. }
  13682. mItems.append(item);
  13683. if (!item->layer()) // usually the layer is already set in the constructor of the item (via QCPLayerable constructor)
  13684. item->setLayer(currentLayer());
  13685. return true;
  13686. }
  13687. /*! \internal
  13688. Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called
  13689. after every operation that changes the layer indices, like layer removal, layer creation, layer
  13690. moving.
  13691. */
  13692. void QCustomPlot::updateLayerIndices() const
  13693. {
  13694. for (int i=0; i<mLayers.size(); ++i)
  13695. mLayers.at(i)->mIndex = i;
  13696. }
  13697. /*! \internal
  13698. Returns the top-most layerable at pixel position \a pos. If \a onlySelectable is set to true,
  13699. only those layerables that are selectable will be considered. (Layerable subclasses communicate
  13700. their selectability via the QCPLayerable::selectTest method, by returning -1.)
  13701. \a selectionDetails is an output parameter that contains selection specifics of the affected
  13702. layerable. This is useful if the respective layerable shall be given a subsequent
  13703. QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
  13704. information about which part of the layerable was hit, in multi-part layerables (e.g.
  13705. QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
  13706. QCPDataSelection instance with the single data point which is closest to \a pos.
  13707. \see layerableListAt, layoutElementAt, axisRectAt
  13708. */
  13709. QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const
  13710. {
  13711. QList<QVariant> details;
  13712. QList<QCPLayerable*> candidates = layerableListAt(pos, onlySelectable, selectionDetails ? &details : nullptr);
  13713. if (selectionDetails && !details.isEmpty())
  13714. *selectionDetails = details.first();
  13715. if (!candidates.isEmpty())
  13716. return candidates.first();
  13717. else
  13718. return nullptr;
  13719. }
  13720. /*! \internal
  13721. Returns the layerables at pixel position \a pos. If \a onlySelectable is set to true, only those
  13722. layerables that are selectable will be considered. (Layerable subclasses communicate their
  13723. selectability via the QCPLayerable::selectTest method, by returning -1.)
  13724. The returned list is sorted by the layerable/drawing order such that the layerable that appears
  13725. on top in the plot is at index 0 of the returned list. If you only need to know the top
  13726. layerable, rather use \ref layerableAt.
  13727. \a selectionDetails is an output parameter that contains selection specifics of the affected
  13728. layerable. This is useful if the respective layerable shall be given a subsequent
  13729. QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
  13730. information about which part of the layerable was hit, in multi-part layerables (e.g.
  13731. QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
  13732. QCPDataSelection instance with the single data point which is closest to \a pos.
  13733. \see layerableAt, layoutElementAt, axisRectAt
  13734. */
  13735. QList<QCPLayerable*> QCustomPlot::layerableListAt(const QPointF &pos, bool onlySelectable, QList<QVariant> *selectionDetails) const
  13736. {
  13737. QList<QCPLayerable*> result;
  13738. for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex)
  13739. {
  13740. const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
  13741. for (int i=layerables.size()-1; i>=0; --i)
  13742. {
  13743. if (!layerables.at(i)->realVisibility())
  13744. continue;
  13745. QVariant details;
  13746. double dist = layerables.at(i)->selectTest(pos, onlySelectable, selectionDetails ? &details : nullptr);
  13747. if (dist >= 0 && dist < selectionTolerance())
  13748. {
  13749. result.append(layerables.at(i));
  13750. if (selectionDetails)
  13751. selectionDetails->append(details);
  13752. }
  13753. }
  13754. }
  13755. return result;
  13756. }
  13757. /*!
  13758. Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is
  13759. sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead
  13760. to a full resolution file with width 200.) If the \a format supports compression, \a quality may
  13761. be between 0 and 100 to control it.
  13762. Returns true on success. If this function fails, most likely the given \a format isn't supported
  13763. by the system, see Qt docs about QImageWriter::supportedImageFormats().
  13764. The \a resolution will be written to the image file header (if the file format supports this) and
  13765. has no direct consequence for the quality or the pixel size. However, if opening the image with a
  13766. tool which respects the metadata, it will be able to scale the image to match either a given size
  13767. in real units of length (inch, centimeters, etc.), or the target display DPI. You can specify in
  13768. which units \a resolution is given, by setting \a resolutionUnit. The \a resolution is converted
  13769. to the format's expected resolution unit internally.
  13770. \see saveBmp, saveJpg, savePng, savePdf
  13771. */
  13772. bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  13773. {
  13774. QImage buffer = toPixmap(width, height, scale).toImage();
  13775. int dotsPerMeter = 0;
  13776. switch (resolutionUnit)
  13777. {
  13778. case QCP::ruDotsPerMeter: dotsPerMeter = resolution; break;
  13779. case QCP::ruDotsPerCentimeter: dotsPerMeter = resolution*100; break;
  13780. case QCP::ruDotsPerInch: dotsPerMeter = int(resolution/0.0254); break;
  13781. }
  13782. buffer.setDotsPerMeterX(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
  13783. buffer.setDotsPerMeterY(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
  13784. if (!buffer.isNull())
  13785. return buffer.save(fileName, format, quality);
  13786. else
  13787. return false;
  13788. }
  13789. /*!
  13790. Renders the plot to a pixmap and returns it.
  13791. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and
  13792. scale 2.0 lead to a full resolution pixmap with width 200.)
  13793. \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf
  13794. */
  13795. QPixmap QCustomPlot::toPixmap(int width, int height, double scale)
  13796. {
  13797. // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too.
  13798. int newWidth, newHeight;
  13799. if (width == 0 || height == 0)
  13800. {
  13801. newWidth = this->width();
  13802. newHeight = this->height();
  13803. } else
  13804. {
  13805. newWidth = width;
  13806. newHeight = height;
  13807. }
  13808. int scaledWidth = qRound(scale*newWidth);
  13809. int scaledHeight = qRound(scale*newHeight);
  13810. QPixmap result(scaledWidth, scaledHeight);
  13811. result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later
  13812. QCPPainter painter;
  13813. painter.begin(&result);
  13814. if (painter.isActive())
  13815. {
  13816. QRect oldViewport = viewport();
  13817. setViewport(QRect(0, 0, newWidth, newHeight));
  13818. painter.setMode(QCPPainter::pmNoCaching);
  13819. if (!qFuzzyCompare(scale, 1.0))
  13820. {
  13821. if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales
  13822. painter.setMode(QCPPainter::pmNonCosmetic);
  13823. painter.scale(scale, scale);
  13824. }
  13825. if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill
  13826. painter.fillRect(mViewport, mBackgroundBrush);
  13827. draw(&painter);
  13828. setViewport(oldViewport);
  13829. painter.end();
  13830. } else // might happen if pixmap has width or height zero
  13831. {
  13832. qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap";
  13833. return QPixmap();
  13834. }
  13835. return result;
  13836. }
  13837. /*!
  13838. Renders the plot using the passed \a painter.
  13839. The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will
  13840. appear scaled accordingly.
  13841. \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter
  13842. on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with
  13843. the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter.
  13844. \see toPixmap
  13845. */
  13846. void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
  13847. {
  13848. // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too.
  13849. int newWidth, newHeight;
  13850. if (width == 0 || height == 0)
  13851. {
  13852. newWidth = this->width();
  13853. newHeight = this->height();
  13854. } else
  13855. {
  13856. newWidth = width;
  13857. newHeight = height;
  13858. }
  13859. if (painter->isActive())
  13860. {
  13861. QRect oldViewport = viewport();
  13862. setViewport(QRect(0, 0, newWidth, newHeight));
  13863. painter->setMode(QCPPainter::pmNoCaching);
  13864. if (mBackgroundBrush.style() != Qt::NoBrush) // unlike in toPixmap, we can't do QPixmap::fill for Qt::SolidPattern brush style, so we also draw solid fills with fillRect here
  13865. painter->fillRect(mViewport, mBackgroundBrush);
  13866. draw(painter);
  13867. setViewport(oldViewport);
  13868. } else
  13869. qDebug() << Q_FUNC_INFO << "Passed painter is not active";
  13870. }
  13871. /* end of 'src/core.cpp' */
  13872. /* including file 'src/colorgradient.cpp' */
  13873. /* modified 2021-03-29T02:30:44, size 25278 */
  13874. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13875. //////////////////// QCPColorGradient
  13876. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13877. /*! \class QCPColorGradient
  13878. \brief Defines a color gradient for use with e.g. \ref QCPColorMap
  13879. This class describes a color gradient which can be used to encode data with color. For example,
  13880. QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which
  13881. take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color)
  13882. with a \a position from 0 to 1. In between these defined color positions, the
  13883. color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation.
  13884. Alternatively, load one of the preset color gradients shown in the image below, with \ref
  13885. loadPreset, or by directly specifying the preset in the constructor.
  13886. Apart from red, green and blue components, the gradient also interpolates the alpha values of the
  13887. configured color stops. This allows to display some portions of the data range as transparent in
  13888. the plot.
  13889. How NaN values are interpreted can be configured with \ref setNanHandling.
  13890. \image html QCPColorGradient.png
  13891. The constructor \ref QCPColorGradient(GradientPreset preset) allows directly converting a \ref
  13892. GradientPreset to a QCPColorGradient. This means that you can directly pass \ref GradientPreset
  13893. to all the \a setGradient methods, e.g.:
  13894. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient
  13895. The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the
  13896. color gradient shall be applied periodically (wrapping around) to data values that lie outside
  13897. the data range specified on the plottable instance can be controlled with \ref setPeriodic.
  13898. */
  13899. /*!
  13900. Constructs a new, empty QCPColorGradient with no predefined color stops. You can add own color
  13901. stops with \ref setColorStopAt.
  13902. The color level count is initialized to 350.
  13903. */
  13904. QCPColorGradient::QCPColorGradient() :
  13905. mLevelCount(350),
  13906. mColorInterpolation(ciRGB),
  13907. mNanHandling(nhNone),
  13908. mNanColor(Qt::black),
  13909. mPeriodic(false),
  13910. mColorBufferInvalidated(true)
  13911. {
  13912. mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
  13913. }
  13914. /*!
  13915. Constructs a new QCPColorGradient initialized with the colors and color interpolation according
  13916. to \a preset.
  13917. The color level count is initialized to 350.
  13918. */
  13919. QCPColorGradient::QCPColorGradient(GradientPreset preset) :
  13920. mLevelCount(350),
  13921. mColorInterpolation(ciRGB),
  13922. mNanHandling(nhNone),
  13923. mNanColor(Qt::black),
  13924. mPeriodic(false),
  13925. mColorBufferInvalidated(true)
  13926. {
  13927. mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
  13928. loadPreset(preset);
  13929. }
  13930. /* undocumented operator */
  13931. bool QCPColorGradient::operator==(const QCPColorGradient &other) const
  13932. {
  13933. return ((other.mLevelCount == this->mLevelCount) &&
  13934. (other.mColorInterpolation == this->mColorInterpolation) &&
  13935. (other.mNanHandling == this ->mNanHandling) &&
  13936. (other.mNanColor == this->mNanColor) &&
  13937. (other.mPeriodic == this->mPeriodic) &&
  13938. (other.mColorStops == this->mColorStops));
  13939. }
  13940. /*!
  13941. Sets the number of discretization levels of the color gradient to \a n. The default is 350 which
  13942. is typically enough to create a smooth appearance. The minimum number of levels is 2.
  13943. \image html QCPColorGradient-levelcount.png
  13944. */
  13945. void QCPColorGradient::setLevelCount(int n)
  13946. {
  13947. if (n < 2)
  13948. {
  13949. qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n;
  13950. n = 2;
  13951. }
  13952. if (n != mLevelCount)
  13953. {
  13954. mLevelCount = n;
  13955. mColorBufferInvalidated = true;
  13956. }
  13957. }
  13958. /*!
  13959. Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the
  13960. colors are the values of the passed QMap \a colorStops. In between these color stops, the color
  13961. is interpolated according to \ref setColorInterpolation.
  13962. A more convenient way to create a custom gradient may be to clear all color stops with \ref
  13963. clearColorStops (or creating a new, empty QCPColorGradient) and then adding them one by one with
  13964. \ref setColorStopAt.
  13965. \see clearColorStops
  13966. */
  13967. void QCPColorGradient::setColorStops(const QMap<double, QColor> &colorStops)
  13968. {
  13969. mColorStops = colorStops;
  13970. mColorBufferInvalidated = true;
  13971. }
  13972. /*!
  13973. Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between
  13974. these color stops, the color is interpolated according to \ref setColorInterpolation.
  13975. \see setColorStops, clearColorStops
  13976. */
  13977. void QCPColorGradient::setColorStopAt(double position, const QColor &color)
  13978. {
  13979. mColorStops.insert(position, color);
  13980. mColorBufferInvalidated = true;
  13981. }
  13982. /*!
  13983. Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be
  13984. interpolated linearly in RGB or in HSV color space.
  13985. For example, a sweep in RGB space from red to green will have a muddy brown intermediate color,
  13986. whereas in HSV space the intermediate color is yellow.
  13987. */
  13988. void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation)
  13989. {
  13990. if (interpolation != mColorInterpolation)
  13991. {
  13992. mColorInterpolation = interpolation;
  13993. mColorBufferInvalidated = true;
  13994. }
  13995. }
  13996. /*!
  13997. Sets how NaNs in the data are displayed in the plot.
  13998. \see setNanColor
  13999. */
  14000. void QCPColorGradient::setNanHandling(QCPColorGradient::NanHandling handling)
  14001. {
  14002. mNanHandling = handling;
  14003. }
  14004. /*!
  14005. Sets the color that NaN data is represented by, if \ref setNanHandling is set
  14006. to ref nhNanColor.
  14007. \see setNanHandling
  14008. */
  14009. void QCPColorGradient::setNanColor(const QColor &color)
  14010. {
  14011. mNanColor = color;
  14012. }
  14013. /*!
  14014. Sets whether data points that are outside the configured data range (e.g. \ref
  14015. QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether
  14016. they all have the same color, corresponding to the respective gradient boundary color.
  14017. \image html QCPColorGradient-periodic.png
  14018. As shown in the image above, gradients that have the same start and end color are especially
  14019. suitable for a periodic gradient mapping, since they produce smooth color transitions throughout
  14020. the color map. A preset that has this property is \ref gpHues.
  14021. In practice, using periodic color gradients makes sense when the data corresponds to a periodic
  14022. dimension, such as an angle or a phase. If this is not the case, the color encoding might become
  14023. ambiguous, because multiple different data values are shown as the same color.
  14024. */
  14025. void QCPColorGradient::setPeriodic(bool enabled)
  14026. {
  14027. mPeriodic = enabled;
  14028. }
  14029. /*! \overload
  14030. This method is used to quickly convert a \a data array to colors. The colors will be output in
  14031. the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this
  14032. function. The data range that shall be used for mapping the data value to the gradient is passed
  14033. in \a range. \a logarithmic indicates whether the data values shall be mapped to colors
  14034. logarithmically.
  14035. if \a data actually contains 2D-data linearized via <tt>[row*columnCount + column]</tt>, you can
  14036. set \a dataIndexFactor to <tt>columnCount</tt> to convert a column instead of a row of the data
  14037. array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data
  14038. is addressed <tt>data[i*dataIndexFactor]</tt>.
  14039. Use the overloaded method to additionally provide alpha map data.
  14040. The QRgb values that are placed in \a scanLine have their r, g, and b components premultiplied
  14041. with alpha (see QImage::Format_ARGB32_Premultiplied).
  14042. */
  14043. void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
  14044. {
  14045. // If you change something here, make sure to also adapt color() and the other colorize() overload
  14046. if (!data)
  14047. {
  14048. qDebug() << Q_FUNC_INFO << "null pointer given as data";
  14049. return;
  14050. }
  14051. if (!scanLine)
  14052. {
  14053. qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
  14054. return;
  14055. }
  14056. if (mColorBufferInvalidated)
  14057. updateColorBuffer();
  14058. const bool skipNanCheck = mNanHandling == nhNone;
  14059. const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
  14060. for (int i=0; i<n; ++i)
  14061. {
  14062. const double value = data[dataIndexFactor*i];
  14063. if (skipNanCheck || !std::isnan(value))
  14064. {
  14065. int index = int((!logarithmic ? value-range.lower : qLn(value/range.lower)) * posToIndexFactor);
  14066. if (!mPeriodic)
  14067. {
  14068. index = qBound(0, index, mLevelCount-1);
  14069. } else
  14070. {
  14071. index %= mLevelCount;
  14072. if (index < 0)
  14073. index += mLevelCount;
  14074. }
  14075. scanLine[i] = mColorBuffer.at(index);
  14076. } else
  14077. {
  14078. switch(mNanHandling)
  14079. {
  14080. case nhLowestColor: scanLine[i] = mColorBuffer.first(); break;
  14081. case nhHighestColor: scanLine[i] = mColorBuffer.last(); break;
  14082. case nhTransparent: scanLine[i] = qRgba(0, 0, 0, 0); break;
  14083. case nhNanColor: scanLine[i] = mNanColor.rgba(); break;
  14084. case nhNone: break; // shouldn't happen
  14085. }
  14086. }
  14087. }
  14088. }
  14089. /*! \overload
  14090. Additionally to the other overload of \ref colorize, this method takes the array \a alpha, which
  14091. has the same size and structure as \a data and encodes the alpha information per data point.
  14092. The QRgb values that are placed in \a scanLine have their r, g and b components premultiplied
  14093. with alpha (see QImage::Format_ARGB32_Premultiplied).
  14094. */
  14095. void QCPColorGradient::colorize(const double *data, const unsigned char *alpha, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
  14096. {
  14097. // If you change something here, make sure to also adapt color() and the other colorize() overload
  14098. if (!data)
  14099. {
  14100. qDebug() << Q_FUNC_INFO << "null pointer given as data";
  14101. return;
  14102. }
  14103. if (!alpha)
  14104. {
  14105. qDebug() << Q_FUNC_INFO << "null pointer given as alpha";
  14106. return;
  14107. }
  14108. if (!scanLine)
  14109. {
  14110. qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
  14111. return;
  14112. }
  14113. if (mColorBufferInvalidated)
  14114. updateColorBuffer();
  14115. const bool skipNanCheck = mNanHandling == nhNone;
  14116. const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
  14117. for (int i=0; i<n; ++i)
  14118. {
  14119. const double value = data[dataIndexFactor*i];
  14120. if (skipNanCheck || !std::isnan(value))
  14121. {
  14122. int index = int((!logarithmic ? value-range.lower : qLn(value/range.lower)) * posToIndexFactor);
  14123. if (!mPeriodic)
  14124. {
  14125. index = qBound(0, index, mLevelCount-1);
  14126. } else
  14127. {
  14128. index %= mLevelCount;
  14129. if (index < 0)
  14130. index += mLevelCount;
  14131. }
  14132. if (alpha[dataIndexFactor*i] == 255)
  14133. {
  14134. scanLine[i] = mColorBuffer.at(index);
  14135. } else
  14136. {
  14137. const QRgb rgb = mColorBuffer.at(index);
  14138. const float alphaF = alpha[dataIndexFactor*i]/255.0f;
  14139. scanLine[i] = qRgba(int(qRed(rgb)*alphaF), int(qGreen(rgb)*alphaF), int(qBlue(rgb)*alphaF), int(qAlpha(rgb)*alphaF)); // also multiply r,g,b with alpha, to conform to Format_ARGB32_Premultiplied
  14140. }
  14141. } else
  14142. {
  14143. switch(mNanHandling)
  14144. {
  14145. case nhLowestColor: scanLine[i] = mColorBuffer.first(); break;
  14146. case nhHighestColor: scanLine[i] = mColorBuffer.last(); break;
  14147. case nhTransparent: scanLine[i] = qRgba(0, 0, 0, 0); break;
  14148. case nhNanColor: scanLine[i] = mNanColor.rgba(); break;
  14149. case nhNone: break; // shouldn't happen
  14150. }
  14151. }
  14152. }
  14153. }
  14154. /*! \internal
  14155. This method is used to colorize a single data value given in \a position, to colors. The data
  14156. range that shall be used for mapping the data value to the gradient is passed in \a range. \a
  14157. logarithmic indicates whether the data value shall be mapped to a color logarithmically.
  14158. If an entire array of data values shall be converted, rather use \ref colorize, for better
  14159. performance.
  14160. The returned QRgb has its r, g and b components premultiplied with alpha (see
  14161. QImage::Format_ARGB32_Premultiplied).
  14162. */
  14163. QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic)
  14164. {
  14165. // If you change something here, make sure to also adapt ::colorize()
  14166. if (mColorBufferInvalidated)
  14167. updateColorBuffer();
  14168. const bool skipNanCheck = mNanHandling == nhNone;
  14169. if (!skipNanCheck && std::isnan(position))
  14170. {
  14171. switch(mNanHandling)
  14172. {
  14173. case nhLowestColor: return mColorBuffer.first();
  14174. case nhHighestColor: return mColorBuffer.last();
  14175. case nhTransparent: return qRgba(0, 0, 0, 0);
  14176. case nhNanColor: return mNanColor.rgba();
  14177. case nhNone: return qRgba(0, 0, 0, 0); // shouldn't happen
  14178. }
  14179. }
  14180. const double posToIndexFactor = !logarithmic ? (mLevelCount-1)/range.size() : (mLevelCount-1)/qLn(range.upper/range.lower);
  14181. int index = int((!logarithmic ? position-range.lower : qLn(position/range.lower)) * posToIndexFactor);
  14182. if (!mPeriodic)
  14183. {
  14184. index = qBound(0, index, mLevelCount-1);
  14185. } else
  14186. {
  14187. index %= mLevelCount;
  14188. if (index < 0)
  14189. index += mLevelCount;
  14190. }
  14191. return mColorBuffer.at(index);
  14192. }
  14193. /*!
  14194. Clears the current color stops and loads the specified \a preset. A preset consists of predefined
  14195. color stops and the corresponding color interpolation method.
  14196. The available presets are:
  14197. \image html QCPColorGradient.png
  14198. */
  14199. void QCPColorGradient::loadPreset(GradientPreset preset)
  14200. {
  14201. clearColorStops();
  14202. switch (preset)
  14203. {
  14204. case gpGrayscale:
  14205. setColorInterpolation(ciRGB);
  14206. setColorStopAt(0, Qt::black);
  14207. setColorStopAt(1, Qt::white);
  14208. break;
  14209. case gpHot:
  14210. setColorInterpolation(ciRGB);
  14211. setColorStopAt(0, QColor(50, 0, 0));
  14212. setColorStopAt(0.2, QColor(180, 10, 0));
  14213. setColorStopAt(0.4, QColor(245, 50, 0));
  14214. setColorStopAt(0.6, QColor(255, 150, 10));
  14215. setColorStopAt(0.8, QColor(255, 255, 50));
  14216. setColorStopAt(1, QColor(255, 255, 255));
  14217. break;
  14218. case gpCold:
  14219. setColorInterpolation(ciRGB);
  14220. setColorStopAt(0, QColor(0, 0, 50));
  14221. setColorStopAt(0.2, QColor(0, 10, 180));
  14222. setColorStopAt(0.4, QColor(0, 50, 245));
  14223. setColorStopAt(0.6, QColor(10, 150, 255));
  14224. setColorStopAt(0.8, QColor(50, 255, 255));
  14225. setColorStopAt(1, QColor(255, 255, 255));
  14226. break;
  14227. case gpNight:
  14228. setColorInterpolation(ciHSV);
  14229. setColorStopAt(0, QColor(10, 20, 30));
  14230. setColorStopAt(1, QColor(250, 255, 250));
  14231. break;
  14232. case gpCandy:
  14233. setColorInterpolation(ciHSV);
  14234. setColorStopAt(0, QColor(0, 0, 255));
  14235. setColorStopAt(1, QColor(255, 250, 250));
  14236. break;
  14237. case gpGeography:
  14238. setColorInterpolation(ciRGB);
  14239. setColorStopAt(0, QColor(70, 170, 210));
  14240. setColorStopAt(0.20, QColor(90, 160, 180));
  14241. setColorStopAt(0.25, QColor(45, 130, 175));
  14242. setColorStopAt(0.30, QColor(100, 140, 125));
  14243. setColorStopAt(0.5, QColor(100, 140, 100));
  14244. setColorStopAt(0.6, QColor(130, 145, 120));
  14245. setColorStopAt(0.7, QColor(140, 130, 120));
  14246. setColorStopAt(0.9, QColor(180, 190, 190));
  14247. setColorStopAt(1, QColor(210, 210, 230));
  14248. break;
  14249. case gpIon:
  14250. setColorInterpolation(ciHSV);
  14251. setColorStopAt(0, QColor(50, 10, 10));
  14252. setColorStopAt(0.45, QColor(0, 0, 255));
  14253. setColorStopAt(0.8, QColor(0, 255, 255));
  14254. setColorStopAt(1, QColor(0, 255, 0));
  14255. break;
  14256. case gpThermal:
  14257. setColorInterpolation(ciRGB);
  14258. setColorStopAt(0, QColor(0, 0, 50));
  14259. setColorStopAt(0.15, QColor(20, 0, 120));
  14260. setColorStopAt(0.33, QColor(200, 30, 140));
  14261. setColorStopAt(0.6, QColor(255, 100, 0));
  14262. setColorStopAt(0.85, QColor(255, 255, 40));
  14263. setColorStopAt(1, QColor(255, 255, 255));
  14264. break;
  14265. case gpPolar:
  14266. setColorInterpolation(ciRGB);
  14267. setColorStopAt(0, QColor(50, 255, 255));
  14268. setColorStopAt(0.18, QColor(10, 70, 255));
  14269. setColorStopAt(0.28, QColor(10, 10, 190));
  14270. setColorStopAt(0.5, QColor(0, 0, 0));
  14271. setColorStopAt(0.72, QColor(190, 10, 10));
  14272. setColorStopAt(0.82, QColor(255, 70, 10));
  14273. setColorStopAt(1, QColor(255, 255, 50));
  14274. break;
  14275. case gpSpectrum:
  14276. setColorInterpolation(ciHSV);
  14277. setColorStopAt(0, QColor(50, 0, 50));
  14278. setColorStopAt(0.15, QColor(0, 0, 255));
  14279. setColorStopAt(0.35, QColor(0, 255, 255));
  14280. setColorStopAt(0.6, QColor(255, 255, 0));
  14281. setColorStopAt(0.75, QColor(255, 30, 0));
  14282. setColorStopAt(1, QColor(50, 0, 0));
  14283. break;
  14284. case gpJet:
  14285. setColorInterpolation(ciRGB);
  14286. setColorStopAt(0, QColor(0, 0, 100));
  14287. setColorStopAt(0.15, QColor(0, 50, 255));
  14288. setColorStopAt(0.35, QColor(0, 255, 255));
  14289. setColorStopAt(0.65, QColor(255, 255, 0));
  14290. setColorStopAt(0.85, QColor(255, 30, 0));
  14291. setColorStopAt(1, QColor(100, 0, 0));
  14292. break;
  14293. case gpHues:
  14294. setColorInterpolation(ciHSV);
  14295. setColorStopAt(0, QColor(255, 0, 0));
  14296. setColorStopAt(1.0/3.0, QColor(0, 0, 255));
  14297. setColorStopAt(2.0/3.0, QColor(0, 255, 0));
  14298. setColorStopAt(1, QColor(255, 0, 0));
  14299. break;
  14300. }
  14301. }
  14302. /*!
  14303. Clears all color stops.
  14304. \see setColorStops, setColorStopAt
  14305. */
  14306. void QCPColorGradient::clearColorStops()
  14307. {
  14308. mColorStops.clear();
  14309. mColorBufferInvalidated = true;
  14310. }
  14311. /*!
  14312. Returns an inverted gradient. The inverted gradient has all properties as this \ref
  14313. QCPColorGradient, but the order of the color stops is inverted.
  14314. \see setColorStops, setColorStopAt
  14315. */
  14316. QCPColorGradient QCPColorGradient::inverted() const
  14317. {
  14318. QCPColorGradient result(*this);
  14319. result.clearColorStops();
  14320. for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
  14321. result.setColorStopAt(1.0-it.key(), it.value());
  14322. return result;
  14323. }
  14324. /*! \internal
  14325. Returns true if the color gradient uses transparency, i.e. if any of the configured color stops
  14326. has an alpha value below 255.
  14327. */
  14328. bool QCPColorGradient::stopsUseAlpha() const
  14329. {
  14330. for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
  14331. {
  14332. if (it.value().alpha() < 255)
  14333. return true;
  14334. }
  14335. return false;
  14336. }
  14337. /*! \internal
  14338. Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly
  14339. convert positions to colors. This is where the interpolation between color stops is calculated.
  14340. */
  14341. void QCPColorGradient::updateColorBuffer()
  14342. {
  14343. if (mColorBuffer.size() != mLevelCount)
  14344. mColorBuffer.resize(mLevelCount);
  14345. if (mColorStops.size() > 1)
  14346. {
  14347. double indexToPosFactor = 1.0/double(mLevelCount-1);
  14348. const bool useAlpha = stopsUseAlpha();
  14349. for (int i=0; i<mLevelCount; ++i)
  14350. {
  14351. double position = i*indexToPosFactor;
  14352. QMap<double, QColor>::const_iterator it = mColorStops.lowerBound(position);
  14353. if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop
  14354. {
  14355. if (useAlpha)
  14356. {
  14357. const QColor col = std::prev(it).value();
  14358. const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied
  14359. mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier),
  14360. int(col.green()*alphaPremultiplier),
  14361. int(col.blue()*alphaPremultiplier),
  14362. col.alpha());
  14363. } else
  14364. mColorBuffer[i] = std::prev(it).value().rgba();
  14365. } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop
  14366. {
  14367. if (useAlpha)
  14368. {
  14369. const QColor &col = it.value();
  14370. const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied
  14371. mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier),
  14372. int(col.green()*alphaPremultiplier),
  14373. int(col.blue()*alphaPremultiplier),
  14374. col.alpha());
  14375. } else
  14376. mColorBuffer[i] = it.value().rgba();
  14377. } else // position is in between stops (or on an intermediate stop), interpolate color
  14378. {
  14379. QMap<double, QColor>::const_iterator high = it;
  14380. QMap<double, QColor>::const_iterator low = std::prev(it);
  14381. double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1
  14382. switch (mColorInterpolation)
  14383. {
  14384. case ciRGB:
  14385. {
  14386. if (useAlpha)
  14387. {
  14388. const int alpha = int((1-t)*low.value().alpha() + t*high.value().alpha());
  14389. const double alphaPremultiplier = alpha/255.0; // since we use QImage::Format_ARGB32_Premultiplied
  14390. mColorBuffer[i] = qRgba(int( ((1-t)*low.value().red() + t*high.value().red())*alphaPremultiplier ),
  14391. int( ((1-t)*low.value().green() + t*high.value().green())*alphaPremultiplier ),
  14392. int( ((1-t)*low.value().blue() + t*high.value().blue())*alphaPremultiplier ),
  14393. alpha);
  14394. } else
  14395. {
  14396. mColorBuffer[i] = qRgb(int( ((1-t)*low.value().red() + t*high.value().red()) ),
  14397. int( ((1-t)*low.value().green() + t*high.value().green()) ),
  14398. int( ((1-t)*low.value().blue() + t*high.value().blue())) );
  14399. }
  14400. break;
  14401. }
  14402. case ciHSV:
  14403. {
  14404. QColor lowHsv = low.value().toHsv();
  14405. QColor highHsv = high.value().toHsv();
  14406. double hue = 0;
  14407. double hueDiff = highHsv.hueF()-lowHsv.hueF();
  14408. if (hueDiff > 0.5)
  14409. hue = lowHsv.hueF() - t*(1.0-hueDiff);
  14410. else if (hueDiff < -0.5)
  14411. hue = lowHsv.hueF() + t*(1.0+hueDiff);
  14412. else
  14413. hue = lowHsv.hueF() + t*hueDiff;
  14414. if (hue < 0) hue += 1.0;
  14415. else if (hue >= 1.0) hue -= 1.0;
  14416. if (useAlpha)
  14417. {
  14418. const QRgb rgb = QColor::fromHsvF(hue,
  14419. (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
  14420. (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
  14421. const double alpha = (1-t)*lowHsv.alphaF() + t*highHsv.alphaF();
  14422. mColorBuffer[i] = qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha));
  14423. }
  14424. else
  14425. {
  14426. mColorBuffer[i] = QColor::fromHsvF(hue,
  14427. (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
  14428. (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
  14429. }
  14430. break;
  14431. }
  14432. }
  14433. }
  14434. }
  14435. } else if (mColorStops.size() == 1)
  14436. {
  14437. const QRgb rgb = mColorStops.constBegin().value().rgb();
  14438. const double alpha = mColorStops.constBegin().value().alphaF();
  14439. mColorBuffer.fill(qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha)));
  14440. } else // mColorStops is empty, fill color buffer with black
  14441. {
  14442. mColorBuffer.fill(qRgb(0, 0, 0));
  14443. }
  14444. mColorBufferInvalidated = false;
  14445. }
  14446. /* end of 'src/colorgradient.cpp' */
  14447. /* including file 'src/selectiondecorator-bracket.cpp' */
  14448. /* modified 2021-03-29T02:30:44, size 12308 */
  14449. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14450. //////////////////// QCPSelectionDecoratorBracket
  14451. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14452. /*! \class QCPSelectionDecoratorBracket
  14453. \brief A selection decorator which draws brackets around each selected data segment
  14454. Additionally to the regular highlighting of selected segments via color, fill and scatter style,
  14455. this \ref QCPSelectionDecorator subclass draws markers at the begin and end of each selected data
  14456. segment of the plottable.
  14457. The shape of the markers can be controlled with \ref setBracketStyle, \ref setBracketWidth and
  14458. \ref setBracketHeight. The color/fill can be controlled with \ref setBracketPen and \ref
  14459. setBracketBrush.
  14460. To introduce custom bracket styles, it is only necessary to sublcass \ref
  14461. QCPSelectionDecoratorBracket and reimplement \ref drawBracket. The rest will be managed by the
  14462. base class.
  14463. */
  14464. /*!
  14465. Creates a new QCPSelectionDecoratorBracket instance with default values.
  14466. */
  14467. QCPSelectionDecoratorBracket::QCPSelectionDecoratorBracket() :
  14468. mBracketPen(QPen(Qt::black)),
  14469. mBracketBrush(Qt::NoBrush),
  14470. mBracketWidth(5),
  14471. mBracketHeight(50),
  14472. mBracketStyle(bsSquareBracket),
  14473. mTangentToData(false),
  14474. mTangentAverage(2)
  14475. {
  14476. }
  14477. QCPSelectionDecoratorBracket::~QCPSelectionDecoratorBracket()
  14478. {
  14479. }
  14480. /*!
  14481. Sets the pen that will be used to draw the brackets at the beginning and end of each selected
  14482. data segment.
  14483. */
  14484. void QCPSelectionDecoratorBracket::setBracketPen(const QPen &pen)
  14485. {
  14486. mBracketPen = pen;
  14487. }
  14488. /*!
  14489. Sets the brush that will be used to draw the brackets at the beginning and end of each selected
  14490. data segment.
  14491. */
  14492. void QCPSelectionDecoratorBracket::setBracketBrush(const QBrush &brush)
  14493. {
  14494. mBracketBrush = brush;
  14495. }
  14496. /*!
  14497. Sets the width of the drawn bracket. The width dimension is always parallel to the key axis of
  14498. the data, or the tangent direction of the current data slope, if \ref setTangentToData is
  14499. enabled.
  14500. */
  14501. void QCPSelectionDecoratorBracket::setBracketWidth(int width)
  14502. {
  14503. mBracketWidth = width;
  14504. }
  14505. /*!
  14506. Sets the height of the drawn bracket. The height dimension is always perpendicular to the key axis
  14507. of the data, or the tangent direction of the current data slope, if \ref setTangentToData is
  14508. enabled.
  14509. */
  14510. void QCPSelectionDecoratorBracket::setBracketHeight(int height)
  14511. {
  14512. mBracketHeight = height;
  14513. }
  14514. /*!
  14515. Sets the shape that the bracket/marker will have.
  14516. \see setBracketWidth, setBracketHeight
  14517. */
  14518. void QCPSelectionDecoratorBracket::setBracketStyle(QCPSelectionDecoratorBracket::BracketStyle style)
  14519. {
  14520. mBracketStyle = style;
  14521. }
  14522. /*!
  14523. Sets whether the brackets will be rotated such that they align with the slope of the data at the
  14524. position that they appear in.
  14525. For noisy data, it might be more visually appealing to average the slope over multiple data
  14526. points. This can be configured via \ref setTangentAverage.
  14527. */
  14528. void QCPSelectionDecoratorBracket::setTangentToData(bool enabled)
  14529. {
  14530. mTangentToData = enabled;
  14531. }
  14532. /*!
  14533. Controls over how many data points the slope shall be averaged, when brackets shall be aligned
  14534. with the data (if \ref setTangentToData is true).
  14535. From the position of the bracket, \a pointCount points towards the selected data range will be
  14536. taken into account. The smallest value of \a pointCount is 1, which is effectively equivalent to
  14537. disabling \ref setTangentToData.
  14538. */
  14539. void QCPSelectionDecoratorBracket::setTangentAverage(int pointCount)
  14540. {
  14541. mTangentAverage = pointCount;
  14542. if (mTangentAverage < 1)
  14543. mTangentAverage = 1;
  14544. }
  14545. /*!
  14546. Draws the bracket shape with \a painter. The parameter \a direction is either -1 or 1 and
  14547. indicates whether the bracket shall point to the left or the right (i.e. is a closing or opening
  14548. bracket, respectively).
  14549. The passed \a painter already contains all transformations that are necessary to position and
  14550. rotate the bracket appropriately. Painting operations can be performed as if drawing upright
  14551. brackets on flat data with horizontal key axis, with (0, 0) being the center of the bracket.
  14552. If you wish to sublcass \ref QCPSelectionDecoratorBracket in order to provide custom bracket
  14553. shapes (see \ref QCPSelectionDecoratorBracket::bsUserStyle), this is the method you should
  14554. reimplement.
  14555. */
  14556. void QCPSelectionDecoratorBracket::drawBracket(QCPPainter *painter, int direction) const
  14557. {
  14558. switch (mBracketStyle)
  14559. {
  14560. case bsSquareBracket:
  14561. {
  14562. painter->drawLine(QLineF(mBracketWidth*direction, -mBracketHeight*0.5, 0, -mBracketHeight*0.5));
  14563. painter->drawLine(QLineF(mBracketWidth*direction, mBracketHeight*0.5, 0, mBracketHeight*0.5));
  14564. painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
  14565. break;
  14566. }
  14567. case bsHalfEllipse:
  14568. {
  14569. painter->drawArc(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight), -90*16, -180*16*direction);
  14570. break;
  14571. }
  14572. case bsEllipse:
  14573. {
  14574. painter->drawEllipse(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight));
  14575. break;
  14576. }
  14577. case bsPlus:
  14578. {
  14579. painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
  14580. painter->drawLine(QLineF(-mBracketWidth*0.5, 0, mBracketWidth*0.5, 0));
  14581. break;
  14582. }
  14583. default:
  14584. {
  14585. qDebug() << Q_FUNC_INFO << "unknown/custom bracket style can't be handeld by default implementation:" << static_cast<int>(mBracketStyle);
  14586. break;
  14587. }
  14588. }
  14589. }
  14590. /*!
  14591. Draws the bracket decoration on the data points at the begin and end of each selected data
  14592. segment given in \a seletion.
  14593. It uses the method \ref drawBracket to actually draw the shapes.
  14594. \seebaseclassmethod
  14595. */
  14596. void QCPSelectionDecoratorBracket::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
  14597. {
  14598. if (!mPlottable || selection.isEmpty()) return;
  14599. if (QCPPlottableInterface1D *interface1d = mPlottable->interface1D())
  14600. {
  14601. foreach (const QCPDataRange &dataRange, selection.dataRanges())
  14602. {
  14603. // determine position and (if tangent mode is enabled) angle of brackets:
  14604. int openBracketDir = (mPlottable->keyAxis() && !mPlottable->keyAxis()->rangeReversed()) ? 1 : -1;
  14605. int closeBracketDir = -openBracketDir;
  14606. QPointF openBracketPos = getPixelCoordinates(interface1d, dataRange.begin());
  14607. QPointF closeBracketPos = getPixelCoordinates(interface1d, dataRange.end()-1);
  14608. double openBracketAngle = 0;
  14609. double closeBracketAngle = 0;
  14610. if (mTangentToData)
  14611. {
  14612. openBracketAngle = getTangentAngle(interface1d, dataRange.begin(), openBracketDir);
  14613. closeBracketAngle = getTangentAngle(interface1d, dataRange.end()-1, closeBracketDir);
  14614. }
  14615. // draw opening bracket:
  14616. QTransform oldTransform = painter->transform();
  14617. painter->setPen(mBracketPen);
  14618. painter->setBrush(mBracketBrush);
  14619. painter->translate(openBracketPos);
  14620. painter->rotate(openBracketAngle/M_PI*180.0);
  14621. drawBracket(painter, openBracketDir);
  14622. painter->setTransform(oldTransform);
  14623. // draw closing bracket:
  14624. painter->setPen(mBracketPen);
  14625. painter->setBrush(mBracketBrush);
  14626. painter->translate(closeBracketPos);
  14627. painter->rotate(closeBracketAngle/M_PI*180.0);
  14628. drawBracket(painter, closeBracketDir);
  14629. painter->setTransform(oldTransform);
  14630. }
  14631. }
  14632. }
  14633. /*! \internal
  14634. If \ref setTangentToData is enabled, brackets need to be rotated according to the data slope.
  14635. This method returns the angle in radians by which a bracket at the given \a dataIndex must be
  14636. rotated.
  14637. The parameter \a direction must be set to either -1 or 1, representing whether it is an opening
  14638. or closing bracket. Since for slope calculation multiple data points are required, this defines
  14639. the direction in which the algorithm walks, starting at \a dataIndex, to average those data
  14640. points. (see \ref setTangentToData and \ref setTangentAverage)
  14641. \a interface1d is the interface to the plottable's data which is used to query data coordinates.
  14642. */
  14643. double QCPSelectionDecoratorBracket::getTangentAngle(const QCPPlottableInterface1D *interface1d, int dataIndex, int direction) const
  14644. {
  14645. if (!interface1d || dataIndex < 0 || dataIndex >= interface1d->dataCount())
  14646. return 0;
  14647. direction = direction < 0 ? -1 : 1; // enforce direction is either -1 or 1
  14648. // how many steps we can actually go from index in the given direction without exceeding data bounds:
  14649. int averageCount;
  14650. if (direction < 0)
  14651. averageCount = qMin(mTangentAverage, dataIndex);
  14652. else
  14653. averageCount = qMin(mTangentAverage, interface1d->dataCount()-1-dataIndex);
  14654. qDebug() << averageCount;
  14655. // calculate point average of averageCount points:
  14656. QVector<QPointF> points(averageCount);
  14657. QPointF pointsAverage;
  14658. int currentIndex = dataIndex;
  14659. for (int i=0; i<averageCount; ++i)
  14660. {
  14661. points[i] = getPixelCoordinates(interface1d, currentIndex);
  14662. pointsAverage += points[i];
  14663. currentIndex += direction;
  14664. }
  14665. pointsAverage /= double(averageCount);
  14666. // calculate slope of linear regression through points:
  14667. double numSum = 0;
  14668. double denomSum = 0;
  14669. for (int i=0; i<averageCount; ++i)
  14670. {
  14671. const double dx = points.at(i).x()-pointsAverage.x();
  14672. const double dy = points.at(i).y()-pointsAverage.y();
  14673. numSum += dx*dy;
  14674. denomSum += dx*dx;
  14675. }
  14676. if (!qFuzzyIsNull(denomSum) && !qFuzzyIsNull(numSum))
  14677. {
  14678. return qAtan2(numSum, denomSum);
  14679. } else // undetermined angle, probably mTangentAverage == 1, so using only one data point
  14680. return 0;
  14681. }
  14682. /*! \internal
  14683. Returns the pixel coordinates of the data point at \a dataIndex, using \a interface1d to access
  14684. the data points.
  14685. */
  14686. QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInterface1D *interface1d, int dataIndex) const
  14687. {
  14688. QCPAxis *keyAxis = mPlottable->keyAxis();
  14689. QCPAxis *valueAxis = mPlottable->valueAxis();
  14690. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {0, 0}; }
  14691. if (keyAxis->orientation() == Qt::Horizontal)
  14692. return {keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)), valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex))};
  14693. else
  14694. return {valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)), keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex))};
  14695. }
  14696. /* end of 'src/selectiondecorator-bracket.cpp' */
  14697. /* including file 'src/layoutelements/layoutelement-axisrect.cpp' */
  14698. /* modified 2021-03-29T02:30:44, size 47193 */
  14699. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14700. //////////////////// QCPAxisRect
  14701. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14702. /*! \class QCPAxisRect
  14703. \brief Holds multiple axes and arranges them in a rectangular shape.
  14704. This class represents an axis rect, a rectangular area that is bounded on all sides with an
  14705. arbitrary number of axes.
  14706. Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the
  14707. layout system allows to have multiple axis rects, e.g. arranged in a grid layout
  14708. (QCustomPlot::plotLayout).
  14709. By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be
  14710. accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index.
  14711. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be
  14712. invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref
  14713. addAxes. To remove an axis, use \ref removeAxis.
  14714. The axis rect layerable itself only draws a background pixmap or color, if specified (\ref
  14715. setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an
  14716. explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be
  14717. placed on other layers, independently of the axis rect.
  14718. Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref
  14719. insetLayout and can be used to have other layout elements (or even other layouts with multiple
  14720. elements) hovering inside the axis rect.
  14721. If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The
  14722. behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel
  14723. is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable
  14724. via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are
  14725. only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref
  14726. QCP::iRangeZoom.
  14727. \image html AxisRectSpacingOverview.png
  14728. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed
  14729. line on the far left indicates the viewport/widget border.</center>
  14730. */
  14731. /* start documentation of inline functions */
  14732. /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const
  14733. Returns the inset layout of this axis rect. It can be used to place other layout elements (or
  14734. even layouts with multiple other elements) inside/on top of an axis rect.
  14735. \see QCPLayoutInset
  14736. */
  14737. /*! \fn int QCPAxisRect::left() const
  14738. Returns the pixel position of the left border of this axis rect. Margins are not taken into
  14739. account here, so the returned value is with respect to the inner \ref rect.
  14740. */
  14741. /*! \fn int QCPAxisRect::right() const
  14742. Returns the pixel position of the right border of this axis rect. Margins are not taken into
  14743. account here, so the returned value is with respect to the inner \ref rect.
  14744. */
  14745. /*! \fn int QCPAxisRect::top() const
  14746. Returns the pixel position of the top border of this axis rect. Margins are not taken into
  14747. account here, so the returned value is with respect to the inner \ref rect.
  14748. */
  14749. /*! \fn int QCPAxisRect::bottom() const
  14750. Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
  14751. account here, so the returned value is with respect to the inner \ref rect.
  14752. */
  14753. /*! \fn int QCPAxisRect::width() const
  14754. Returns the pixel width of this axis rect. Margins are not taken into account here, so the
  14755. returned value is with respect to the inner \ref rect.
  14756. */
  14757. /*! \fn int QCPAxisRect::height() const
  14758. Returns the pixel height of this axis rect. Margins are not taken into account here, so the
  14759. returned value is with respect to the inner \ref rect.
  14760. */
  14761. /*! \fn QSize QCPAxisRect::size() const
  14762. Returns the pixel size of this axis rect. Margins are not taken into account here, so the
  14763. returned value is with respect to the inner \ref rect.
  14764. */
  14765. /*! \fn QPoint QCPAxisRect::topLeft() const
  14766. Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
  14767. so the returned value is with respect to the inner \ref rect.
  14768. */
  14769. /*! \fn QPoint QCPAxisRect::topRight() const
  14770. Returns the top right corner of this axis rect in pixels. Margins are not taken into account
  14771. here, so the returned value is with respect to the inner \ref rect.
  14772. */
  14773. /*! \fn QPoint QCPAxisRect::bottomLeft() const
  14774. Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
  14775. here, so the returned value is with respect to the inner \ref rect.
  14776. */
  14777. /*! \fn QPoint QCPAxisRect::bottomRight() const
  14778. Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
  14779. here, so the returned value is with respect to the inner \ref rect.
  14780. */
  14781. /*! \fn QPoint QCPAxisRect::center() const
  14782. Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
  14783. returned value is with respect to the inner \ref rect.
  14784. */
  14785. /* end documentation of inline functions */
  14786. /*!
  14787. Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four
  14788. sides, the top and right axes are set invisible initially.
  14789. */
  14790. QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) :
  14791. QCPLayoutElement(parentPlot),
  14792. mBackgroundBrush(Qt::NoBrush),
  14793. mBackgroundScaled(true),
  14794. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  14795. mInsetLayout(new QCPLayoutInset),
  14796. mRangeDrag(Qt::Horizontal|Qt::Vertical),
  14797. mRangeZoom(Qt::Horizontal|Qt::Vertical),
  14798. mRangeZoomFactorHorz(0.85),
  14799. mRangeZoomFactorVert(0.85),
  14800. mDragging(false)
  14801. {
  14802. mInsetLayout->initializeParentPlot(mParentPlot);
  14803. mInsetLayout->setParentLayerable(this);
  14804. mInsetLayout->setParent(this);
  14805. setMinimumSize(50, 50);
  14806. setMinimumMargins(QMargins(15, 15, 15, 15));
  14807. mAxes.insert(QCPAxis::atLeft, QList<QCPAxis*>());
  14808. mAxes.insert(QCPAxis::atRight, QList<QCPAxis*>());
  14809. mAxes.insert(QCPAxis::atTop, QList<QCPAxis*>());
  14810. mAxes.insert(QCPAxis::atBottom, QList<QCPAxis*>());
  14811. if (setupDefaultAxes)
  14812. {
  14813. QCPAxis *xAxis = addAxis(QCPAxis::atBottom);
  14814. QCPAxis *yAxis = addAxis(QCPAxis::atLeft);
  14815. QCPAxis *xAxis2 = addAxis(QCPAxis::atTop);
  14816. QCPAxis *yAxis2 = addAxis(QCPAxis::atRight);
  14817. setRangeDragAxes(xAxis, yAxis);
  14818. setRangeZoomAxes(xAxis, yAxis);
  14819. xAxis2->setVisible(false);
  14820. yAxis2->setVisible(false);
  14821. xAxis->grid()->setVisible(true);
  14822. yAxis->grid()->setVisible(true);
  14823. xAxis2->grid()->setVisible(false);
  14824. yAxis2->grid()->setVisible(false);
  14825. xAxis2->grid()->setZeroLinePen(Qt::NoPen);
  14826. yAxis2->grid()->setZeroLinePen(Qt::NoPen);
  14827. xAxis2->grid()->setVisible(false);
  14828. yAxis2->grid()->setVisible(false);
  14829. }
  14830. }
  14831. QCPAxisRect::~QCPAxisRect()
  14832. {
  14833. delete mInsetLayout;
  14834. mInsetLayout = nullptr;
  14835. foreach (QCPAxis *axis, axes())
  14836. removeAxis(axis);
  14837. }
  14838. /*!
  14839. Returns the number of axes on the axis rect side specified with \a type.
  14840. \see axis
  14841. */
  14842. int QCPAxisRect::axisCount(QCPAxis::AxisType type) const
  14843. {
  14844. return mAxes.value(type).size();
  14845. }
  14846. /*!
  14847. Returns the axis with the given \a index on the axis rect side specified with \a type.
  14848. \see axisCount, axes
  14849. */
  14850. QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const
  14851. {
  14852. QList<QCPAxis*> ax(mAxes.value(type));
  14853. if (index >= 0 && index < ax.size())
  14854. {
  14855. return ax.at(index);
  14856. } else
  14857. {
  14858. qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
  14859. return nullptr;
  14860. }
  14861. }
  14862. /*!
  14863. Returns all axes on the axis rect sides specified with \a types.
  14864. \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
  14865. multiple sides.
  14866. \see axis
  14867. */
  14868. QList<QCPAxis*> QCPAxisRect::axes(QCPAxis::AxisTypes types) const
  14869. {
  14870. QList<QCPAxis*> result;
  14871. if (types.testFlag(QCPAxis::atLeft))
  14872. result << mAxes.value(QCPAxis::atLeft);
  14873. if (types.testFlag(QCPAxis::atRight))
  14874. result << mAxes.value(QCPAxis::atRight);
  14875. if (types.testFlag(QCPAxis::atTop))
  14876. result << mAxes.value(QCPAxis::atTop);
  14877. if (types.testFlag(QCPAxis::atBottom))
  14878. result << mAxes.value(QCPAxis::atBottom);
  14879. return result;
  14880. }
  14881. /*! \overload
  14882. Returns all axes of this axis rect.
  14883. */
  14884. QList<QCPAxis*> QCPAxisRect::axes() const
  14885. {
  14886. QList<QCPAxis*> result;
  14887. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
  14888. while (it.hasNext())
  14889. {
  14890. it.next();
  14891. result << it.value();
  14892. }
  14893. return result;
  14894. }
  14895. /*!
  14896. Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
  14897. new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
  14898. remove an axis, use \ref removeAxis instead of deleting it manually.
  14899. You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was
  14900. previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
  14901. of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
  14902. with this axis rect as parent and with the same axis type as specified in \a type. If this is not
  14903. the case, a debug output is generated, the axis is not added, and the method returns \c nullptr.
  14904. This method can not be used to move \a axis between axis rects. The same \a axis instance must
  14905. not be added multiple times to the same or different axis rects.
  14906. If an axis rect side already contains one or more axes, the lower and upper endings of the new
  14907. axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
  14908. QCPLineEnding::esHalfBar.
  14909. \see addAxes, setupFullAxesBox
  14910. */
  14911. QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis)
  14912. {
  14913. QCPAxis *newAxis = axis;
  14914. if (!newAxis)
  14915. {
  14916. newAxis = new QCPAxis(this, type);
  14917. } else // user provided existing axis instance, do some sanity checks
  14918. {
  14919. if (newAxis->axisType() != type)
  14920. {
  14921. qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter";
  14922. return nullptr;
  14923. }
  14924. if (newAxis->axisRect() != this)
  14925. {
  14926. qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect";
  14927. return nullptr;
  14928. }
  14929. if (axes().contains(newAxis))
  14930. {
  14931. qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect";
  14932. return nullptr;
  14933. }
  14934. }
  14935. if (!mAxes[type].isEmpty()) // multiple axes on one side, add half-bar axis ending to additional axes with offset
  14936. {
  14937. bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom);
  14938. newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert));
  14939. newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert));
  14940. }
  14941. mAxes[type].append(newAxis);
  14942. // reset convenience axis pointers on parent QCustomPlot if they are unset:
  14943. if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
  14944. {
  14945. switch (type)
  14946. {
  14947. case QCPAxis::atBottom: { if (!mParentPlot->xAxis) mParentPlot->xAxis = newAxis; break; }
  14948. case QCPAxis::atLeft: { if (!mParentPlot->yAxis) mParentPlot->yAxis = newAxis; break; }
  14949. case QCPAxis::atTop: { if (!mParentPlot->xAxis2) mParentPlot->xAxis2 = newAxis; break; }
  14950. case QCPAxis::atRight: { if (!mParentPlot->yAxis2) mParentPlot->yAxis2 = newAxis; break; }
  14951. }
  14952. }
  14953. return newAxis;
  14954. }
  14955. /*!
  14956. Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an
  14957. <tt>or</tt>-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once.
  14958. Returns a list of the added axes.
  14959. \see addAxis, setupFullAxesBox
  14960. */
  14961. QList<QCPAxis*> QCPAxisRect::addAxes(QCPAxis::AxisTypes types)
  14962. {
  14963. QList<QCPAxis*> result;
  14964. if (types.testFlag(QCPAxis::atLeft))
  14965. result << addAxis(QCPAxis::atLeft);
  14966. if (types.testFlag(QCPAxis::atRight))
  14967. result << addAxis(QCPAxis::atRight);
  14968. if (types.testFlag(QCPAxis::atTop))
  14969. result << addAxis(QCPAxis::atTop);
  14970. if (types.testFlag(QCPAxis::atBottom))
  14971. result << addAxis(QCPAxis::atBottom);
  14972. return result;
  14973. }
  14974. /*!
  14975. Removes the specified \a axis from the axis rect and deletes it.
  14976. Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
  14977. \see addAxis
  14978. */
  14979. bool QCPAxisRect::removeAxis(QCPAxis *axis)
  14980. {
  14981. // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers:
  14982. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
  14983. while (it.hasNext())
  14984. {
  14985. it.next();
  14986. if (it.value().contains(axis))
  14987. {
  14988. if (it.value().first() == axis && it.value().size() > 1) // if removing first axis, transfer axis offset to the new first axis (which at this point is the second axis, if it exists)
  14989. it.value()[1]->setOffset(axis->offset());
  14990. mAxes[it.key()].removeOne(axis);
  14991. if (qobject_cast<QCustomPlot*>(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot)
  14992. parentPlot()->axisRemoved(axis);
  14993. delete axis;
  14994. return true;
  14995. }
  14996. }
  14997. qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast<quintptr>(axis);
  14998. return false;
  14999. }
  15000. /*!
  15001. Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
  15002. All axes of this axis rect will have their range zoomed accordingly. If you only wish to zoom
  15003. specific axes, use the overloaded version of this method.
  15004. \see QCustomPlot::setSelectionRectMode
  15005. */
  15006. void QCPAxisRect::zoom(const QRectF &pixelRect)
  15007. {
  15008. zoom(pixelRect, axes());
  15009. }
  15010. /*! \overload
  15011. Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
  15012. Only the axes passed in \a affectedAxes will have their ranges zoomed accordingly.
  15013. \see QCustomPlot::setSelectionRectMode
  15014. */
  15015. void QCPAxisRect::zoom(const QRectF &pixelRect, const QList<QCPAxis*> &affectedAxes)
  15016. {
  15017. foreach (QCPAxis *axis, affectedAxes)
  15018. {
  15019. if (!axis)
  15020. {
  15021. qDebug() << Q_FUNC_INFO << "a passed axis was zero";
  15022. continue;
  15023. }
  15024. QCPRange pixelRange;
  15025. if (axis->orientation() == Qt::Horizontal)
  15026. pixelRange = QCPRange(pixelRect.left(), pixelRect.right());
  15027. else
  15028. pixelRange = QCPRange(pixelRect.top(), pixelRect.bottom());
  15029. axis->setRange(axis->pixelToCoord(pixelRange.lower), axis->pixelToCoord(pixelRange.upper));
  15030. }
  15031. }
  15032. /*!
  15033. Convenience function to create an axis on each side that doesn't have any axes yet and set their
  15034. visibility to true. Further, the top/right axes are assigned the following properties of the
  15035. bottom/left axes:
  15036. \li range (\ref QCPAxis::setRange)
  15037. \li range reversed (\ref QCPAxis::setRangeReversed)
  15038. \li scale type (\ref QCPAxis::setScaleType)
  15039. \li tick visibility (\ref QCPAxis::setTicks)
  15040. \li number format (\ref QCPAxis::setNumberFormat)
  15041. \li number precision (\ref QCPAxis::setNumberPrecision)
  15042. \li tick count of ticker (\ref QCPAxisTicker::setTickCount)
  15043. \li tick origin of ticker (\ref QCPAxisTicker::setTickOrigin)
  15044. Tick label visibility (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
  15045. If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom
  15046. and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes.
  15047. */
  15048. void QCPAxisRect::setupFullAxesBox(bool connectRanges)
  15049. {
  15050. QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
  15051. if (axisCount(QCPAxis::atBottom) == 0)
  15052. xAxis = addAxis(QCPAxis::atBottom);
  15053. else
  15054. xAxis = axis(QCPAxis::atBottom);
  15055. if (axisCount(QCPAxis::atLeft) == 0)
  15056. yAxis = addAxis(QCPAxis::atLeft);
  15057. else
  15058. yAxis = axis(QCPAxis::atLeft);
  15059. if (axisCount(QCPAxis::atTop) == 0)
  15060. xAxis2 = addAxis(QCPAxis::atTop);
  15061. else
  15062. xAxis2 = axis(QCPAxis::atTop);
  15063. if (axisCount(QCPAxis::atRight) == 0)
  15064. yAxis2 = addAxis(QCPAxis::atRight);
  15065. else
  15066. yAxis2 = axis(QCPAxis::atRight);
  15067. xAxis->setVisible(true);
  15068. yAxis->setVisible(true);
  15069. xAxis2->setVisible(true);
  15070. yAxis2->setVisible(true);
  15071. xAxis2->setTickLabels(false);
  15072. yAxis2->setTickLabels(false);
  15073. xAxis2->setRange(xAxis->range());
  15074. xAxis2->setRangeReversed(xAxis->rangeReversed());
  15075. xAxis2->setScaleType(xAxis->scaleType());
  15076. xAxis2->setTicks(xAxis->ticks());
  15077. xAxis2->setNumberFormat(xAxis->numberFormat());
  15078. xAxis2->setNumberPrecision(xAxis->numberPrecision());
  15079. xAxis2->ticker()->setTickCount(xAxis->ticker()->tickCount());
  15080. xAxis2->ticker()->setTickOrigin(xAxis->ticker()->tickOrigin());
  15081. yAxis2->setRange(yAxis->range());
  15082. yAxis2->setRangeReversed(yAxis->rangeReversed());
  15083. yAxis2->setScaleType(yAxis->scaleType());
  15084. yAxis2->setTicks(yAxis->ticks());
  15085. yAxis2->setNumberFormat(yAxis->numberFormat());
  15086. yAxis2->setNumberPrecision(yAxis->numberPrecision());
  15087. yAxis2->ticker()->setTickCount(yAxis->ticker()->tickCount());
  15088. yAxis2->ticker()->setTickOrigin(yAxis->ticker()->tickOrigin());
  15089. if (connectRanges)
  15090. {
  15091. connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange)));
  15092. connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange)));
  15093. }
  15094. }
  15095. /*!
  15096. Returns a list of all the plottables that are associated with this axis rect.
  15097. A plottable is considered associated with an axis rect if its key or value axis (or both) is in
  15098. this axis rect.
  15099. \see graphs, items
  15100. */
  15101. QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const
  15102. {
  15103. // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries
  15104. QList<QCPAbstractPlottable*> result;
  15105. foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables)
  15106. {
  15107. if (plottable->keyAxis()->axisRect() == this || plottable->valueAxis()->axisRect() == this)
  15108. result.append(plottable);
  15109. }
  15110. return result;
  15111. }
  15112. /*!
  15113. Returns a list of all the graphs that are associated with this axis rect.
  15114. A graph is considered associated with an axis rect if its key or value axis (or both) is in
  15115. this axis rect.
  15116. \see plottables, items
  15117. */
  15118. QList<QCPGraph*> QCPAxisRect::graphs() const
  15119. {
  15120. // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries
  15121. QList<QCPGraph*> result;
  15122. foreach (QCPGraph *graph, mParentPlot->mGraphs)
  15123. {
  15124. if (graph->keyAxis()->axisRect() == this || graph->valueAxis()->axisRect() == this)
  15125. result.append(graph);
  15126. }
  15127. return result;
  15128. }
  15129. /*!
  15130. Returns a list of all the items that are associated with this axis rect.
  15131. An item is considered associated with an axis rect if any of its positions has key or value axis
  15132. set to an axis that is in this axis rect, or if any of its positions has \ref
  15133. QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref
  15134. QCPAbstractItem::setClipAxisRect) is set to this axis rect.
  15135. \see plottables, graphs
  15136. */
  15137. QList<QCPAbstractItem *> QCPAxisRect::items() const
  15138. {
  15139. // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries
  15140. // and miss those items that have this axis rect as clipAxisRect.
  15141. QList<QCPAbstractItem*> result;
  15142. foreach (QCPAbstractItem *item, mParentPlot->mItems)
  15143. {
  15144. if (item->clipAxisRect() == this)
  15145. {
  15146. result.append(item);
  15147. continue;
  15148. }
  15149. foreach (QCPItemPosition *position, item->positions())
  15150. {
  15151. if (position->axisRect() == this ||
  15152. position->keyAxis()->axisRect() == this ||
  15153. position->valueAxis()->axisRect() == this)
  15154. {
  15155. result.append(item);
  15156. break;
  15157. }
  15158. }
  15159. }
  15160. return result;
  15161. }
  15162. /*!
  15163. This method is called automatically upon replot and doesn't need to be called by users of
  15164. QCPAxisRect.
  15165. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
  15166. and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
  15167. QCPInsetLayout::update function.
  15168. \seebaseclassmethod
  15169. */
  15170. void QCPAxisRect::update(UpdatePhase phase)
  15171. {
  15172. QCPLayoutElement::update(phase);
  15173. switch (phase)
  15174. {
  15175. case upPreparation:
  15176. {
  15177. foreach (QCPAxis *axis, axes())
  15178. axis->setupTickVectors();
  15179. break;
  15180. }
  15181. case upLayout:
  15182. {
  15183. mInsetLayout->setOuterRect(rect());
  15184. break;
  15185. }
  15186. default: break;
  15187. }
  15188. // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout):
  15189. mInsetLayout->update(phase);
  15190. }
  15191. /* inherits documentation from base class */
  15192. QList<QCPLayoutElement*> QCPAxisRect::elements(bool recursive) const
  15193. {
  15194. QList<QCPLayoutElement*> result;
  15195. if (mInsetLayout)
  15196. {
  15197. result << mInsetLayout;
  15198. if (recursive)
  15199. result << mInsetLayout->elements(recursive);
  15200. }
  15201. return result;
  15202. }
  15203. /* inherits documentation from base class */
  15204. void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
  15205. {
  15206. painter->setAntialiasing(false);
  15207. }
  15208. /* inherits documentation from base class */
  15209. void QCPAxisRect::draw(QCPPainter *painter)
  15210. {
  15211. drawBackground(painter);
  15212. }
  15213. /*!
  15214. Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
  15215. axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
  15216. backgrounds are usually drawn below everything else.
  15217. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
  15218. enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
  15219. is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  15220. consider using the overloaded version of this function.
  15221. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
  15222. setBackground(const QBrush &brush).
  15223. \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
  15224. */
  15225. void QCPAxisRect::setBackground(const QPixmap &pm)
  15226. {
  15227. mBackgroundPixmap = pm;
  15228. mScaledBackgroundPixmap = QPixmap();
  15229. }
  15230. /*! \overload
  15231. Sets \a brush as the background brush. The axis rect background will be filled with this brush.
  15232. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
  15233. are usually drawn below everything else.
  15234. The brush will be drawn before (under) any background pixmap, which may be specified with \ref
  15235. setBackground(const QPixmap &pm).
  15236. To disable drawing of a background brush, set \a brush to Qt::NoBrush.
  15237. \see setBackground(const QPixmap &pm)
  15238. */
  15239. void QCPAxisRect::setBackground(const QBrush &brush)
  15240. {
  15241. mBackgroundBrush = brush;
  15242. }
  15243. /*! \overload
  15244. Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
  15245. shall be scaled in one call.
  15246. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  15247. */
  15248. void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  15249. {
  15250. mBackgroundPixmap = pm;
  15251. mScaledBackgroundPixmap = QPixmap();
  15252. mBackgroundScaled = scaled;
  15253. mBackgroundScaledMode = mode;
  15254. }
  15255. /*!
  15256. Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
  15257. is set to true, you may control whether and how the aspect ratio of the original pixmap is
  15258. preserved with \ref setBackgroundScaledMode.
  15259. Note that the scaled version of the original pixmap is buffered, so there is no performance
  15260. penalty on replots. (Except when the axis rect dimensions are changed continuously.)
  15261. \see setBackground, setBackgroundScaledMode
  15262. */
  15263. void QCPAxisRect::setBackgroundScaled(bool scaled)
  15264. {
  15265. mBackgroundScaled = scaled;
  15266. }
  15267. /*!
  15268. If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
  15269. define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
  15270. \see setBackground, setBackgroundScaled
  15271. */
  15272. void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  15273. {
  15274. mBackgroundScaledMode = mode;
  15275. }
  15276. /*!
  15277. Returns the range drag axis of the \a orientation provided. If multiple axes were set, returns
  15278. the first one (use \ref rangeDragAxes to retrieve a list with all set axes).
  15279. \see setRangeDragAxes
  15280. */
  15281. QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation)
  15282. {
  15283. if (orientation == Qt::Horizontal)
  15284. return mRangeDragHorzAxis.isEmpty() ? nullptr : mRangeDragHorzAxis.first().data();
  15285. else
  15286. return mRangeDragVertAxis.isEmpty() ? nullptr : mRangeDragVertAxis.first().data();
  15287. }
  15288. /*!
  15289. Returns the range zoom axis of the \a orientation provided. If multiple axes were set, returns
  15290. the first one (use \ref rangeZoomAxes to retrieve a list with all set axes).
  15291. \see setRangeZoomAxes
  15292. */
  15293. QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation)
  15294. {
  15295. if (orientation == Qt::Horizontal)
  15296. return mRangeZoomHorzAxis.isEmpty() ? nullptr : mRangeZoomHorzAxis.first().data();
  15297. else
  15298. return mRangeZoomVertAxis.isEmpty() ? nullptr : mRangeZoomVertAxis.first().data();
  15299. }
  15300. /*!
  15301. Returns all range drag axes of the \a orientation provided.
  15302. \see rangeZoomAxis, setRangeZoomAxes
  15303. */
  15304. QList<QCPAxis*> QCPAxisRect::rangeDragAxes(Qt::Orientation orientation)
  15305. {
  15306. QList<QCPAxis*> result;
  15307. if (orientation == Qt::Horizontal)
  15308. {
  15309. foreach (QPointer<QCPAxis> axis, mRangeDragHorzAxis)
  15310. {
  15311. if (!axis.isNull())
  15312. result.append(axis.data());
  15313. }
  15314. } else
  15315. {
  15316. foreach (QPointer<QCPAxis> axis, mRangeDragVertAxis)
  15317. {
  15318. if (!axis.isNull())
  15319. result.append(axis.data());
  15320. }
  15321. }
  15322. return result;
  15323. }
  15324. /*!
  15325. Returns all range zoom axes of the \a orientation provided.
  15326. \see rangeDragAxis, setRangeDragAxes
  15327. */
  15328. QList<QCPAxis*> QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation)
  15329. {
  15330. QList<QCPAxis*> result;
  15331. if (orientation == Qt::Horizontal)
  15332. {
  15333. foreach (QPointer<QCPAxis> axis, mRangeZoomHorzAxis)
  15334. {
  15335. if (!axis.isNull())
  15336. result.append(axis.data());
  15337. }
  15338. } else
  15339. {
  15340. foreach (QPointer<QCPAxis> axis, mRangeZoomVertAxis)
  15341. {
  15342. if (!axis.isNull())
  15343. result.append(axis.data());
  15344. }
  15345. }
  15346. return result;
  15347. }
  15348. /*!
  15349. Returns the range zoom factor of the \a orientation provided.
  15350. \see setRangeZoomFactor
  15351. */
  15352. double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation)
  15353. {
  15354. return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert);
  15355. }
  15356. /*!
  15357. Sets which axis orientation may be range dragged by the user with mouse interaction.
  15358. What orientation corresponds to which specific axis can be set with
  15359. \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By
  15360. default, the horizontal axis is the bottom axis (xAxis) and the vertical axis
  15361. is the left axis (yAxis).
  15362. To disable range dragging entirely, pass \c nullptr as \a orientations or remove \ref
  15363. QCP::iRangeDrag from \ref QCustomPlot::setInteractions. To enable range dragging for both
  15364. directions, pass <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations.
  15365. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
  15366. contains \ref QCP::iRangeDrag to enable the range dragging interaction.
  15367. \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag
  15368. */
  15369. void QCPAxisRect::setRangeDrag(Qt::Orientations orientations)
  15370. {
  15371. mRangeDrag = orientations;
  15372. }
  15373. /*!
  15374. Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation
  15375. corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal,
  15376. QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical
  15377. axis is the left axis (yAxis).
  15378. To disable range zooming entirely, pass \c nullptr as \a orientations or remove \ref
  15379. QCP::iRangeZoom from \ref QCustomPlot::setInteractions. To enable range zooming for both
  15380. directions, pass <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations.
  15381. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
  15382. contains \ref QCP::iRangeZoom to enable the range zooming interaction.
  15383. \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag
  15384. */
  15385. void QCPAxisRect::setRangeZoom(Qt::Orientations orientations)
  15386. {
  15387. mRangeZoom = orientations;
  15388. }
  15389. /*! \overload
  15390. Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on
  15391. the QCustomPlot widget. Pass \c nullptr if no axis shall be dragged in the respective
  15392. orientation.
  15393. Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
  15394. react to dragging interactions.
  15395. \see setRangeZoomAxes
  15396. */
  15397. void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical)
  15398. {
  15399. QList<QCPAxis*> horz, vert;
  15400. if (horizontal)
  15401. horz.append(horizontal);
  15402. if (vertical)
  15403. vert.append(vertical);
  15404. setRangeDragAxes(horz, vert);
  15405. }
  15406. /*! \overload
  15407. This method allows to set up multiple axes to react to horizontal and vertical dragging. The drag
  15408. orientation that the respective axis will react to is deduced from its orientation (\ref
  15409. QCPAxis::orientation).
  15410. In the unusual case that you wish to e.g. drag a vertically oriented axis with a horizontal drag
  15411. motion, use the overload taking two separate lists for horizontal and vertical dragging.
  15412. */
  15413. void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> axes)
  15414. {
  15415. QList<QCPAxis*> horz, vert;
  15416. foreach (QCPAxis *ax, axes)
  15417. {
  15418. if (ax->orientation() == Qt::Horizontal)
  15419. horz.append(ax);
  15420. else
  15421. vert.append(ax);
  15422. }
  15423. setRangeDragAxes(horz, vert);
  15424. }
  15425. /*! \overload
  15426. This method allows to set multiple axes up to react to horizontal and vertical dragging, and
  15427. define specifically which axis reacts to which drag orientation (irrespective of the axis
  15428. orientation).
  15429. */
  15430. void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
  15431. {
  15432. mRangeDragHorzAxis.clear();
  15433. foreach (QCPAxis *ax, horizontal)
  15434. {
  15435. QPointer<QCPAxis> axPointer(ax);
  15436. if (!axPointer.isNull())
  15437. mRangeDragHorzAxis.append(axPointer);
  15438. else
  15439. qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
  15440. }
  15441. mRangeDragVertAxis.clear();
  15442. foreach (QCPAxis *ax, vertical)
  15443. {
  15444. QPointer<QCPAxis> axPointer(ax);
  15445. if (!axPointer.isNull())
  15446. mRangeDragVertAxis.append(axPointer);
  15447. else
  15448. qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
  15449. }
  15450. }
  15451. /*!
  15452. Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on
  15453. the QCustomPlot widget. Pass \c nullptr if no axis shall be zoomed in the respective orientation.
  15454. The two axes can be zoomed with different strengths, when different factors are passed to \ref
  15455. setRangeZoomFactor(double horizontalFactor, double verticalFactor).
  15456. Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
  15457. react to zooming interactions.
  15458. \see setRangeDragAxes
  15459. */
  15460. void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical)
  15461. {
  15462. QList<QCPAxis*> horz, vert;
  15463. if (horizontal)
  15464. horz.append(horizontal);
  15465. if (vertical)
  15466. vert.append(vertical);
  15467. setRangeZoomAxes(horz, vert);
  15468. }
  15469. /*! \overload
  15470. This method allows to set up multiple axes to react to horizontal and vertical range zooming. The
  15471. zoom orientation that the respective axis will react to is deduced from its orientation (\ref
  15472. QCPAxis::orientation).
  15473. In the unusual case that you wish to e.g. zoom a vertically oriented axis with a horizontal zoom
  15474. interaction, use the overload taking two separate lists for horizontal and vertical zooming.
  15475. */
  15476. void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> axes)
  15477. {
  15478. QList<QCPAxis*> horz, vert;
  15479. foreach (QCPAxis *ax, axes)
  15480. {
  15481. if (ax->orientation() == Qt::Horizontal)
  15482. horz.append(ax);
  15483. else
  15484. vert.append(ax);
  15485. }
  15486. setRangeZoomAxes(horz, vert);
  15487. }
  15488. /*! \overload
  15489. This method allows to set multiple axes up to react to horizontal and vertical zooming, and
  15490. define specifically which axis reacts to which zoom orientation (irrespective of the axis
  15491. orientation).
  15492. */
  15493. void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
  15494. {
  15495. mRangeZoomHorzAxis.clear();
  15496. foreach (QCPAxis *ax, horizontal)
  15497. {
  15498. QPointer<QCPAxis> axPointer(ax);
  15499. if (!axPointer.isNull())
  15500. mRangeZoomHorzAxis.append(axPointer);
  15501. else
  15502. qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
  15503. }
  15504. mRangeZoomVertAxis.clear();
  15505. foreach (QCPAxis *ax, vertical)
  15506. {
  15507. QPointer<QCPAxis> axPointer(ax);
  15508. if (!axPointer.isNull())
  15509. mRangeZoomVertAxis.append(axPointer);
  15510. else
  15511. qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
  15512. }
  15513. }
  15514. /*!
  15515. Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with
  15516. \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to
  15517. let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal
  15518. and which is vertical, can be set with \ref setRangeZoomAxes.
  15519. When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user)
  15520. will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the
  15521. same scrolling direction will zoom out.
  15522. */
  15523. void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor)
  15524. {
  15525. mRangeZoomFactorHorz = horizontalFactor;
  15526. mRangeZoomFactorVert = verticalFactor;
  15527. }
  15528. /*! \overload
  15529. Sets both the horizontal and vertical zoom \a factor.
  15530. */
  15531. void QCPAxisRect::setRangeZoomFactor(double factor)
  15532. {
  15533. mRangeZoomFactorHorz = factor;
  15534. mRangeZoomFactorVert = factor;
  15535. }
  15536. /*! \internal
  15537. Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
  15538. pixmap.
  15539. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
  15540. according filling inside the axis rect with the provided \a painter.
  15541. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
  15542. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  15543. the axis rect with the provided \a painter. The scaled version is buffered in
  15544. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  15545. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  15546. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  15547. set.
  15548. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  15549. */
  15550. void QCPAxisRect::drawBackground(QCPPainter *painter)
  15551. {
  15552. // draw background fill:
  15553. if (mBackgroundBrush != Qt::NoBrush)
  15554. painter->fillRect(mRect, mBackgroundBrush);
  15555. // draw background pixmap (on top of fill, if brush specified):
  15556. if (!mBackgroundPixmap.isNull())
  15557. {
  15558. if (mBackgroundScaled)
  15559. {
  15560. // check whether mScaledBackground needs to be updated:
  15561. QSize scaledSize(mBackgroundPixmap.size());
  15562. scaledSize.scale(mRect.size(), mBackgroundScaledMode);
  15563. if (mScaledBackgroundPixmap.size() != scaledSize)
  15564. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  15565. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
  15566. } else
  15567. {
  15568. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
  15569. }
  15570. }
  15571. }
  15572. /*! \internal
  15573. This function makes sure multiple axes on the side specified with \a type don't collide, but are
  15574. distributed according to their respective space requirement (QCPAxis::calculateMargin).
  15575. It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the
  15576. one with index zero.
  15577. This function is called by \ref calculateAutoMargin.
  15578. */
  15579. void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type)
  15580. {
  15581. const QList<QCPAxis*> axesList = mAxes.value(type);
  15582. if (axesList.isEmpty())
  15583. return;
  15584. bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false
  15585. for (int i=1; i<axesList.size(); ++i)
  15586. {
  15587. int offset = axesList.at(i-1)->offset() + axesList.at(i-1)->calculateMargin();
  15588. if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible)
  15589. {
  15590. if (!isFirstVisible)
  15591. offset += axesList.at(i)->tickLengthIn();
  15592. isFirstVisible = false;
  15593. }
  15594. axesList.at(i)->setOffset(offset);
  15595. }
  15596. }
  15597. /* inherits documentation from base class */
  15598. int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
  15599. {
  15600. if (!mAutoMargins.testFlag(side))
  15601. qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin";
  15602. updateAxesOffset(QCPAxis::marginSideToAxisType(side));
  15603. // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call
  15604. const QList<QCPAxis*> axesList = mAxes.value(QCPAxis::marginSideToAxisType(side));
  15605. if (!axesList.isEmpty())
  15606. return axesList.last()->offset() + axesList.last()->calculateMargin();
  15607. else
  15608. return 0;
  15609. }
  15610. /*! \internal
  15611. Reacts to a change in layout to potentially set the convenience axis pointers \ref
  15612. QCustomPlot::xAxis, \ref QCustomPlot::yAxis, etc. of the parent QCustomPlot to the respective
  15613. axes of this axis rect. This is only done if the respective convenience pointer is currently zero
  15614. and if there is no QCPAxisRect at position (0, 0) of the plot layout.
  15615. This automation makes it simpler to replace the main axis rect with a newly created one, without
  15616. the need to manually reset the convenience pointers.
  15617. */
  15618. void QCPAxisRect::layoutChanged()
  15619. {
  15620. if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
  15621. {
  15622. if (axisCount(QCPAxis::atBottom) > 0 && !mParentPlot->xAxis)
  15623. mParentPlot->xAxis = axis(QCPAxis::atBottom);
  15624. if (axisCount(QCPAxis::atLeft) > 0 && !mParentPlot->yAxis)
  15625. mParentPlot->yAxis = axis(QCPAxis::atLeft);
  15626. if (axisCount(QCPAxis::atTop) > 0 && !mParentPlot->xAxis2)
  15627. mParentPlot->xAxis2 = axis(QCPAxis::atTop);
  15628. if (axisCount(QCPAxis::atRight) > 0 && !mParentPlot->yAxis2)
  15629. mParentPlot->yAxis2 = axis(QCPAxis::atRight);
  15630. }
  15631. }
  15632. /*! \internal
  15633. Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
  15634. pressed, the range dragging interaction is initialized (the actual range manipulation happens in
  15635. the \ref mouseMoveEvent).
  15636. The mDragging flag is set to true and some anchor points are set that are needed to determine the
  15637. distance the mouse was dragged in the mouse move/release events later.
  15638. \see mouseMoveEvent, mouseReleaseEvent
  15639. */
  15640. void QCPAxisRect::mousePressEvent(QMouseEvent *event, const QVariant &details)
  15641. {
  15642. Q_UNUSED(details)
  15643. if (event->buttons() & Qt::LeftButton)
  15644. {
  15645. mDragging = true;
  15646. // initialize antialiasing backup in case we start dragging:
  15647. if (mParentPlot->noAntialiasingOnDrag())
  15648. {
  15649. mAADragBackup = mParentPlot->antialiasedElements();
  15650. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  15651. }
  15652. // Mouse range dragging interaction:
  15653. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  15654. {
  15655. mDragStartHorzRange.clear();
  15656. foreach (QPointer<QCPAxis> axis, mRangeDragHorzAxis)
  15657. mDragStartHorzRange.append(axis.isNull() ? QCPRange() : axis->range());
  15658. mDragStartVertRange.clear();
  15659. foreach (QPointer<QCPAxis> axis, mRangeDragVertAxis)
  15660. mDragStartVertRange.append(axis.isNull() ? QCPRange() : axis->range());
  15661. }
  15662. }
  15663. }
  15664. /*! \internal
  15665. Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
  15666. preceding \ref mousePressEvent, the range is moved accordingly.
  15667. \see mousePressEvent, mouseReleaseEvent
  15668. */
  15669. void QCPAxisRect::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  15670. {
  15671. Q_UNUSED(startPos)
  15672. // Mouse range dragging interaction:
  15673. if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  15674. {
  15675. if (mRangeDrag.testFlag(Qt::Horizontal))
  15676. {
  15677. for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
  15678. {
  15679. QCPAxis *ax = mRangeDragHorzAxis.at(i).data();
  15680. if (!ax)
  15681. continue;
  15682. if (i >= mDragStartHorzRange.size())
  15683. break;
  15684. if (ax->mScaleType == QCPAxis::stLinear)
  15685. {
  15686. double diff = ax->pixelToCoord(startPos.x()) - ax->pixelToCoord(event->pos().x());
  15687. ax->setRange(mDragStartHorzRange.at(i).lower+diff, mDragStartHorzRange.at(i).upper+diff);
  15688. } else if (ax->mScaleType == QCPAxis::stLogarithmic)
  15689. {
  15690. double diff = ax->pixelToCoord(startPos.x()) / ax->pixelToCoord(event->pos().x());
  15691. ax->setRange(mDragStartHorzRange.at(i).lower*diff, mDragStartHorzRange.at(i).upper*diff);
  15692. }
  15693. }
  15694. }
  15695. if (mRangeDrag.testFlag(Qt::Vertical))
  15696. {
  15697. for (int i=0; i<mRangeDragVertAxis.size(); ++i)
  15698. {
  15699. QCPAxis *ax = mRangeDragVertAxis.at(i).data();
  15700. if (!ax)
  15701. continue;
  15702. if (i >= mDragStartVertRange.size())
  15703. break;
  15704. if (ax->mScaleType == QCPAxis::stLinear)
  15705. {
  15706. double diff = ax->pixelToCoord(startPos.y()) - ax->pixelToCoord(event->pos().y());
  15707. ax->setRange(mDragStartVertRange.at(i).lower+diff, mDragStartVertRange.at(i).upper+diff);
  15708. } else if (ax->mScaleType == QCPAxis::stLogarithmic)
  15709. {
  15710. double diff = ax->pixelToCoord(startPos.y()) / ax->pixelToCoord(event->pos().y());
  15711. ax->setRange(mDragStartVertRange.at(i).lower*diff, mDragStartVertRange.at(i).upper*diff);
  15712. }
  15713. }
  15714. }
  15715. if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot
  15716. {
  15717. if (mParentPlot->noAntialiasingOnDrag())
  15718. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  15719. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  15720. }
  15721. }
  15722. }
  15723. /* inherits documentation from base class */
  15724. void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  15725. {
  15726. Q_UNUSED(event)
  15727. Q_UNUSED(startPos)
  15728. mDragging = false;
  15729. if (mParentPlot->noAntialiasingOnDrag())
  15730. {
  15731. mParentPlot->setAntialiasedElements(mAADragBackup);
  15732. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  15733. }
  15734. }
  15735. /*! \internal
  15736. Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
  15737. ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
  15738. the scaling operation is the current cursor position inside the axis rect. The scaling factor is
  15739. dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
  15740. zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
  15741. Note, that event->angleDelta() is usually +/-120 for single rotation steps. However, if the mouse
  15742. wheel is turned rapidly, many steps may bunch up to one event, so the delta may then be multiples
  15743. of 120. This is taken into account here, by calculating \a wheelSteps and using it as exponent of
  15744. the range zoom factor. This takes care of the wheel direction automatically, by inverting the
  15745. factor, when the wheel step is negative (f^-1 = 1/f).
  15746. */
  15747. void QCPAxisRect::wheelEvent(QWheelEvent *event)
  15748. {
  15749. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  15750. const double delta = event->delta();
  15751. #else
  15752. const double delta = event->angleDelta().y();
  15753. #endif
  15754. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  15755. const QPointF pos = event->pos();
  15756. #else
  15757. const QPointF pos = event->position();
  15758. #endif
  15759. // Mouse range zooming interaction:
  15760. if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  15761. {
  15762. if (mRangeZoom != 0)
  15763. {
  15764. double factor;
  15765. double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
  15766. if (mRangeZoom.testFlag(Qt::Horizontal))
  15767. {
  15768. factor = qPow(mRangeZoomFactorHorz, wheelSteps);
  15769. foreach (QPointer<QCPAxis> axis, mRangeZoomHorzAxis)
  15770. {
  15771. if (!axis.isNull())
  15772. axis->scaleRange(factor, axis->pixelToCoord(pos.x()));
  15773. }
  15774. }
  15775. if (mRangeZoom.testFlag(Qt::Vertical))
  15776. {
  15777. factor = qPow(mRangeZoomFactorVert, wheelSteps);
  15778. foreach (QPointer<QCPAxis> axis, mRangeZoomVertAxis)
  15779. {
  15780. if (!axis.isNull())
  15781. axis->scaleRange(factor, axis->pixelToCoord(pos.y()));
  15782. }
  15783. }
  15784. mParentPlot->replot();
  15785. }
  15786. }
  15787. }
  15788. /* end of 'src/layoutelements/layoutelement-axisrect.cpp' */
  15789. /* including file 'src/layoutelements/layoutelement-legend.cpp' */
  15790. /* modified 2021-03-29T02:30:44, size 31762 */
  15791. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15792. //////////////////// QCPAbstractLegendItem
  15793. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15794. /*! \class QCPAbstractLegendItem
  15795. \brief The abstract base class for all entries in a QCPLegend.
  15796. It defines a very basic interface for entries in a QCPLegend. For representing plottables in the
  15797. legend, the subclass \ref QCPPlottableLegendItem is more suitable.
  15798. Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry
  15799. that's not even associated with a plottable).
  15800. You must implement the following pure virtual functions:
  15801. \li \ref draw (from QCPLayerable)
  15802. You inherit the following members you may use:
  15803. <table>
  15804. <tr>
  15805. <td>QCPLegend *\b mParentLegend</td>
  15806. <td>A pointer to the parent QCPLegend.</td>
  15807. </tr><tr>
  15808. <td>QFont \b mFont</td>
  15809. <td>The generic font of the item. You should use this font for all or at least the most prominent text of the item.</td>
  15810. </tr>
  15811. </table>
  15812. */
  15813. /* start of documentation of signals */
  15814. /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected)
  15815. This signal is emitted when the selection state of this legend item has changed, either by user
  15816. interaction or by a direct call to \ref setSelected.
  15817. */
  15818. /* end of documentation of signals */
  15819. /*!
  15820. Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not
  15821. cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately.
  15822. */
  15823. QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) :
  15824. QCPLayoutElement(parent->parentPlot()),
  15825. mParentLegend(parent),
  15826. mFont(parent->font()),
  15827. mTextColor(parent->textColor()),
  15828. mSelectedFont(parent->selectedFont()),
  15829. mSelectedTextColor(parent->selectedTextColor()),
  15830. mSelectable(true),
  15831. mSelected(false)
  15832. {
  15833. setLayer(QLatin1String("legend"));
  15834. setMargins(QMargins(0, 0, 0, 0));
  15835. }
  15836. /*!
  15837. Sets the default font of this specific legend item to \a font.
  15838. \see setTextColor, QCPLegend::setFont
  15839. */
  15840. void QCPAbstractLegendItem::setFont(const QFont &font)
  15841. {
  15842. mFont = font;
  15843. }
  15844. /*!
  15845. Sets the default text color of this specific legend item to \a color.
  15846. \see setFont, QCPLegend::setTextColor
  15847. */
  15848. void QCPAbstractLegendItem::setTextColor(const QColor &color)
  15849. {
  15850. mTextColor = color;
  15851. }
  15852. /*!
  15853. When this legend item is selected, \a font is used to draw generic text, instead of the normal
  15854. font set with \ref setFont.
  15855. \see setFont, QCPLegend::setSelectedFont
  15856. */
  15857. void QCPAbstractLegendItem::setSelectedFont(const QFont &font)
  15858. {
  15859. mSelectedFont = font;
  15860. }
  15861. /*!
  15862. When this legend item is selected, \a color is used to draw generic text, instead of the normal
  15863. color set with \ref setTextColor.
  15864. \see setTextColor, QCPLegend::setSelectedTextColor
  15865. */
  15866. void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color)
  15867. {
  15868. mSelectedTextColor = color;
  15869. }
  15870. /*!
  15871. Sets whether this specific legend item is selectable.
  15872. \see setSelectedParts, QCustomPlot::setInteractions
  15873. */
  15874. void QCPAbstractLegendItem::setSelectable(bool selectable)
  15875. {
  15876. if (mSelectable != selectable)
  15877. {
  15878. mSelectable = selectable;
  15879. Q_EMIT selectableChanged(mSelectable);
  15880. }
  15881. }
  15882. /*!
  15883. Sets whether this specific legend item is selected.
  15884. It is possible to set the selection state of this item by calling this function directly, even if
  15885. setSelectable is set to false.
  15886. \see setSelectableParts, QCustomPlot::setInteractions
  15887. */
  15888. void QCPAbstractLegendItem::setSelected(bool selected)
  15889. {
  15890. if (mSelected != selected)
  15891. {
  15892. mSelected = selected;
  15893. Q_EMIT selectionChanged(mSelected);
  15894. }
  15895. }
  15896. /* inherits documentation from base class */
  15897. double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  15898. {
  15899. Q_UNUSED(details)
  15900. if (!mParentPlot) return -1;
  15901. if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems)))
  15902. return -1;
  15903. if (mRect.contains(pos.toPoint()))
  15904. return mParentPlot->selectionTolerance()*0.99;
  15905. else
  15906. return -1;
  15907. }
  15908. /* inherits documentation from base class */
  15909. void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
  15910. {
  15911. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems);
  15912. }
  15913. /* inherits documentation from base class */
  15914. QRect QCPAbstractLegendItem::clipRect() const
  15915. {
  15916. return mOuterRect;
  15917. }
  15918. /* inherits documentation from base class */
  15919. void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  15920. {
  15921. Q_UNUSED(event)
  15922. Q_UNUSED(details)
  15923. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
  15924. {
  15925. bool selBefore = mSelected;
  15926. setSelected(additive ? !mSelected : true);
  15927. if (selectionStateChanged)
  15928. *selectionStateChanged = mSelected != selBefore;
  15929. }
  15930. }
  15931. /* inherits documentation from base class */
  15932. void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged)
  15933. {
  15934. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
  15935. {
  15936. bool selBefore = mSelected;
  15937. setSelected(false);
  15938. if (selectionStateChanged)
  15939. *selectionStateChanged = mSelected != selBefore;
  15940. }
  15941. }
  15942. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15943. //////////////////// QCPPlottableLegendItem
  15944. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15945. /*! \class QCPPlottableLegendItem
  15946. \brief A legend item representing a plottable with an icon and the plottable name.
  15947. This is the standard legend item for plottables. It displays an icon of the plottable next to the
  15948. plottable name. The icon is drawn by the respective plottable itself (\ref
  15949. QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable.
  15950. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the
  15951. middle.
  15952. Legend items of this type are always associated with one plottable (retrievable via the
  15953. plottable() function and settable with the constructor). You may change the font of the plottable
  15954. name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref
  15955. QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding.
  15956. The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend
  15957. creates/removes legend items of this type.
  15958. Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of
  15959. QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout
  15960. interface, QCPLegend has specialized functions for handling legend items conveniently, see the
  15961. documentation of \ref QCPLegend.
  15962. */
  15963. /*!
  15964. Creates a new legend item associated with \a plottable.
  15965. Once it's created, it can be added to the legend via \ref QCPLegend::addItem.
  15966. A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref
  15967. QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend.
  15968. */
  15969. QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) :
  15970. QCPAbstractLegendItem(parent),
  15971. mPlottable(plottable)
  15972. {
  15973. setAntialiased(false);
  15974. }
  15975. /*! \internal
  15976. Returns the pen that shall be used to draw the icon border, taking into account the selection
  15977. state of this item.
  15978. */
  15979. QPen QCPPlottableLegendItem::getIconBorderPen() const
  15980. {
  15981. return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
  15982. }
  15983. /*! \internal
  15984. Returns the text color that shall be used to draw text, taking into account the selection state
  15985. of this item.
  15986. */
  15987. QColor QCPPlottableLegendItem::getTextColor() const
  15988. {
  15989. return mSelected ? mSelectedTextColor : mTextColor;
  15990. }
  15991. /*! \internal
  15992. Returns the font that shall be used to draw text, taking into account the selection state of this
  15993. item.
  15994. */
  15995. QFont QCPPlottableLegendItem::getFont() const
  15996. {
  15997. return mSelected ? mSelectedFont : mFont;
  15998. }
  15999. /*! \internal
  16000. Draws the item with \a painter. The size and position of the drawn legend item is defined by the
  16001. parent layout (typically a \ref QCPLegend) and the \ref minimumOuterSizeHint and \ref
  16002. maximumOuterSizeHint of this legend item.
  16003. */
  16004. void QCPPlottableLegendItem::draw(QCPPainter *painter)
  16005. {
  16006. if (!mPlottable) return;
  16007. painter->setFont(getFont());
  16008. painter->setPen(QPen(getTextColor()));
  16009. QSize iconSize = mParentLegend->iconSize();
  16010. QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  16011. QRect iconRect(mRect.topLeft(), iconSize);
  16012. int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
  16013. painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name());
  16014. // draw icon:
  16015. painter->save();
  16016. painter->setClipRect(iconRect, Qt::IntersectClip);
  16017. mPlottable->drawLegendIcon(painter, iconRect);
  16018. painter->restore();
  16019. // draw icon border:
  16020. if (getIconBorderPen().style() != Qt::NoPen)
  16021. {
  16022. painter->setPen(getIconBorderPen());
  16023. painter->setBrush(Qt::NoBrush);
  16024. int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
  16025. painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
  16026. painter->drawRect(iconRect);
  16027. }
  16028. }
  16029. /*! \internal
  16030. Calculates and returns the size of this item. This includes the icon, the text and the padding in
  16031. between.
  16032. \seebaseclassmethod
  16033. */
  16034. QSize QCPPlottableLegendItem::minimumOuterSizeHint() const
  16035. {
  16036. if (!mPlottable) return {};
  16037. QSize result(0, 0);
  16038. QRect textRect;
  16039. QFontMetrics fontMetrics(getFont());
  16040. QSize iconSize = mParentLegend->iconSize();
  16041. textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  16042. result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width());
  16043. result.setHeight(qMax(textRect.height(), iconSize.height()));
  16044. result.rwidth() += mMargins.left()+mMargins.right();
  16045. result.rheight() += mMargins.top()+mMargins.bottom();
  16046. return result;
  16047. }
  16048. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16049. //////////////////// QCPLegend
  16050. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16051. /*! \class QCPLegend
  16052. \brief Manages a legend inside a QCustomPlot.
  16053. A legend is a small box somewhere in the plot which lists plottables with their name and icon.
  16054. A legend is populated with legend items by calling \ref QCPAbstractPlottable::addToLegend on the
  16055. plottable, for which a legend item shall be created. In the case of the main legend (\ref
  16056. QCustomPlot::legend), simply adding plottables to the plot while \ref
  16057. QCustomPlot::setAutoAddPlottableToLegend is set to true (the default) creates corresponding
  16058. legend items. The legend item associated with a certain plottable can be removed with \ref
  16059. QCPAbstractPlottable::removeFromLegend. However, QCPLegend also offers an interface to add and
  16060. manipulate legend items directly: \ref item, \ref itemWithPlottable, \ref itemCount, \ref
  16061. addItem, \ref removeItem, etc.
  16062. Since \ref QCPLegend derives from \ref QCPLayoutGrid, it can be placed in any position a \ref
  16063. QCPLayoutElement may be positioned. The legend items are themselves \ref QCPLayoutElement
  16064. "QCPLayoutElements" which are placed in the grid layout of the legend. \ref QCPLegend only adds
  16065. an interface specialized for handling child elements of type \ref QCPAbstractLegendItem, as
  16066. mentioned above. In principle, any other layout elements may also be added to a legend via the
  16067. normal \ref QCPLayoutGrid interface. See the special page about \link thelayoutsystem The Layout
  16068. System\endlink for examples on how to add other elements to the legend and move it outside the axis
  16069. rect.
  16070. Use the methods \ref setFillOrder and \ref setWrap inherited from \ref QCPLayoutGrid to control
  16071. in which order (column first or row first) the legend is filled up when calling \ref addItem, and
  16072. at which column or row wrapping occurs. The default fill order for legends is \ref foRowsFirst.
  16073. By default, every QCustomPlot has one legend (\ref QCustomPlot::legend) which is placed in the
  16074. inset layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
  16075. position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend
  16076. outside of the axis rect, place it anywhere else with the \ref QCPLayout/\ref QCPLayoutElement
  16077. interface.
  16078. */
  16079. /* start of documentation of signals */
  16080. /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection);
  16081. This signal is emitted when the selection state of this legend has changed.
  16082. \see setSelectedParts, setSelectableParts
  16083. */
  16084. /* end of documentation of signals */
  16085. /*!
  16086. Constructs a new QCPLegend instance with default values.
  16087. Note that by default, QCustomPlot already contains a legend ready to be used as \ref
  16088. QCustomPlot::legend
  16089. */
  16090. QCPLegend::QCPLegend() :
  16091. mIconTextPadding{}
  16092. {
  16093. setFillOrder(QCPLayoutGrid::foRowsFirst);
  16094. setWrap(0);
  16095. setRowSpacing(3);
  16096. setColumnSpacing(8);
  16097. setMargins(QMargins(7, 5, 7, 4));
  16098. setAntialiased(false);
  16099. setIconSize(32, 18);
  16100. setIconTextPadding(7);
  16101. setSelectableParts(spLegendBox | spItems);
  16102. setSelectedParts(spNone);
  16103. setBorderPen(QPen(Qt::black, 0));
  16104. setSelectedBorderPen(QPen(Qt::blue, 2));
  16105. setIconBorderPen(Qt::NoPen);
  16106. setSelectedIconBorderPen(QPen(Qt::blue, 2));
  16107. setBrush(Qt::white);
  16108. setSelectedBrush(Qt::white);
  16109. setTextColor(Qt::black);
  16110. setSelectedTextColor(Qt::blue);
  16111. }
  16112. QCPLegend::~QCPLegend()
  16113. {
  16114. clearItems();
  16115. if (qobject_cast<QCustomPlot*>(mParentPlot)) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot)
  16116. mParentPlot->legendRemoved(this);
  16117. }
  16118. /* no doc for getter, see setSelectedParts */
  16119. QCPLegend::SelectableParts QCPLegend::selectedParts() const
  16120. {
  16121. // check whether any legend elements selected, if yes, add spItems to return value
  16122. bool hasSelectedItems = false;
  16123. for (int i=0; i<itemCount(); ++i)
  16124. {
  16125. if (item(i) && item(i)->selected())
  16126. {
  16127. hasSelectedItems = true;
  16128. break;
  16129. }
  16130. }
  16131. if (hasSelectedItems)
  16132. return mSelectedParts | spItems;
  16133. else
  16134. return mSelectedParts & ~spItems;
  16135. }
  16136. /*!
  16137. Sets the pen, the border of the entire legend is drawn with.
  16138. */
  16139. void QCPLegend::setBorderPen(const QPen &pen)
  16140. {
  16141. mBorderPen = pen;
  16142. }
  16143. /*!
  16144. Sets the brush of the legend background.
  16145. */
  16146. void QCPLegend::setBrush(const QBrush &brush)
  16147. {
  16148. mBrush = brush;
  16149. }
  16150. /*!
  16151. Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will
  16152. use this font by default. However, a different font can be specified on a per-item-basis by
  16153. accessing the specific legend item.
  16154. This function will also set \a font on all already existing legend items.
  16155. \see QCPAbstractLegendItem::setFont
  16156. */
  16157. void QCPLegend::setFont(const QFont &font)
  16158. {
  16159. mFont = font;
  16160. for (int i=0; i<itemCount(); ++i)
  16161. {
  16162. if (item(i))
  16163. item(i)->setFont(mFont);
  16164. }
  16165. }
  16166. /*!
  16167. Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph)
  16168. will use this color by default. However, a different colors can be specified on a per-item-basis
  16169. by accessing the specific legend item.
  16170. This function will also set \a color on all already existing legend items.
  16171. \see QCPAbstractLegendItem::setTextColor
  16172. */
  16173. void QCPLegend::setTextColor(const QColor &color)
  16174. {
  16175. mTextColor = color;
  16176. for (int i=0; i<itemCount(); ++i)
  16177. {
  16178. if (item(i))
  16179. item(i)->setTextColor(color);
  16180. }
  16181. }
  16182. /*!
  16183. Sets the size of legend icons. Legend items that draw an icon (e.g. a visual
  16184. representation of the graph) will use this size by default.
  16185. */
  16186. void QCPLegend::setIconSize(const QSize &size)
  16187. {
  16188. mIconSize = size;
  16189. }
  16190. /*! \overload
  16191. */
  16192. void QCPLegend::setIconSize(int width, int height)
  16193. {
  16194. mIconSize.setWidth(width);
  16195. mIconSize.setHeight(height);
  16196. }
  16197. /*!
  16198. Sets the horizontal space in pixels between the legend icon and the text next to it.
  16199. Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the
  16200. name of the graph) will use this space by default.
  16201. */
  16202. void QCPLegend::setIconTextPadding(int padding)
  16203. {
  16204. mIconTextPadding = padding;
  16205. }
  16206. /*!
  16207. Sets the pen used to draw a border around each legend icon. Legend items that draw an
  16208. icon (e.g. a visual representation of the graph) will use this pen by default.
  16209. If no border is wanted, set this to \a Qt::NoPen.
  16210. */
  16211. void QCPLegend::setIconBorderPen(const QPen &pen)
  16212. {
  16213. mIconBorderPen = pen;
  16214. }
  16215. /*!
  16216. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  16217. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.)
  16218. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  16219. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  16220. directly.
  16221. \see SelectablePart, setSelectedParts
  16222. */
  16223. void QCPLegend::setSelectableParts(const SelectableParts &selectable)
  16224. {
  16225. if (mSelectableParts != selectable)
  16226. {
  16227. mSelectableParts = selectable;
  16228. Q_EMIT selectableChanged(mSelectableParts);
  16229. }
  16230. }
  16231. /*!
  16232. Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part
  16233. is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected
  16234. doesn't contain \ref spItems, those items become deselected.
  16235. The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions
  16236. contains iSelectLegend. You only need to call this function when you wish to change the selection
  16237. state manually.
  16238. This function can change the selection state of a part even when \ref setSelectableParts was set to a
  16239. value that actually excludes the part.
  16240. Q_EMITs the \ref selectionChanged signal when \a selected is different from the previous selection state.
  16241. Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set
  16242. before, because there's no way to specify which exact items to newly select. Do this by calling
  16243. \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select.
  16244. \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush,
  16245. setSelectedFont
  16246. */
  16247. void QCPLegend::setSelectedParts(const SelectableParts &selected)
  16248. {
  16249. SelectableParts newSelected = selected;
  16250. mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed
  16251. if (mSelectedParts != newSelected)
  16252. {
  16253. if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that)
  16254. {
  16255. qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function";
  16256. newSelected &= ~spItems;
  16257. }
  16258. if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection
  16259. {
  16260. for (int i=0; i<itemCount(); ++i)
  16261. {
  16262. if (item(i))
  16263. item(i)->setSelected(false);
  16264. }
  16265. }
  16266. mSelectedParts = newSelected;
  16267. Q_EMIT selectionChanged(mSelectedParts);
  16268. }
  16269. }
  16270. /*!
  16271. When the legend box is selected, this pen is used to draw the border instead of the normal pen
  16272. set via \ref setBorderPen.
  16273. \see setSelectedParts, setSelectableParts, setSelectedBrush
  16274. */
  16275. void QCPLegend::setSelectedBorderPen(const QPen &pen)
  16276. {
  16277. mSelectedBorderPen = pen;
  16278. }
  16279. /*!
  16280. Sets the pen legend items will use to draw their icon borders, when they are selected.
  16281. \see setSelectedParts, setSelectableParts, setSelectedFont
  16282. */
  16283. void QCPLegend::setSelectedIconBorderPen(const QPen &pen)
  16284. {
  16285. mSelectedIconBorderPen = pen;
  16286. }
  16287. /*!
  16288. When the legend box is selected, this brush is used to draw the legend background instead of the normal brush
  16289. set via \ref setBrush.
  16290. \see setSelectedParts, setSelectableParts, setSelectedBorderPen
  16291. */
  16292. void QCPLegend::setSelectedBrush(const QBrush &brush)
  16293. {
  16294. mSelectedBrush = brush;
  16295. }
  16296. /*!
  16297. Sets the default font that is used by legend items when they are selected.
  16298. This function will also set \a font on all already existing legend items.
  16299. \see setFont, QCPAbstractLegendItem::setSelectedFont
  16300. */
  16301. void QCPLegend::setSelectedFont(const QFont &font)
  16302. {
  16303. mSelectedFont = font;
  16304. for (int i=0; i<itemCount(); ++i)
  16305. {
  16306. if (item(i))
  16307. item(i)->setSelectedFont(font);
  16308. }
  16309. }
  16310. /*!
  16311. Sets the default text color that is used by legend items when they are selected.
  16312. This function will also set \a color on all already existing legend items.
  16313. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor
  16314. */
  16315. void QCPLegend::setSelectedTextColor(const QColor &color)
  16316. {
  16317. mSelectedTextColor = color;
  16318. for (int i=0; i<itemCount(); ++i)
  16319. {
  16320. if (item(i))
  16321. item(i)->setSelectedTextColor(color);
  16322. }
  16323. }
  16324. /*!
  16325. Returns the item with index \a i. If non-legend items were added to the legend, and the element
  16326. at the specified cell index is not a QCPAbstractLegendItem, returns \c nullptr.
  16327. Note that the linear index depends on the current fill order (\ref setFillOrder).
  16328. \see itemCount, addItem, itemWithPlottable
  16329. */
  16330. QCPAbstractLegendItem *QCPLegend::item(int index) const
  16331. {
  16332. return qobject_cast<QCPAbstractLegendItem*>(elementAt(index));
  16333. }
  16334. /*!
  16335. Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  16336. If such an item isn't in the legend, returns \c nullptr.
  16337. \see hasItemWithPlottable
  16338. */
  16339. QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const
  16340. {
  16341. for (int i=0; i<itemCount(); ++i)
  16342. {
  16343. if (QCPPlottableLegendItem *pli = qobject_cast<QCPPlottableLegendItem*>(item(i)))
  16344. {
  16345. if (pli->plottable() == plottable)
  16346. return pli;
  16347. }
  16348. }
  16349. return nullptr;
  16350. }
  16351. /*!
  16352. Returns the number of items currently in the legend. It is identical to the base class
  16353. QCPLayoutGrid::elementCount(), and unlike the other "item" interface methods of QCPLegend,
  16354. doesn't only address elements which can be cast to QCPAbstractLegendItem.
  16355. Note that if empty cells are in the legend (e.g. by calling methods of the \ref QCPLayoutGrid
  16356. base class which allows creating empty cells), they are included in the returned count.
  16357. \see item
  16358. */
  16359. int QCPLegend::itemCount() const
  16360. {
  16361. return elementCount();
  16362. }
  16363. /*!
  16364. Returns whether the legend contains \a item.
  16365. \see hasItemWithPlottable
  16366. */
  16367. bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const
  16368. {
  16369. for (int i=0; i<itemCount(); ++i)
  16370. {
  16371. if (item == this->item(i))
  16372. return true;
  16373. }
  16374. return false;
  16375. }
  16376. /*!
  16377. Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  16378. If such an item isn't in the legend, returns false.
  16379. \see itemWithPlottable
  16380. */
  16381. bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const
  16382. {
  16383. return itemWithPlottable(plottable);
  16384. }
  16385. /*!
  16386. Adds \a item to the legend, if it's not present already. The element is arranged according to the
  16387. current fill order (\ref setFillOrder) and wrapping (\ref setWrap).
  16388. Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added.
  16389. The legend takes ownership of the item.
  16390. \see removeItem, item, hasItem
  16391. */
  16392. bool QCPLegend::addItem(QCPAbstractLegendItem *item)
  16393. {
  16394. return addElement(item);
  16395. }
  16396. /*! \overload
  16397. Removes the item with the specified \a index from the legend and deletes it.
  16398. After successful removal, the legend is reordered according to the current fill order (\ref
  16399. setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
  16400. was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
  16401. Returns true, if successful. Unlike \ref QCPLayoutGrid::removeAt, this method only removes
  16402. elements derived from \ref QCPAbstractLegendItem.
  16403. \see itemCount, clearItems
  16404. */
  16405. bool QCPLegend::removeItem(int index)
  16406. {
  16407. if (QCPAbstractLegendItem *ali = item(index))
  16408. {
  16409. bool success = remove(ali);
  16410. if (success)
  16411. setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
  16412. return success;
  16413. } else
  16414. return false;
  16415. }
  16416. /*! \overload
  16417. Removes \a item from the legend and deletes it.
  16418. After successful removal, the legend is reordered according to the current fill order (\ref
  16419. setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
  16420. was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
  16421. Returns true, if successful.
  16422. \see clearItems
  16423. */
  16424. bool QCPLegend::removeItem(QCPAbstractLegendItem *item)
  16425. {
  16426. bool success = remove(item);
  16427. if (success)
  16428. setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
  16429. return success;
  16430. }
  16431. /*!
  16432. Removes all items from the legend.
  16433. */
  16434. void QCPLegend::clearItems()
  16435. {
  16436. for (int i=elementCount()-1; i>=0; --i)
  16437. {
  16438. if (item(i))
  16439. removeAt(i); // don't use removeItem() because it would unnecessarily reorder the whole legend for each item
  16440. }
  16441. setFillOrder(fillOrder(), true); // get rid of empty cells by reordering once after all items are removed
  16442. }
  16443. /*!
  16444. Returns the legend items that are currently selected. If no items are selected,
  16445. the list is empty.
  16446. \see QCPAbstractLegendItem::setSelected, setSelectable
  16447. */
  16448. QList<QCPAbstractLegendItem *> QCPLegend::selectedItems() const
  16449. {
  16450. QList<QCPAbstractLegendItem*> result;
  16451. for (int i=0; i<itemCount(); ++i)
  16452. {
  16453. if (QCPAbstractLegendItem *ali = item(i))
  16454. {
  16455. if (ali->selected())
  16456. result.append(ali);
  16457. }
  16458. }
  16459. return result;
  16460. }
  16461. /*! \internal
  16462. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  16463. before drawing main legend elements.
  16464. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  16465. This function takes into account the local setting of the antialiasing flag as well as the
  16466. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  16467. QCustomPlot::setNotAntialiasedElements.
  16468. \seebaseclassmethod
  16469. \see setAntialiased
  16470. */
  16471. void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const
  16472. {
  16473. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend);
  16474. }
  16475. /*! \internal
  16476. Returns the pen used to paint the border of the legend, taking into account the selection state
  16477. of the legend box.
  16478. */
  16479. QPen QCPLegend::getBorderPen() const
  16480. {
  16481. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen;
  16482. }
  16483. /*! \internal
  16484. Returns the brush used to paint the background of the legend, taking into account the selection
  16485. state of the legend box.
  16486. */
  16487. QBrush QCPLegend::getBrush() const
  16488. {
  16489. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush;
  16490. }
  16491. /*! \internal
  16492. Draws the legend box with the provided \a painter. The individual legend items are layerables
  16493. themselves, thus are drawn independently.
  16494. */
  16495. void QCPLegend::draw(QCPPainter *painter)
  16496. {
  16497. // draw background rect:
  16498. painter->setBrush(getBrush());
  16499. painter->setPen(getBorderPen());
  16500. painter->drawRect(mOuterRect);
  16501. }
  16502. /* inherits documentation from base class */
  16503. double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16504. {
  16505. if (!mParentPlot) return -1;
  16506. if (onlySelectable && !mSelectableParts.testFlag(spLegendBox))
  16507. return -1;
  16508. if (mOuterRect.contains(pos.toPoint()))
  16509. {
  16510. if (details) details->setValue(spLegendBox);
  16511. return mParentPlot->selectionTolerance()*0.99;
  16512. }
  16513. return -1;
  16514. }
  16515. /* inherits documentation from base class */
  16516. void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  16517. {
  16518. Q_UNUSED(event)
  16519. mSelectedParts = selectedParts(); // in case item selection has changed
  16520. if (details.value<SelectablePart>() == spLegendBox && mSelectableParts.testFlag(spLegendBox))
  16521. {
  16522. SelectableParts selBefore = mSelectedParts;
  16523. setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent)
  16524. if (selectionStateChanged)
  16525. *selectionStateChanged = mSelectedParts != selBefore;
  16526. }
  16527. }
  16528. /* inherits documentation from base class */
  16529. void QCPLegend::deselectEvent(bool *selectionStateChanged)
  16530. {
  16531. mSelectedParts = selectedParts(); // in case item selection has changed
  16532. if (mSelectableParts.testFlag(spLegendBox))
  16533. {
  16534. SelectableParts selBefore = mSelectedParts;
  16535. setSelectedParts(selectedParts() & ~spLegendBox);
  16536. if (selectionStateChanged)
  16537. *selectionStateChanged = mSelectedParts != selBefore;
  16538. }
  16539. }
  16540. /* inherits documentation from base class */
  16541. QCP::Interaction QCPLegend::selectionCategory() const
  16542. {
  16543. return QCP::iSelectLegend;
  16544. }
  16545. /* inherits documentation from base class */
  16546. QCP::Interaction QCPAbstractLegendItem::selectionCategory() const
  16547. {
  16548. return QCP::iSelectLegend;
  16549. }
  16550. /* inherits documentation from base class */
  16551. void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot)
  16552. {
  16553. if (parentPlot && !parentPlot->legend)
  16554. parentPlot->legend = this;
  16555. }
  16556. /* end of 'src/layoutelements/layoutelement-legend.cpp' */
  16557. /* including file 'src/layoutelements/layoutelement-textelement.cpp' */
  16558. /* modified 2021-03-29T02:30:44, size 12925 */
  16559. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16560. //////////////////// QCPTextElement
  16561. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16562. /*! \class QCPTextElement
  16563. \brief A layout element displaying a text
  16564. The text may be specified with \ref setText, the formatting can be controlled with \ref setFont,
  16565. \ref setTextColor, and \ref setTextFlags.
  16566. A text element can be added as follows:
  16567. \snippet documentation/doc-code-snippets/mainwindow.cpp qcptextelement-creation
  16568. */
  16569. /* start documentation of signals */
  16570. /*! \fn void QCPTextElement::selectionChanged(bool selected)
  16571. This signal is emitted when the selection state has changed to \a selected, either by user
  16572. interaction or by a direct call to \ref setSelected.
  16573. \see setSelected, setSelectable
  16574. */
  16575. /*! \fn void QCPTextElement::clicked(QMouseEvent *event)
  16576. This signal is emitted when the text element is clicked.
  16577. \see doubleClicked, selectTest
  16578. */
  16579. /*! \fn void QCPTextElement::doubleClicked(QMouseEvent *event)
  16580. This signal is emitted when the text element is double clicked.
  16581. \see clicked, selectTest
  16582. */
  16583. /* end documentation of signals */
  16584. /*! \overload
  16585. Creates a new QCPTextElement instance and sets default values. The initial text is empty (\ref
  16586. setText).
  16587. */
  16588. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot) :
  16589. QCPLayoutElement(parentPlot),
  16590. mText(),
  16591. mTextFlags(Qt::AlignCenter),
  16592. mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16593. mTextColor(Qt::black),
  16594. mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16595. mSelectedTextColor(Qt::blue),
  16596. mSelectable(false),
  16597. mSelected(false)
  16598. {
  16599. if (parentPlot)
  16600. {
  16601. mFont = parentPlot->font();
  16602. mSelectedFont = parentPlot->font();
  16603. }
  16604. setMargins(QMargins(2, 2, 2, 2));
  16605. }
  16606. /*! \overload
  16607. Creates a new QCPTextElement instance and sets default values.
  16608. The initial text is set to \a text.
  16609. */
  16610. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text) :
  16611. QCPLayoutElement(parentPlot),
  16612. mText(text),
  16613. mTextFlags(Qt::AlignCenter),
  16614. mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16615. mTextColor(Qt::black),
  16616. mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16617. mSelectedTextColor(Qt::blue),
  16618. mSelectable(false),
  16619. mSelected(false)
  16620. {
  16621. if (parentPlot)
  16622. {
  16623. mFont = parentPlot->font();
  16624. mSelectedFont = parentPlot->font();
  16625. }
  16626. setMargins(QMargins(2, 2, 2, 2));
  16627. }
  16628. /*! \overload
  16629. Creates a new QCPTextElement instance and sets default values.
  16630. The initial text is set to \a text with \a pointSize.
  16631. */
  16632. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, double pointSize) :
  16633. QCPLayoutElement(parentPlot),
  16634. mText(text),
  16635. mTextFlags(Qt::AlignCenter),
  16636. mFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below
  16637. mTextColor(Qt::black),
  16638. mSelectedFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below
  16639. mSelectedTextColor(Qt::blue),
  16640. mSelectable(false),
  16641. mSelected(false)
  16642. {
  16643. mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer
  16644. if (parentPlot)
  16645. {
  16646. mFont = parentPlot->font();
  16647. mFont.setPointSizeF(pointSize);
  16648. mSelectedFont = parentPlot->font();
  16649. mSelectedFont.setPointSizeF(pointSize);
  16650. }
  16651. setMargins(QMargins(2, 2, 2, 2));
  16652. }
  16653. /*! \overload
  16654. Creates a new QCPTextElement instance and sets default values.
  16655. The initial text is set to \a text with \a pointSize and the specified \a fontFamily.
  16656. */
  16657. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QString &fontFamily, double pointSize) :
  16658. QCPLayoutElement(parentPlot),
  16659. mText(text),
  16660. mTextFlags(Qt::AlignCenter),
  16661. mFont(QFont(fontFamily, int(pointSize))),
  16662. mTextColor(Qt::black),
  16663. mSelectedFont(QFont(fontFamily, int(pointSize))),
  16664. mSelectedTextColor(Qt::blue),
  16665. mSelectable(false),
  16666. mSelected(false)
  16667. {
  16668. mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer
  16669. setMargins(QMargins(2, 2, 2, 2));
  16670. }
  16671. /*! \overload
  16672. Creates a new QCPTextElement instance and sets default values.
  16673. The initial text is set to \a text with the specified \a font.
  16674. */
  16675. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QFont &font) :
  16676. QCPLayoutElement(parentPlot),
  16677. mText(text),
  16678. mTextFlags(Qt::AlignCenter),
  16679. mFont(font),
  16680. mTextColor(Qt::black),
  16681. mSelectedFont(font),
  16682. mSelectedTextColor(Qt::blue),
  16683. mSelectable(false),
  16684. mSelected(false)
  16685. {
  16686. setMargins(QMargins(2, 2, 2, 2));
  16687. }
  16688. /*!
  16689. Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n".
  16690. \see setFont, setTextColor, setTextFlags
  16691. */
  16692. void QCPTextElement::setText(const QString &text)
  16693. {
  16694. mText = text;
  16695. }
  16696. /*!
  16697. Sets options for text alignment and wrapping behaviour. \a flags is a bitwise OR-combination of
  16698. \c Qt::AlignmentFlag and \c Qt::TextFlag enums.
  16699. Possible enums are:
  16700. - Qt::AlignLeft
  16701. - Qt::AlignRight
  16702. - Qt::AlignHCenter
  16703. - Qt::AlignJustify
  16704. - Qt::AlignTop
  16705. - Qt::AlignBottom
  16706. - Qt::AlignVCenter
  16707. - Qt::AlignCenter
  16708. - Qt::TextDontClip
  16709. - Qt::TextSingleLine
  16710. - Qt::TextExpandTabs
  16711. - Qt::TextShowMnemonic
  16712. - Qt::TextWordWrap
  16713. - Qt::TextIncludeTrailingSpaces
  16714. */
  16715. void QCPTextElement::setTextFlags(int flags)
  16716. {
  16717. mTextFlags = flags;
  16718. }
  16719. /*!
  16720. Sets the \a font of the text.
  16721. \see setTextColor, setSelectedFont
  16722. */
  16723. void QCPTextElement::setFont(const QFont &font)
  16724. {
  16725. mFont = font;
  16726. }
  16727. /*!
  16728. Sets the \a color of the text.
  16729. \see setFont, setSelectedTextColor
  16730. */
  16731. void QCPTextElement::setTextColor(const QColor &color)
  16732. {
  16733. mTextColor = color;
  16734. }
  16735. /*!
  16736. Sets the \a font of the text that will be used if the text element is selected (\ref setSelected).
  16737. \see setFont
  16738. */
  16739. void QCPTextElement::setSelectedFont(const QFont &font)
  16740. {
  16741. mSelectedFont = font;
  16742. }
  16743. /*!
  16744. Sets the \a color of the text that will be used if the text element is selected (\ref setSelected).
  16745. \see setTextColor
  16746. */
  16747. void QCPTextElement::setSelectedTextColor(const QColor &color)
  16748. {
  16749. mSelectedTextColor = color;
  16750. }
  16751. /*!
  16752. Sets whether the user may select this text element.
  16753. Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed
  16754. programmatically via \ref setSelected.
  16755. */
  16756. void QCPTextElement::setSelectable(bool selectable)
  16757. {
  16758. if (mSelectable != selectable)
  16759. {
  16760. mSelectable = selectable;
  16761. Q_EMIT selectableChanged(mSelectable);
  16762. }
  16763. }
  16764. /*!
  16765. Sets the selection state of this text element to \a selected. If the selection has changed, \ref
  16766. selectionChanged is emitted.
  16767. Note that this function can change the selection state independently of the current \ref
  16768. setSelectable state.
  16769. */
  16770. void QCPTextElement::setSelected(bool selected)
  16771. {
  16772. if (mSelected != selected)
  16773. {
  16774. mSelected = selected;
  16775. Q_EMIT selectionChanged(mSelected);
  16776. }
  16777. }
  16778. /* inherits documentation from base class */
  16779. void QCPTextElement::applyDefaultAntialiasingHint(QCPPainter *painter) const
  16780. {
  16781. applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
  16782. }
  16783. /* inherits documentation from base class */
  16784. void QCPTextElement::draw(QCPPainter *painter)
  16785. {
  16786. painter->setFont(mainFont());
  16787. painter->setPen(QPen(mainTextColor()));
  16788. painter->drawText(mRect, mTextFlags, mText, &mTextBoundingRect);
  16789. }
  16790. /* inherits documentation from base class */
  16791. QSize QCPTextElement::minimumOuterSizeHint() const
  16792. {
  16793. QFontMetrics metrics(mFont);
  16794. QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size());
  16795. result.rwidth() += mMargins.left()+mMargins.right();
  16796. result.rheight() += mMargins.top()+mMargins.bottom();
  16797. return result;
  16798. }
  16799. /* inherits documentation from base class */
  16800. QSize QCPTextElement::maximumOuterSizeHint() const
  16801. {
  16802. QFontMetrics metrics(mFont);
  16803. QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size());
  16804. result.setWidth(QWIDGETSIZE_MAX);
  16805. result.rheight() += mMargins.top()+mMargins.bottom();
  16806. return result;
  16807. }
  16808. /* inherits documentation from base class */
  16809. void QCPTextElement::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  16810. {
  16811. Q_UNUSED(event)
  16812. Q_UNUSED(details)
  16813. if (mSelectable)
  16814. {
  16815. bool selBefore = mSelected;
  16816. setSelected(additive ? !mSelected : true);
  16817. if (selectionStateChanged)
  16818. *selectionStateChanged = mSelected != selBefore;
  16819. }
  16820. }
  16821. /* inherits documentation from base class */
  16822. void QCPTextElement::deselectEvent(bool *selectionStateChanged)
  16823. {
  16824. if (mSelectable)
  16825. {
  16826. bool selBefore = mSelected;
  16827. setSelected(false);
  16828. if (selectionStateChanged)
  16829. *selectionStateChanged = mSelected != selBefore;
  16830. }
  16831. }
  16832. /*!
  16833. Returns 0.99*selectionTolerance (see \ref QCustomPlot::setSelectionTolerance) when \a pos is
  16834. within the bounding box of the text element's text. Note that this bounding box is updated in the
  16835. draw call.
  16836. If \a pos is outside the text's bounding box or if \a onlySelectable is true and this text
  16837. element is not selectable (\ref setSelectable), returns -1.
  16838. \seebaseclassmethod
  16839. */
  16840. double QCPTextElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16841. {
  16842. Q_UNUSED(details)
  16843. if (onlySelectable && !mSelectable)
  16844. return -1;
  16845. if (mTextBoundingRect.contains(pos.toPoint()))
  16846. return mParentPlot->selectionTolerance()*0.99;
  16847. else
  16848. return -1;
  16849. }
  16850. /*!
  16851. Accepts the mouse event in order to emit the according click signal in the \ref
  16852. mouseReleaseEvent.
  16853. \seebaseclassmethod
  16854. */
  16855. void QCPTextElement::mousePressEvent(QMouseEvent *event, const QVariant &details)
  16856. {
  16857. Q_UNUSED(details)
  16858. event->accept();
  16859. }
  16860. /*!
  16861. Emits the \ref clicked signal if the cursor hasn't moved by more than a few pixels since the \ref
  16862. mousePressEvent.
  16863. \seebaseclassmethod
  16864. */
  16865. void QCPTextElement::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  16866. {
  16867. if ((QPointF(event->pos())-startPos).manhattanLength() <= 3)
  16868. Q_EMIT clicked(event);
  16869. }
  16870. /*!
  16871. Emits the \ref doubleClicked signal.
  16872. \seebaseclassmethod
  16873. */
  16874. void QCPTextElement::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
  16875. {
  16876. Q_UNUSED(details)
  16877. Q_EMIT doubleClicked(event);
  16878. }
  16879. /*! \internal
  16880. Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to
  16881. <tt>true</tt>, else mFont is returned.
  16882. */
  16883. QFont QCPTextElement::mainFont() const
  16884. {
  16885. return mSelected ? mSelectedFont : mFont;
  16886. }
  16887. /*! \internal
  16888. Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to
  16889. <tt>true</tt>, else mTextColor is returned.
  16890. */
  16891. QColor QCPTextElement::mainTextColor() const
  16892. {
  16893. return mSelected ? mSelectedTextColor : mTextColor;
  16894. }
  16895. /* end of 'src/layoutelements/layoutelement-textelement.cpp' */
  16896. /* including file 'src/layoutelements/layoutelement-colorscale.cpp' */
  16897. /* modified 2021-03-29T02:30:44, size 26531 */
  16898. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16899. //////////////////// QCPColorScale
  16900. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16901. /*! \class QCPColorScale
  16902. \brief A color scale for use with color coding data such as QCPColorMap
  16903. This layout element can be placed on the plot to correlate a color gradient with data values. It
  16904. is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps".
  16905. \image html QCPColorScale.png
  16906. The color scale can be either horizontal or vertical, as shown in the image above. The
  16907. orientation and the side where the numbers appear is controlled with \ref setType.
  16908. Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are
  16909. connected, they share their gradient, data range and data scale type (\ref setGradient, \ref
  16910. setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color
  16911. scale, to make them all synchronize these properties.
  16912. To have finer control over the number display and axis behaviour, you can directly access the
  16913. \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if
  16914. you want to change the number of automatically generated ticks, call
  16915. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-tickcount
  16916. Placing a color scale next to the main axis rect works like with any other layout element:
  16917. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation
  16918. In this case we have placed it to the right of the default axis rect, so it wasn't necessary to
  16919. call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color
  16920. scale can be set with \ref setLabel.
  16921. For optimum appearance (like in the image above), it may be desirable to line up the axis rect and
  16922. the borders of the color scale. Use a \ref QCPMarginGroup to achieve this:
  16923. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup
  16924. Color scales are initialized with a non-zero minimum top and bottom margin (\ref
  16925. setMinimumMargins), because vertical color scales are most common and the minimum top/bottom
  16926. margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a
  16927. horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you
  16928. might want to also change the minimum margins accordingly, e.g. <tt>setMinimumMargins(QMargins(6, 0, 6, 0))</tt>.
  16929. */
  16930. /* start documentation of inline functions */
  16931. /*! \fn QCPAxis *QCPColorScale::axis() const
  16932. Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the
  16933. appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its
  16934. interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref
  16935. setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref
  16936. QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on
  16937. the QCPColorScale or on its QCPAxis.
  16938. If the type of the color scale is changed with \ref setType, the axis returned by this method
  16939. will change, too, to either the left, right, bottom or top axis, depending on which type was set.
  16940. */
  16941. /* end documentation of signals */
  16942. /* start documentation of signals */
  16943. /*! \fn void QCPColorScale::dataRangeChanged(const QCPRange &newRange);
  16944. This signal is emitted when the data range changes.
  16945. \see setDataRange
  16946. */
  16947. /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  16948. This signal is emitted when the data scale type changes.
  16949. \see setDataScaleType
  16950. */
  16951. /*! \fn void QCPColorScale::gradientChanged(const QCPColorGradient &newGradient);
  16952. This signal is emitted when the gradient changes.
  16953. \see setGradient
  16954. */
  16955. /* end documentation of signals */
  16956. /*!
  16957. Constructs a new QCPColorScale.
  16958. */
  16959. QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) :
  16960. QCPLayoutElement(parentPlot),
  16961. mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight
  16962. mDataScaleType(QCPAxis::stLinear),
  16963. mGradient(QCPColorGradient::gpCold),
  16964. mBarWidth(20),
  16965. mAxisRect(new QCPColorScaleAxisRectPrivate(this))
  16966. {
  16967. setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used)
  16968. setType(QCPAxis::atRight);
  16969. setDataRange(QCPRange(0, 6));
  16970. }
  16971. QCPColorScale::~QCPColorScale()
  16972. {
  16973. delete mAxisRect;
  16974. }
  16975. /* undocumented getter */
  16976. QString QCPColorScale::label() const
  16977. {
  16978. if (!mColorAxis)
  16979. {
  16980. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  16981. return QString();
  16982. }
  16983. return mColorAxis.data()->label();
  16984. }
  16985. /* undocumented getter */
  16986. bool QCPColorScale::rangeDrag() const
  16987. {
  16988. if (!mAxisRect)
  16989. {
  16990. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  16991. return false;
  16992. }
  16993. return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) &&
  16994. mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) &&
  16995. mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
  16996. }
  16997. /* undocumented getter */
  16998. bool QCPColorScale::rangeZoom() const
  16999. {
  17000. if (!mAxisRect)
  17001. {
  17002. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17003. return false;
  17004. }
  17005. return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) &&
  17006. mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) &&
  17007. mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
  17008. }
  17009. /*!
  17010. Sets at which side of the color scale the axis is placed, and thus also its orientation.
  17011. Note that after setting \a type to a different value, the axis returned by \ref axis() will
  17012. be a different one. The new axis will adopt the following properties from the previous axis: The
  17013. range, scale type, label and ticker (the latter will be shared and not copied).
  17014. */
  17015. void QCPColorScale::setType(QCPAxis::AxisType type)
  17016. {
  17017. if (!mAxisRect)
  17018. {
  17019. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17020. return;
  17021. }
  17022. if (mType != type)
  17023. {
  17024. mType = type;
  17025. QCPRange rangeTransfer(0, 6);
  17026. QString labelTransfer;
  17027. QSharedPointer<QCPAxisTicker> tickerTransfer;
  17028. // transfer/revert some settings on old axis if it exists:
  17029. bool doTransfer = !mColorAxis.isNull();
  17030. if (doTransfer)
  17031. {
  17032. rangeTransfer = mColorAxis.data()->range();
  17033. labelTransfer = mColorAxis.data()->label();
  17034. tickerTransfer = mColorAxis.data()->ticker();
  17035. mColorAxis.data()->setLabel(QString());
  17036. disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  17037. disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  17038. }
  17039. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop;
  17040. foreach (QCPAxis::AxisType atype, allAxisTypes)
  17041. {
  17042. mAxisRect.data()->axis(atype)->setTicks(atype == mType);
  17043. mAxisRect.data()->axis(atype)->setTickLabels(atype== mType);
  17044. }
  17045. // set new mColorAxis pointer:
  17046. mColorAxis = mAxisRect.data()->axis(mType);
  17047. // transfer settings to new axis:
  17048. if (doTransfer)
  17049. {
  17050. mColorAxis.data()->setRange(rangeTransfer); // range transfer necessary if axis changes from vertical to horizontal or vice versa (axes with same orientation are synchronized via signals)
  17051. mColorAxis.data()->setLabel(labelTransfer);
  17052. mColorAxis.data()->setTicker(tickerTransfer);
  17053. }
  17054. connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  17055. connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  17056. mAxisRect.data()->setRangeDragAxes(QList<QCPAxis*>() << mColorAxis.data());
  17057. }
  17058. }
  17059. /*!
  17060. Sets the range spanned by the color gradient and that is shown by the axis in the color scale.
  17061. It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is
  17062. also equivalent to directly accessing the \ref axis and setting its range with \ref
  17063. QCPAxis::setRange.
  17064. \see setDataScaleType, setGradient, rescaleDataRange
  17065. */
  17066. void QCPColorScale::setDataRange(const QCPRange &dataRange)
  17067. {
  17068. if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
  17069. {
  17070. mDataRange = dataRange;
  17071. if (mColorAxis)
  17072. mColorAxis.data()->setRange(mDataRange);
  17073. Q_EMIT dataRangeChanged(mDataRange);
  17074. }
  17075. }
  17076. /*!
  17077. Sets the scale type of the color scale, i.e. whether values are associated with colors linearly
  17078. or logarithmically.
  17079. It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is
  17080. also equivalent to directly accessing the \ref axis and setting its scale type with \ref
  17081. QCPAxis::setScaleType.
  17082. Note that this method controls the coordinate transformation. For logarithmic scales, you will
  17083. likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
  17084. the color scale's \ref axis ticker to an instance of \ref QCPAxisTickerLog :
  17085. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-colorscale
  17086. See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
  17087. creation.
  17088. \see setDataRange, setGradient
  17089. */
  17090. void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType)
  17091. {
  17092. if (mDataScaleType != scaleType)
  17093. {
  17094. mDataScaleType = scaleType;
  17095. if (mColorAxis)
  17096. mColorAxis.data()->setScaleType(mDataScaleType);
  17097. if (mDataScaleType == QCPAxis::stLogarithmic)
  17098. setDataRange(mDataRange.sanitizedForLogScale());
  17099. Q_EMIT dataScaleTypeChanged(mDataScaleType);
  17100. }
  17101. }
  17102. /*!
  17103. Sets the color gradient that will be used to represent data values.
  17104. It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps.
  17105. \see setDataRange, setDataScaleType
  17106. */
  17107. void QCPColorScale::setGradient(const QCPColorGradient &gradient)
  17108. {
  17109. if (mGradient != gradient)
  17110. {
  17111. mGradient = gradient;
  17112. if (mAxisRect)
  17113. mAxisRect.data()->mGradientImageInvalidated = true;
  17114. Q_EMIT gradientChanged(mGradient);
  17115. }
  17116. }
  17117. /*!
  17118. Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on
  17119. the internal \ref axis.
  17120. */
  17121. void QCPColorScale::setLabel(const QString &str)
  17122. {
  17123. if (!mColorAxis)
  17124. {
  17125. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  17126. return;
  17127. }
  17128. mColorAxis.data()->setLabel(str);
  17129. }
  17130. /*!
  17131. Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed
  17132. will have.
  17133. */
  17134. void QCPColorScale::setBarWidth(int width)
  17135. {
  17136. mBarWidth = width;
  17137. }
  17138. /*!
  17139. Sets whether the user can drag the data range (\ref setDataRange).
  17140. Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref
  17141. QCustomPlot::setInteractions) to allow range dragging.
  17142. */
  17143. void QCPColorScale::setRangeDrag(bool enabled)
  17144. {
  17145. if (!mAxisRect)
  17146. {
  17147. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17148. return;
  17149. }
  17150. if (enabled)
  17151. {
  17152. mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType));
  17153. } else
  17154. {
  17155. #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
  17156. mAxisRect.data()->setRangeDrag(nullptr);
  17157. #else
  17158. mAxisRect.data()->setRangeDrag({});
  17159. #endif
  17160. }
  17161. }
  17162. /*!
  17163. Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel.
  17164. Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref
  17165. QCustomPlot::setInteractions) to allow range dragging.
  17166. */
  17167. void QCPColorScale::setRangeZoom(bool enabled)
  17168. {
  17169. if (!mAxisRect)
  17170. {
  17171. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17172. return;
  17173. }
  17174. if (enabled)
  17175. {
  17176. mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType));
  17177. } else
  17178. {
  17179. #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
  17180. mAxisRect.data()->setRangeDrag(nullptr);
  17181. #else
  17182. mAxisRect.data()->setRangeZoom({});
  17183. #endif
  17184. }
  17185. }
  17186. /*!
  17187. Returns a list of all the color maps associated with this color scale.
  17188. */
  17189. QList<QCPColorMap*> QCPColorScale::colorMaps() const
  17190. {
  17191. QList<QCPColorMap*> result;
  17192. for (int i=0; i<mParentPlot->plottableCount(); ++i)
  17193. {
  17194. if (QCPColorMap *cm = qobject_cast<QCPColorMap*>(mParentPlot->plottable(i)))
  17195. if (cm->colorScale() == this)
  17196. result.append(cm);
  17197. }
  17198. return result;
  17199. }
  17200. /*!
  17201. Changes the data range such that all color maps associated with this color scale are fully mapped
  17202. to the gradient in the data dimension.
  17203. \see setDataRange
  17204. */
  17205. void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps)
  17206. {
  17207. QList<QCPColorMap*> maps = colorMaps();
  17208. QCPRange newRange;
  17209. bool haveRange = false;
  17210. QCP::SignDomain sign = QCP::sdBoth;
  17211. if (mDataScaleType == QCPAxis::stLogarithmic)
  17212. sign = (mDataRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  17213. foreach (QCPColorMap *map, maps)
  17214. {
  17215. if (!map->realVisibility() && onlyVisibleMaps)
  17216. continue;
  17217. QCPRange mapRange;
  17218. if (map->colorScale() == this)
  17219. {
  17220. bool currentFoundRange = true;
  17221. mapRange = map->data()->dataBounds();
  17222. if (sign == QCP::sdPositive)
  17223. {
  17224. if (mapRange.lower <= 0 && mapRange.upper > 0)
  17225. mapRange.lower = mapRange.upper*1e-3;
  17226. else if (mapRange.lower <= 0 && mapRange.upper <= 0)
  17227. currentFoundRange = false;
  17228. } else if (sign == QCP::sdNegative)
  17229. {
  17230. if (mapRange.upper >= 0 && mapRange.lower < 0)
  17231. mapRange.upper = mapRange.lower*1e-3;
  17232. else if (mapRange.upper >= 0 && mapRange.lower >= 0)
  17233. currentFoundRange = false;
  17234. }
  17235. if (currentFoundRange)
  17236. {
  17237. if (!haveRange)
  17238. newRange = mapRange;
  17239. else
  17240. newRange.expand(mapRange);
  17241. haveRange = true;
  17242. }
  17243. }
  17244. }
  17245. if (haveRange)
  17246. {
  17247. if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data
  17248. {
  17249. double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
  17250. if (mDataScaleType == QCPAxis::stLinear)
  17251. {
  17252. newRange.lower = center-mDataRange.size()/2.0;
  17253. newRange.upper = center+mDataRange.size()/2.0;
  17254. } else // mScaleType == stLogarithmic
  17255. {
  17256. newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower);
  17257. newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower);
  17258. }
  17259. }
  17260. setDataRange(newRange);
  17261. }
  17262. }
  17263. /* inherits documentation from base class */
  17264. void QCPColorScale::update(UpdatePhase phase)
  17265. {
  17266. QCPLayoutElement::update(phase);
  17267. if (!mAxisRect)
  17268. {
  17269. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17270. return;
  17271. }
  17272. mAxisRect.data()->update(phase);
  17273. switch (phase)
  17274. {
  17275. case upMargins:
  17276. {
  17277. if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop)
  17278. {
  17279. setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom());
  17280. setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom());
  17281. } else
  17282. {
  17283. setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), QWIDGETSIZE_MAX);
  17284. setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), 0);
  17285. }
  17286. break;
  17287. }
  17288. case upLayout:
  17289. {
  17290. mAxisRect.data()->setOuterRect(rect());
  17291. break;
  17292. }
  17293. default: break;
  17294. }
  17295. }
  17296. /* inherits documentation from base class */
  17297. void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const
  17298. {
  17299. painter->setAntialiasing(false);
  17300. }
  17301. /* inherits documentation from base class */
  17302. void QCPColorScale::mousePressEvent(QMouseEvent *event, const QVariant &details)
  17303. {
  17304. if (!mAxisRect)
  17305. {
  17306. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17307. return;
  17308. }
  17309. mAxisRect.data()->mousePressEvent(event, details);
  17310. }
  17311. /* inherits documentation from base class */
  17312. void QCPColorScale::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  17313. {
  17314. if (!mAxisRect)
  17315. {
  17316. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17317. return;
  17318. }
  17319. mAxisRect.data()->mouseMoveEvent(event, startPos);
  17320. }
  17321. /* inherits documentation from base class */
  17322. void QCPColorScale::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  17323. {
  17324. if (!mAxisRect)
  17325. {
  17326. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17327. return;
  17328. }
  17329. mAxisRect.data()->mouseReleaseEvent(event, startPos);
  17330. }
  17331. /* inherits documentation from base class */
  17332. void QCPColorScale::wheelEvent(QWheelEvent *event)
  17333. {
  17334. if (!mAxisRect)
  17335. {
  17336. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17337. return;
  17338. }
  17339. mAxisRect.data()->wheelEvent(event);
  17340. }
  17341. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17342. //////////////////// QCPColorScaleAxisRectPrivate
  17343. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17344. /*! \class QCPColorScaleAxisRectPrivate
  17345. \internal
  17346. \brief An axis rect subclass for use in a QCPColorScale
  17347. This is a private class and not part of the public QCustomPlot interface.
  17348. It provides the axis rect functionality for the QCPColorScale class.
  17349. */
  17350. /*!
  17351. Creates a new instance, as a child of \a parentColorScale.
  17352. */
  17353. QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) :
  17354. QCPAxisRect(parentColorScale->parentPlot(), true),
  17355. mParentColorScale(parentColorScale),
  17356. mGradientImageInvalidated(true)
  17357. {
  17358. setParentLayerable(parentColorScale);
  17359. setMinimumMargins(QMargins(0, 0, 0, 0));
  17360. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
  17361. foreach (QCPAxis::AxisType type, allAxisTypes)
  17362. {
  17363. axis(type)->setVisible(true);
  17364. axis(type)->grid()->setVisible(false);
  17365. axis(type)->setPadding(0);
  17366. connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts)));
  17367. connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts)));
  17368. }
  17369. connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange)));
  17370. connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange)));
  17371. connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange)));
  17372. connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange)));
  17373. connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType)));
  17374. connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType)));
  17375. connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType)));
  17376. connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType)));
  17377. // make layer transfers of color scale transfer to axis rect and axes
  17378. // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect:
  17379. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*)));
  17380. foreach (QCPAxis::AxisType type, allAxisTypes)
  17381. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*)));
  17382. }
  17383. /*! \internal
  17384. Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws
  17385. it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation.
  17386. \seebaseclassmethod
  17387. */
  17388. void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter)
  17389. {
  17390. if (mGradientImageInvalidated)
  17391. updateGradientImage();
  17392. bool mirrorHorz = false;
  17393. bool mirrorVert = false;
  17394. if (mParentColorScale->mColorAxis)
  17395. {
  17396. mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop);
  17397. mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight);
  17398. }
  17399. painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert));
  17400. QCPAxisRect::draw(painter);
  17401. }
  17402. /*! \internal
  17403. Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to
  17404. generate a gradient image. This gradient image will be used in the \ref draw method.
  17405. */
  17406. void QCPColorScaleAxisRectPrivate::updateGradientImage()
  17407. {
  17408. if (rect().isEmpty())
  17409. return;
  17410. const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
  17411. int n = mParentColorScale->mGradient.levelCount();
  17412. int w, h;
  17413. QVector<double> data(n);
  17414. for (int i=0; i<n; ++i)
  17415. data[i] = i;
  17416. if (mParentColorScale->mType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop)
  17417. {
  17418. w = n;
  17419. h = rect().height();
  17420. mGradientImage = QImage(w, h, format);
  17421. QVector<QRgb*> pixels;
  17422. for (int y=0; y<h; ++y)
  17423. pixels.append(reinterpret_cast<QRgb*>(mGradientImage.scanLine(y)));
  17424. mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n);
  17425. for (int y=1; y<h; ++y)
  17426. memcpy(pixels.at(y), pixels.first(), size_t(n)*sizeof(QRgb));
  17427. } else
  17428. {
  17429. w = rect().width();
  17430. h = n;
  17431. mGradientImage = QImage(w, h, format);
  17432. for (int y=0; y<h; ++y)
  17433. {
  17434. QRgb *pixels = reinterpret_cast<QRgb*>(mGradientImage.scanLine(y));
  17435. const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1));
  17436. for (int x=0; x<w; ++x)
  17437. pixels[x] = lineColor;
  17438. }
  17439. }
  17440. mGradientImageInvalidated = false;
  17441. }
  17442. /*! \internal
  17443. This slot is connected to the selectionChanged signals of the four axes in the constructor. It
  17444. synchronizes the selection state of the axes.
  17445. */
  17446. void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts)
  17447. {
  17448. // axis bases of four axes shall always (de-)selected synchronously:
  17449. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
  17450. foreach (QCPAxis::AxisType type, allAxisTypes)
  17451. {
  17452. if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
  17453. if (senderAxis->axisType() == type)
  17454. continue;
  17455. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
  17456. {
  17457. if (selectedParts.testFlag(QCPAxis::spAxis))
  17458. axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis);
  17459. else
  17460. axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis);
  17461. }
  17462. }
  17463. }
  17464. /*! \internal
  17465. This slot is connected to the selectableChanged signals of the four axes in the constructor. It
  17466. synchronizes the selectability of the axes.
  17467. */
  17468. void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts)
  17469. {
  17470. // synchronize axis base selectability:
  17471. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight;
  17472. foreach (QCPAxis::AxisType type, allAxisTypes)
  17473. {
  17474. if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
  17475. if (senderAxis->axisType() == type)
  17476. continue;
  17477. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
  17478. {
  17479. if (selectableParts.testFlag(QCPAxis::spAxis))
  17480. axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis);
  17481. else
  17482. axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis);
  17483. }
  17484. }
  17485. }
  17486. /* end of 'src/layoutelements/layoutelement-colorscale.cpp' */
  17487. /* including file 'src/plottables/plottable-graph.cpp' */
  17488. /* modified 2021-03-29T02:30:44, size 74518 */
  17489. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17490. //////////////////// QCPGraphData
  17491. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17492. /*! \class QCPGraphData
  17493. \brief Holds the data of one single data point for QCPGraph.
  17494. The stored data is:
  17495. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  17496. \li \a value: coordinate on the value axis of this data point (this is the \a mainValue)
  17497. The container for storing multiple data points is \ref QCPGraphDataContainer. It is a typedef for
  17498. \ref QCPDataContainer with \ref QCPGraphData as the DataType template parameter. See the
  17499. documentation there for an explanation regarding the data type's generic methods.
  17500. \see QCPGraphDataContainer
  17501. */
  17502. /* start documentation of inline functions */
  17503. /*! \fn double QCPGraphData::sortKey() const
  17504. Returns the \a key member of this data point.
  17505. For a general explanation of what this method is good for in the context of the data container,
  17506. see the documentation of \ref QCPDataContainer.
  17507. */
  17508. /*! \fn static QCPGraphData QCPGraphData::fromSortKey(double sortKey)
  17509. Returns a data point with the specified \a sortKey. All other members are set to zero.
  17510. For a general explanation of what this method is good for in the context of the data container,
  17511. see the documentation of \ref QCPDataContainer.
  17512. */
  17513. /*! \fn static static bool QCPGraphData::sortKeyIsMainKey()
  17514. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  17515. this method returns true.
  17516. For a general explanation of what this method is good for in the context of the data container,
  17517. see the documentation of \ref QCPDataContainer.
  17518. */
  17519. /*! \fn double QCPGraphData::mainKey() const
  17520. Returns the \a key member of this data point.
  17521. For a general explanation of what this method is good for in the context of the data container,
  17522. see the documentation of \ref QCPDataContainer.
  17523. */
  17524. /*! \fn double QCPGraphData::mainValue() const
  17525. Returns the \a value member of this data point.
  17526. For a general explanation of what this method is good for in the context of the data container,
  17527. see the documentation of \ref QCPDataContainer.
  17528. */
  17529. /*! \fn QCPRange QCPGraphData::valueRange() const
  17530. Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
  17531. For a general explanation of what this method is good for in the context of the data container,
  17532. see the documentation of \ref QCPDataContainer.
  17533. */
  17534. /* end documentation of inline functions */
  17535. /*!
  17536. Constructs a data point with key and value set to zero.
  17537. */
  17538. QCPGraphData::QCPGraphData() :
  17539. key(0),
  17540. value(0)
  17541. {
  17542. }
  17543. /*!
  17544. Constructs a data point with the specified \a key and \a value.
  17545. */
  17546. QCPGraphData::QCPGraphData(double key, double value) :
  17547. key(key),
  17548. value(value)
  17549. {
  17550. }
  17551. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17552. //////////////////// QCPGraph
  17553. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17554. /*! \class QCPGraph
  17555. \brief A plottable representing a graph in a plot.
  17556. \image html QCPGraph.png
  17557. Usually you create new graphs by calling QCustomPlot::addGraph. The resulting instance can be
  17558. accessed via QCustomPlot::graph.
  17559. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  17560. also access and modify the data via the \ref data method, which returns a pointer to the internal
  17561. \ref QCPGraphDataContainer.
  17562. Graphs are used to display single-valued data. Single-valued means that there should only be one
  17563. data point per unique key coordinate. In other words, the graph can't have \a loops. If you do
  17564. want to plot non-single-valued curves, rather use the QCPCurve plottable.
  17565. Gaps in the graph line can be created by adding data points with NaN as value
  17566. (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
  17567. separated.
  17568. \section qcpgraph-appearance Changing the appearance
  17569. The appearance of the graph is mainly determined by the line style, scatter style, brush and pen
  17570. of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen).
  17571. \subsection filling Filling under or between graphs
  17572. QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to
  17573. the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill,
  17574. just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent.
  17575. By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill
  17576. between this graph and another one, call \ref setChannelFillGraph with the other graph as
  17577. parameter.
  17578. \see QCustomPlot::addGraph, QCustomPlot::graph
  17579. */
  17580. /* start of documentation of inline functions */
  17581. /*! \fn QSharedPointer<QCPGraphDataContainer> QCPGraph::data() const
  17582. Returns a shared pointer to the internal data storage of type \ref QCPGraphDataContainer. You may
  17583. use it to directly manipulate the data, which may be more convenient and faster than using the
  17584. regular \ref setData or \ref addData methods.
  17585. */
  17586. /* end of documentation of inline functions */
  17587. /*!
  17588. Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  17589. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  17590. the same orientation. If either of these restrictions is violated, a corresponding message is
  17591. printed to the debug output (qDebug), the construction is not aborted, though.
  17592. The created QCPGraph is automatically registered with the QCustomPlot instance inferred from \a
  17593. keyAxis. This QCustomPlot instance takes ownership of the QCPGraph, so do not delete it manually
  17594. but use QCustomPlot::removePlottable() instead.
  17595. To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function.
  17596. */
  17597. QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  17598. QCPAbstractPlottable1D<QCPGraphData>(keyAxis, valueAxis),
  17599. mLineStyle{},
  17600. mScatterSkip{},
  17601. mAdaptiveSampling{}
  17602. {
  17603. // special handling for QCPGraphs to maintain the simple graph interface:
  17604. mParentPlot->registerGraph(this);
  17605. setPen(QPen(Qt::blue, 0));
  17606. setBrush(Qt::NoBrush);
  17607. setLineStyle(lsLine);
  17608. setScatterSkip(0);
  17609. setChannelFillGraph(nullptr);
  17610. setAdaptiveSampling(true);
  17611. }
  17612. QCPGraph::~QCPGraph()
  17613. {
  17614. }
  17615. /*! \overload
  17616. Replaces the current data container with the provided \a data container.
  17617. Since a QSharedPointer is used, multiple QCPGraphs may share the same data container safely.
  17618. Modifying the data in the container will then affect all graphs that share the container. Sharing
  17619. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  17620. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-1
  17621. If you do not wish to share containers, but create a copy from an existing container, rather use
  17622. the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
  17623. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-2
  17624. \see addData
  17625. */
  17626. void QCPGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
  17627. {
  17628. mDataContainer = data;
  17629. }
  17630. /*! \overload
  17631. Replaces the current data with the provided points in \a keys and \a values. The provided
  17632. vectors should have equal length. Else, the number of added points will be the size of the
  17633. smallest vector.
  17634. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  17635. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  17636. \see addData
  17637. */
  17638. void QCPGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  17639. {
  17640. mDataContainer->clear();
  17641. addData(keys, values, alreadySorted);
  17642. }
  17643. /*!
  17644. Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
  17645. \ref lsNone and \ref setScatterStyle to the desired scatter style.
  17646. \see setScatterStyle
  17647. */
  17648. void QCPGraph::setLineStyle(LineStyle ls)
  17649. {
  17650. mLineStyle = ls;
  17651. }
  17652. /*!
  17653. Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
  17654. are drawn (e.g. for line-only-plots with appropriate line style).
  17655. \see QCPScatterStyle, setLineStyle
  17656. */
  17657. void QCPGraph::setScatterStyle(const QCPScatterStyle &style)
  17658. {
  17659. mScatterStyle = style;
  17660. }
  17661. /*!
  17662. If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
  17663. scatter points are skipped/not drawn after every drawn scatter point.
  17664. This can be used to make the data appear sparser while for example still having a smooth line,
  17665. and to improve performance for very high density plots.
  17666. If \a skip is set to 0 (default), all scatter points are drawn.
  17667. \see setScatterStyle
  17668. */
  17669. void QCPGraph::setScatterSkip(int skip)
  17670. {
  17671. mScatterSkip = qMax(0, skip);
  17672. }
  17673. /*!
  17674. Sets the target graph for filling the area between this graph and \a targetGraph with the current
  17675. brush (\ref setBrush).
  17676. When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To
  17677. disable any filling, set the brush to Qt::NoBrush.
  17678. \see setBrush
  17679. */
  17680. void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph)
  17681. {
  17682. // prevent setting channel target to this graph itself:
  17683. if (targetGraph == this)
  17684. {
  17685. qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself";
  17686. mChannelFillGraph = nullptr;
  17687. return;
  17688. }
  17689. // prevent setting channel target to a graph not in the plot:
  17690. if (targetGraph && targetGraph->mParentPlot != mParentPlot)
  17691. {
  17692. qDebug() << Q_FUNC_INFO << "targetGraph not in same plot";
  17693. mChannelFillGraph = nullptr;
  17694. return;
  17695. }
  17696. mChannelFillGraph = targetGraph;
  17697. }
  17698. /*!
  17699. Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive
  17700. sampling technique can drastically improve the replot performance for graphs with a larger number
  17701. of points (e.g. above 10,000), without notably changing the appearance of the graph.
  17702. By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive
  17703. sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no
  17704. disadvantage in almost all cases.
  17705. \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling"
  17706. As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are
  17707. reproduced reliably, as well as the overall shape of the data set. The replot time reduces
  17708. dramatically though. This allows QCustomPlot to display large amounts of data in realtime.
  17709. \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling"
  17710. Care must be taken when using high-density scatter plots in combination with adaptive sampling.
  17711. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still
  17712. gives a significant reduction of replot times, but not quite as much as for line plots. This is
  17713. because scatter plots inherently need more data points to be preserved in order to still resemble
  17714. the original, non-adaptive-sampling plot. As shown above, the results still aren't quite
  17715. identical, as banding occurs for the outer data points. This is in fact intentional, such that
  17716. the boundaries of the data cloud stay visible to the viewer. How strong the banding appears,
  17717. depends on the point density, i.e. the number of points in the plot.
  17718. For some situations with scatter plots it might thus be desirable to manually turn adaptive
  17719. sampling off. For example, when saving the plot to disk. This can be achieved by setting \a
  17720. enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled
  17721. back to true afterwards.
  17722. */
  17723. void QCPGraph::setAdaptiveSampling(bool enabled)
  17724. {
  17725. mAdaptiveSampling = enabled;
  17726. }
  17727. /*! \overload
  17728. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  17729. should have equal length. Else, the number of added points will be the size of the smallest
  17730. vector.
  17731. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  17732. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  17733. Alternatively, you can also access and modify the data directly via the \ref data method, which
  17734. returns a pointer to the internal data container.
  17735. */
  17736. void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  17737. {
  17738. if (keys.size() != values.size())
  17739. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  17740. const int n = qMin(keys.size(), values.size());
  17741. QVector<QCPGraphData> tempData(n);
  17742. QVector<QCPGraphData>::iterator it = tempData.begin();
  17743. const QVector<QCPGraphData>::iterator itEnd = tempData.end();
  17744. int i = 0;
  17745. while (it != itEnd)
  17746. {
  17747. it->key = keys[i];
  17748. it->value = values[i];
  17749. ++it;
  17750. ++i;
  17751. }
  17752. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  17753. }
  17754. /*! \overload
  17755. Adds the provided data point as \a key and \a value to the current data.
  17756. Alternatively, you can also access and modify the data directly via the \ref data method, which
  17757. returns a pointer to the internal data container.
  17758. */
  17759. void QCPGraph::addData(double key, double value)
  17760. {
  17761. mDataContainer->add(QCPGraphData(key, value));
  17762. }
  17763. /*!
  17764. Implements a selectTest specific to this plottable's point geometry.
  17765. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  17766. point to \a pos.
  17767. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  17768. */
  17769. double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17770. {
  17771. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  17772. return -1;
  17773. if (!mKeyAxis || !mValueAxis)
  17774. return -1;
  17775. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  17776. {
  17777. QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  17778. double result = pointDistance(pos, closestDataPoint);
  17779. if (details)
  17780. {
  17781. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  17782. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  17783. }
  17784. return result;
  17785. } else
  17786. return -1;
  17787. }
  17788. /* inherits documentation from base class */
  17789. QCPRange QCPGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  17790. {
  17791. return mDataContainer->keyRange(foundRange, inSignDomain);
  17792. }
  17793. /* inherits documentation from base class */
  17794. QCPRange QCPGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  17795. {
  17796. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  17797. }
  17798. /* inherits documentation from base class */
  17799. void QCPGraph::draw(QCPPainter *painter)
  17800. {
  17801. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  17802. if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
  17803. if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
  17804. QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
  17805. // loop over and draw segments of unselected/selected data:
  17806. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  17807. getDataSegments(selectedSegments, unselectedSegments);
  17808. allSegments << unselectedSegments << selectedSegments;
  17809. for (int i=0; i<allSegments.size(); ++i)
  17810. {
  17811. bool isSelectedSegment = i >= unselectedSegments.size();
  17812. // get line pixel points appropriate to line style:
  17813. QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getLines takes care)
  17814. getLines(&lines, lineDataRange);
  17815. // check data validity if flag set:
  17816. #ifdef QCUSTOMPLOT_CHECK_DATA
  17817. QCPGraphDataContainer::const_iterator it;
  17818. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  17819. {
  17820. if (QCP::isInvalidData(it->key, it->value))
  17821. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
  17822. }
  17823. #endif
  17824. // draw fill of graph:
  17825. if (isSelectedSegment && mSelectionDecorator)
  17826. mSelectionDecorator->applyBrush(painter);
  17827. else
  17828. painter->setBrush(mBrush);
  17829. painter->setPen(Qt::NoPen);
  17830. drawFill(painter, &lines);
  17831. // draw line:
  17832. if (mLineStyle != lsNone)
  17833. {
  17834. if (isSelectedSegment && mSelectionDecorator)
  17835. mSelectionDecorator->applyPen(painter);
  17836. else
  17837. painter->setPen(mPen);
  17838. painter->setBrush(Qt::NoBrush);
  17839. if (mLineStyle == lsImpulse)
  17840. drawImpulsePlot(painter, lines);
  17841. else
  17842. drawLinePlot(painter, lines); // also step plots can be drawn as a line plot
  17843. }
  17844. // draw scatters:
  17845. QCPScatterStyle finalScatterStyle = mScatterStyle;
  17846. if (isSelectedSegment && mSelectionDecorator)
  17847. finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
  17848. if (!finalScatterStyle.isNone())
  17849. {
  17850. getScatters(&scatters, allSegments.at(i));
  17851. drawScatterPlot(painter, scatters, finalScatterStyle);
  17852. }
  17853. }
  17854. // draw other selection decoration that isn't just line/scatter pens and brushes:
  17855. if (mSelectionDecorator)
  17856. mSelectionDecorator->drawDecoration(painter, selection());
  17857. }
  17858. /* inherits documentation from base class */
  17859. void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  17860. {
  17861. // draw fill:
  17862. if (mBrush.style() != Qt::NoBrush)
  17863. {
  17864. applyFillAntialiasingHint(painter);
  17865. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  17866. }
  17867. // draw line vertically centered:
  17868. if (mLineStyle != lsNone)
  17869. {
  17870. applyDefaultAntialiasingHint(painter);
  17871. painter->setPen(mPen);
  17872. painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
  17873. }
  17874. // draw scatter symbol:
  17875. if (!mScatterStyle.isNone())
  17876. {
  17877. applyScattersAntialiasingHint(painter);
  17878. // scale scatter pixmap if it's too large to fit in legend icon rect:
  17879. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  17880. {
  17881. QCPScatterStyle scaledStyle(mScatterStyle);
  17882. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  17883. scaledStyle.applyTo(painter, mPen);
  17884. scaledStyle.drawShape(painter, QRectF(rect).center());
  17885. } else
  17886. {
  17887. mScatterStyle.applyTo(painter, mPen);
  17888. mScatterStyle.drawShape(painter, QRectF(rect).center());
  17889. }
  17890. }
  17891. }
  17892. /*! \internal
  17893. This method retrieves an optimized set of data points via \ref getOptimizedLineData, and branches
  17894. out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
  17895. according to the line style of the graph.
  17896. \a lines will be filled with points in pixel coordinates, that can be drawn with the according
  17897. draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
  17898. aren't necessarily the original data points. For example, step line styles require additional
  17899. points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
  17900. lines vector will be empty.
  17901. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  17902. conversion. In this function, the specified range may exceed the total data bounds without harm:
  17903. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  17904. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  17905. getDataSegments.
  17906. \see getScatters
  17907. */
  17908. void QCPGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
  17909. {
  17910. if (!lines) return;
  17911. QCPGraphDataContainer::const_iterator begin, end;
  17912. getVisibleDataBounds(begin, end, dataRange);
  17913. if (begin == end)
  17914. {
  17915. lines->clear();
  17916. return;
  17917. }
  17918. QVector<QCPGraphData> lineData;
  17919. if (mLineStyle != lsNone)
  17920. getOptimizedLineData(&lineData, begin, end);
  17921. if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in lineData (significantly simplifies following processing)
  17922. std::reverse(lineData.begin(), lineData.end());
  17923. switch (mLineStyle)
  17924. {
  17925. case lsNone: lines->clear(); break;
  17926. case lsLine: *lines = dataToLines(lineData); break;
  17927. case lsStepLeft: *lines = dataToStepLeftLines(lineData); break;
  17928. case lsStepRight: *lines = dataToStepRightLines(lineData); break;
  17929. case lsStepCenter: *lines = dataToStepCenterLines(lineData); break;
  17930. case lsImpulse: *lines = dataToImpulseLines(lineData); break;
  17931. }
  17932. }
  17933. /*! \internal
  17934. This method retrieves an optimized set of data points via \ref getOptimizedScatterData and then
  17935. converts them to pixel coordinates. The resulting points are returned in \a scatters, and can be
  17936. passed to \ref drawScatterPlot.
  17937. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  17938. conversion. In this function, the specified range may exceed the total data bounds without harm:
  17939. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  17940. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  17941. getDataSegments.
  17942. */
  17943. void QCPGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
  17944. {
  17945. if (!scatters) return;
  17946. QCPAxis *keyAxis = mKeyAxis.data();
  17947. QCPAxis *valueAxis = mValueAxis.data();
  17948. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; scatters->clear(); return; }
  17949. QCPGraphDataContainer::const_iterator begin, end;
  17950. getVisibleDataBounds(begin, end, dataRange);
  17951. if (begin == end)
  17952. {
  17953. scatters->clear();
  17954. return;
  17955. }
  17956. QVector<QCPGraphData> data;
  17957. getOptimizedScatterData(&data, begin, end);
  17958. if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in data (significantly simplifies following processing)
  17959. std::reverse(data.begin(), data.end());
  17960. scatters->resize(data.size());
  17961. if (keyAxis->orientation() == Qt::Vertical)
  17962. {
  17963. for (int i=0; i<data.size(); ++i)
  17964. {
  17965. if (!qIsNaN(data.at(i).value))
  17966. {
  17967. (*scatters)[i].setX(valueAxis->coordToPixel(data.at(i).value));
  17968. (*scatters)[i].setY(keyAxis->coordToPixel(data.at(i).key));
  17969. }
  17970. }
  17971. } else
  17972. {
  17973. for (int i=0; i<data.size(); ++i)
  17974. {
  17975. if (!qIsNaN(data.at(i).value))
  17976. {
  17977. (*scatters)[i].setX(keyAxis->coordToPixel(data.at(i).key));
  17978. (*scatters)[i].setY(valueAxis->coordToPixel(data.at(i).value));
  17979. }
  17980. }
  17981. }
  17982. }
  17983. /*! \internal
  17984. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  17985. coordinate points which are suitable for drawing the line style \ref lsLine.
  17986. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  17987. getLines if the line style is set accordingly.
  17988. \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  17989. */
  17990. QVector<QPointF> QCPGraph::dataToLines(const QVector<QCPGraphData> &data) const
  17991. {
  17992. QVector<QPointF> result;
  17993. QCPAxis *keyAxis = mKeyAxis.data();
  17994. QCPAxis *valueAxis = mValueAxis.data();
  17995. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  17996. result.resize(data.size());
  17997. // transform data points to pixels:
  17998. if (keyAxis->orientation() == Qt::Vertical)
  17999. {
  18000. for (int i=0; i<data.size(); ++i)
  18001. {
  18002. result[i].setX(valueAxis->coordToPixel(data.at(i).value));
  18003. result[i].setY(keyAxis->coordToPixel(data.at(i).key));
  18004. }
  18005. } else // key axis is horizontal
  18006. {
  18007. for (int i=0; i<data.size(); ++i)
  18008. {
  18009. result[i].setX(keyAxis->coordToPixel(data.at(i).key));
  18010. result[i].setY(valueAxis->coordToPixel(data.at(i).value));
  18011. }
  18012. }
  18013. return result;
  18014. }
  18015. /*! \internal
  18016. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18017. coordinate points which are suitable for drawing the line style \ref lsStepLeft.
  18018. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18019. getLines if the line style is set accordingly.
  18020. \see dataToLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  18021. */
  18022. QVector<QPointF> QCPGraph::dataToStepLeftLines(const QVector<QCPGraphData> &data) const
  18023. {
  18024. QVector<QPointF> result;
  18025. QCPAxis *keyAxis = mKeyAxis.data();
  18026. QCPAxis *valueAxis = mValueAxis.data();
  18027. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18028. result.resize(data.size()*2);
  18029. // calculate steps from data and transform to pixel coordinates:
  18030. if (keyAxis->orientation() == Qt::Vertical)
  18031. {
  18032. double lastValue = valueAxis->coordToPixel(data.first().value);
  18033. for (int i=0; i<data.size(); ++i)
  18034. {
  18035. const double key = keyAxis->coordToPixel(data.at(i).key);
  18036. result[i*2+0].setX(lastValue);
  18037. result[i*2+0].setY(key);
  18038. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18039. result[i*2+1].setX(lastValue);
  18040. result[i*2+1].setY(key);
  18041. }
  18042. } else // key axis is horizontal
  18043. {
  18044. double lastValue = valueAxis->coordToPixel(data.first().value);
  18045. for (int i=0; i<data.size(); ++i)
  18046. {
  18047. const double key = keyAxis->coordToPixel(data.at(i).key);
  18048. result[i*2+0].setX(key);
  18049. result[i*2+0].setY(lastValue);
  18050. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18051. result[i*2+1].setX(key);
  18052. result[i*2+1].setY(lastValue);
  18053. }
  18054. }
  18055. return result;
  18056. }
  18057. /*! \internal
  18058. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18059. coordinate points which are suitable for drawing the line style \ref lsStepRight.
  18060. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18061. getLines if the line style is set accordingly.
  18062. \see dataToLines, dataToStepLeftLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  18063. */
  18064. QVector<QPointF> QCPGraph::dataToStepRightLines(const QVector<QCPGraphData> &data) const
  18065. {
  18066. QVector<QPointF> result;
  18067. QCPAxis *keyAxis = mKeyAxis.data();
  18068. QCPAxis *valueAxis = mValueAxis.data();
  18069. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18070. result.resize(data.size()*2);
  18071. // calculate steps from data and transform to pixel coordinates:
  18072. if (keyAxis->orientation() == Qt::Vertical)
  18073. {
  18074. double lastKey = keyAxis->coordToPixel(data.first().key);
  18075. for (int i=0; i<data.size(); ++i)
  18076. {
  18077. const double value = valueAxis->coordToPixel(data.at(i).value);
  18078. result[i*2+0].setX(value);
  18079. result[i*2+0].setY(lastKey);
  18080. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18081. result[i*2+1].setX(value);
  18082. result[i*2+1].setY(lastKey);
  18083. }
  18084. } else // key axis is horizontal
  18085. {
  18086. double lastKey = keyAxis->coordToPixel(data.first().key);
  18087. for (int i=0; i<data.size(); ++i)
  18088. {
  18089. const double value = valueAxis->coordToPixel(data.at(i).value);
  18090. result[i*2+0].setX(lastKey);
  18091. result[i*2+0].setY(value);
  18092. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18093. result[i*2+1].setX(lastKey);
  18094. result[i*2+1].setY(value);
  18095. }
  18096. }
  18097. return result;
  18098. }
  18099. /*! \internal
  18100. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18101. coordinate points which are suitable for drawing the line style \ref lsStepCenter.
  18102. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18103. getLines if the line style is set accordingly.
  18104. \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToImpulseLines, getLines, drawLinePlot
  18105. */
  18106. QVector<QPointF> QCPGraph::dataToStepCenterLines(const QVector<QCPGraphData> &data) const
  18107. {
  18108. QVector<QPointF> result;
  18109. QCPAxis *keyAxis = mKeyAxis.data();
  18110. QCPAxis *valueAxis = mValueAxis.data();
  18111. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18112. result.resize(data.size()*2);
  18113. // calculate steps from data and transform to pixel coordinates:
  18114. if (keyAxis->orientation() == Qt::Vertical)
  18115. {
  18116. double lastKey = keyAxis->coordToPixel(data.first().key);
  18117. double lastValue = valueAxis->coordToPixel(data.first().value);
  18118. result[0].setX(lastValue);
  18119. result[0].setY(lastKey);
  18120. for (int i=1; i<data.size(); ++i)
  18121. {
  18122. const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
  18123. result[i*2-1].setX(lastValue);
  18124. result[i*2-1].setY(key);
  18125. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18126. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18127. result[i*2+0].setX(lastValue);
  18128. result[i*2+0].setY(key);
  18129. }
  18130. result[data.size()*2-1].setX(lastValue);
  18131. result[data.size()*2-1].setY(lastKey);
  18132. } else // key axis is horizontal
  18133. {
  18134. double lastKey = keyAxis->coordToPixel(data.first().key);
  18135. double lastValue = valueAxis->coordToPixel(data.first().value);
  18136. result[0].setX(lastKey);
  18137. result[0].setY(lastValue);
  18138. for (int i=1; i<data.size(); ++i)
  18139. {
  18140. const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
  18141. result[i*2-1].setX(key);
  18142. result[i*2-1].setY(lastValue);
  18143. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18144. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18145. result[i*2+0].setX(key);
  18146. result[i*2+0].setY(lastValue);
  18147. }
  18148. result[data.size()*2-1].setX(lastKey);
  18149. result[data.size()*2-1].setY(lastValue);
  18150. }
  18151. return result;
  18152. }
  18153. /*! \internal
  18154. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18155. coordinate points which are suitable for drawing the line style \ref lsImpulse.
  18156. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18157. getLines if the line style is set accordingly.
  18158. \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, getLines, drawImpulsePlot
  18159. */
  18160. QVector<QPointF> QCPGraph::dataToImpulseLines(const QVector<QCPGraphData> &data) const
  18161. {
  18162. QVector<QPointF> result;
  18163. QCPAxis *keyAxis = mKeyAxis.data();
  18164. QCPAxis *valueAxis = mValueAxis.data();
  18165. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18166. result.resize(data.size()*2);
  18167. // transform data points to pixels:
  18168. if (keyAxis->orientation() == Qt::Vertical)
  18169. {
  18170. for (int i=0; i<data.size(); ++i)
  18171. {
  18172. const double key = keyAxis->coordToPixel(data.at(i).key);
  18173. result[i*2+0].setX(valueAxis->coordToPixel(0));
  18174. result[i*2+0].setY(key);
  18175. result[i*2+1].setX(valueAxis->coordToPixel(data.at(i).value));
  18176. result[i*2+1].setY(key);
  18177. }
  18178. } else // key axis is horizontal
  18179. {
  18180. for (int i=0; i<data.size(); ++i)
  18181. {
  18182. const double key = keyAxis->coordToPixel(data.at(i).key);
  18183. result[i*2+0].setX(key);
  18184. result[i*2+0].setY(valueAxis->coordToPixel(0));
  18185. result[i*2+1].setX(key);
  18186. result[i*2+1].setY(valueAxis->coordToPixel(data.at(i).value));
  18187. }
  18188. }
  18189. return result;
  18190. }
  18191. /*! \internal
  18192. Draws the fill of the graph using the specified \a painter, with the currently set brush.
  18193. Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref
  18194. getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons.
  18195. In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas),
  18196. this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to
  18197. operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN
  18198. segments of the two involved graphs, before passing the overlapping pairs to \ref
  18199. getChannelFillPolygon.
  18200. Pass the points of this graph's line as \a lines, in pixel coordinates.
  18201. \see drawLinePlot, drawImpulsePlot, drawScatterPlot
  18202. */
  18203. void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
  18204. {
  18205. if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot
  18206. if (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) return;
  18207. applyFillAntialiasingHint(painter);
  18208. const QVector<QCPDataRange> segments = getNonNanSegments(lines, keyAxis()->orientation());
  18209. if (!mChannelFillGraph)
  18210. {
  18211. // draw base fill under graph, fill goes all the way to the zero-value-line:
  18212. foreach (QCPDataRange segment, segments)
  18213. painter->drawPolygon(getFillPolygon(lines, segment));
  18214. } else
  18215. {
  18216. // draw fill between this graph and mChannelFillGraph:
  18217. QVector<QPointF> otherLines;
  18218. mChannelFillGraph->getLines(&otherLines, QCPDataRange(0, mChannelFillGraph->dataCount()));
  18219. if (!otherLines.isEmpty())
  18220. {
  18221. QVector<QCPDataRange> otherSegments = getNonNanSegments(&otherLines, mChannelFillGraph->keyAxis()->orientation());
  18222. QVector<QPair<QCPDataRange, QCPDataRange> > segmentPairs = getOverlappingSegments(segments, lines, otherSegments, &otherLines);
  18223. for (int i=0; i<segmentPairs.size(); ++i)
  18224. painter->drawPolygon(getChannelFillPolygon(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second));
  18225. }
  18226. }
  18227. }
  18228. /*! \internal
  18229. Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
  18230. scatters will be drawn with \a painter and have the appearance as specified in \a style.
  18231. \see drawLinePlot, drawImpulsePlot
  18232. */
  18233. void QCPGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
  18234. {
  18235. applyScattersAntialiasingHint(painter);
  18236. style.applyTo(painter, mPen);
  18237. foreach (const QPointF &scatter, scatters)
  18238. style.drawShape(painter, scatter.x(), scatter.y());
  18239. }
  18240. /*! \internal
  18241. Draws lines between the points in \a lines, given in pixel coordinates.
  18242. \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
  18243. */
  18244. void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
  18245. {
  18246. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  18247. {
  18248. applyDefaultAntialiasingHint(painter);
  18249. drawPolyline(painter, lines);
  18250. }
  18251. }
  18252. /*! \internal
  18253. Draws impulses from the provided data, i.e. it connects all line pairs in \a lines, given in
  18254. pixel coordinates. The \a lines necessary for impulses are generated by \ref dataToImpulseLines
  18255. from the regular graph data points.
  18256. \see drawLinePlot, drawScatterPlot
  18257. */
  18258. void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
  18259. {
  18260. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  18261. {
  18262. applyDefaultAntialiasingHint(painter);
  18263. QPen oldPen = painter->pen();
  18264. QPen newPen = painter->pen();
  18265. newPen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
  18266. painter->setPen(newPen);
  18267. painter->drawLines(lines);
  18268. painter->setPen(oldPen);
  18269. }
  18270. }
  18271. /*! \internal
  18272. Returns via \a lineData the data points that need to be visualized for this graph when plotting
  18273. graph lines, taking into consideration the currently visible axis ranges and, if \ref
  18274. setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
  18275. further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
  18276. getDataSegments).
  18277. This method is used by \ref getLines to retrieve the basic working set of data.
  18278. \see getOptimizedScatterData
  18279. */
  18280. void QCPGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
  18281. {
  18282. if (!lineData) return;
  18283. QCPAxis *keyAxis = mKeyAxis.data();
  18284. QCPAxis *valueAxis = mValueAxis.data();
  18285. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  18286. if (begin == end) return;
  18287. int dataCount = int(end-begin);
  18288. int maxCount = (std::numeric_limits<int>::max)();
  18289. if (mAdaptiveSampling)
  18290. {
  18291. double keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key));
  18292. if (2*keyPixelSpan+2 < static_cast<double>((std::numeric_limits<int>::max)()))
  18293. maxCount = int(2*keyPixelSpan+2);
  18294. }
  18295. if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
  18296. {
  18297. QCPGraphDataContainer::const_iterator it = begin;
  18298. double minValue = it->value;
  18299. double maxValue = it->value;
  18300. QCPGraphDataContainer::const_iterator currentIntervalFirstPoint = it;
  18301. int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
  18302. int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
  18303. double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound));
  18304. double lastIntervalEndKey = currentIntervalStartKey;
  18305. double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
  18306. bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
  18307. int intervalDataCount = 1;
  18308. ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
  18309. while (it != end)
  18310. {
  18311. if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary
  18312. {
  18313. if (it->value < minValue)
  18314. minValue = it->value;
  18315. else if (it->value > maxValue)
  18316. maxValue = it->value;
  18317. ++intervalDataCount;
  18318. } else // new pixel interval started
  18319. {
  18320. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
  18321. {
  18322. if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point
  18323. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
  18324. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
  18325. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
  18326. if (it->key > currentIntervalStartKey+keyEpsilon*2) // new pixel started further away from previous cluster, so make sure the last point of the cluster is at a real data point
  18327. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.8, (it-1)->value));
  18328. } else
  18329. lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
  18330. lastIntervalEndKey = (it-1)->key;
  18331. minValue = it->value;
  18332. maxValue = it->value;
  18333. currentIntervalFirstPoint = it;
  18334. currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(it->key)+reversedRound));
  18335. if (keyEpsilonVariable)
  18336. keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
  18337. intervalDataCount = 1;
  18338. }
  18339. ++it;
  18340. }
  18341. // handle last interval:
  18342. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
  18343. {
  18344. if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point
  18345. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
  18346. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
  18347. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
  18348. } else
  18349. lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
  18350. } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
  18351. {
  18352. lineData->resize(dataCount);
  18353. std::copy(begin, end, lineData->begin());
  18354. }
  18355. }
  18356. /*! \internal
  18357. Returns via \a scatterData the data points that need to be visualized for this graph when
  18358. plotting scatter points, taking into consideration the currently visible axis ranges and, if \ref
  18359. setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
  18360. further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
  18361. getDataSegments).
  18362. This method is used by \ref getScatters to retrieve the basic working set of data.
  18363. \see getOptimizedLineData
  18364. */
  18365. void QCPGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
  18366. {
  18367. if (!scatterData) return;
  18368. QCPAxis *keyAxis = mKeyAxis.data();
  18369. QCPAxis *valueAxis = mValueAxis.data();
  18370. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  18371. const int scatterModulo = mScatterSkip+1;
  18372. const bool doScatterSkip = mScatterSkip > 0;
  18373. int beginIndex = int(begin-mDataContainer->constBegin());
  18374. int endIndex = int(end-mDataContainer->constBegin());
  18375. while (doScatterSkip && begin != end && beginIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
  18376. {
  18377. ++beginIndex;
  18378. ++begin;
  18379. }
  18380. if (begin == end) return;
  18381. int dataCount = int(end-begin);
  18382. int maxCount = (std::numeric_limits<int>::max)();
  18383. if (mAdaptiveSampling)
  18384. {
  18385. int keyPixelSpan = int(qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key)));
  18386. maxCount = 2*keyPixelSpan+2;
  18387. }
  18388. if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
  18389. {
  18390. double valueMaxRange = valueAxis->range().upper;
  18391. double valueMinRange = valueAxis->range().lower;
  18392. QCPGraphDataContainer::const_iterator it = begin;
  18393. int itIndex = int(beginIndex);
  18394. double minValue = it->value;
  18395. double maxValue = it->value;
  18396. QCPGraphDataContainer::const_iterator minValueIt = it;
  18397. QCPGraphDataContainer::const_iterator maxValueIt = it;
  18398. QCPGraphDataContainer::const_iterator currentIntervalStart = it;
  18399. int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
  18400. int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
  18401. double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound));
  18402. double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
  18403. bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
  18404. int intervalDataCount = 1;
  18405. // advance iterator to second (non-skipped) data point because adaptive sampling works in 1 point retrospect:
  18406. if (!doScatterSkip)
  18407. ++it;
  18408. else
  18409. {
  18410. itIndex += scatterModulo;
  18411. if (itIndex < endIndex) // make sure we didn't jump over end
  18412. it += scatterModulo;
  18413. else
  18414. {
  18415. it = end;
  18416. itIndex = endIndex;
  18417. }
  18418. }
  18419. // main loop over data points:
  18420. while (it != end)
  18421. {
  18422. if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary
  18423. {
  18424. if (it->value < minValue && it->value > valueMinRange && it->value < valueMaxRange)
  18425. {
  18426. minValue = it->value;
  18427. minValueIt = it;
  18428. } else if (it->value > maxValue && it->value > valueMinRange && it->value < valueMaxRange)
  18429. {
  18430. maxValue = it->value;
  18431. maxValueIt = it;
  18432. }
  18433. ++intervalDataCount;
  18434. } else // new pixel started
  18435. {
  18436. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  18437. {
  18438. // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
  18439. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
  18440. int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
  18441. QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
  18442. int c = 0;
  18443. while (intervalIt != it)
  18444. {
  18445. if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
  18446. scatterData->append(*intervalIt);
  18447. ++c;
  18448. if (!doScatterSkip)
  18449. ++intervalIt;
  18450. else
  18451. intervalIt += scatterModulo; // since we know indices of "currentIntervalStart", "intervalIt" and "it" are multiples of scatterModulo, we can't accidentally jump over "it" here
  18452. }
  18453. } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
  18454. scatterData->append(*currentIntervalStart);
  18455. minValue = it->value;
  18456. maxValue = it->value;
  18457. currentIntervalStart = it;
  18458. currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(it->key)+reversedRound));
  18459. if (keyEpsilonVariable)
  18460. keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
  18461. intervalDataCount = 1;
  18462. }
  18463. // advance to next data point:
  18464. if (!doScatterSkip)
  18465. ++it;
  18466. else
  18467. {
  18468. itIndex += scatterModulo;
  18469. if (itIndex < endIndex) // make sure we didn't jump over end
  18470. it += scatterModulo;
  18471. else
  18472. {
  18473. it = end;
  18474. itIndex = endIndex;
  18475. }
  18476. }
  18477. }
  18478. // handle last interval:
  18479. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  18480. {
  18481. // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
  18482. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
  18483. int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
  18484. QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
  18485. int intervalItIndex = int(intervalIt-mDataContainer->constBegin());
  18486. int c = 0;
  18487. while (intervalIt != it)
  18488. {
  18489. if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
  18490. scatterData->append(*intervalIt);
  18491. ++c;
  18492. if (!doScatterSkip)
  18493. ++intervalIt;
  18494. else // here we can't guarantee that adding scatterModulo doesn't exceed "it" (because "it" is equal to "end" here, and "end" isn't scatterModulo-aligned), so check via index comparison:
  18495. {
  18496. intervalItIndex += scatterModulo;
  18497. if (intervalItIndex < itIndex)
  18498. intervalIt += scatterModulo;
  18499. else
  18500. {
  18501. intervalIt = it;
  18502. intervalItIndex = itIndex;
  18503. }
  18504. }
  18505. }
  18506. } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
  18507. scatterData->append(*currentIntervalStart);
  18508. } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
  18509. {
  18510. QCPGraphDataContainer::const_iterator it = begin;
  18511. int itIndex = beginIndex;
  18512. scatterData->reserve(dataCount);
  18513. while (it != end)
  18514. {
  18515. scatterData->append(*it);
  18516. // advance to next data point:
  18517. if (!doScatterSkip)
  18518. ++it;
  18519. else
  18520. {
  18521. itIndex += scatterModulo;
  18522. if (itIndex < endIndex)
  18523. it += scatterModulo;
  18524. else
  18525. {
  18526. it = end;
  18527. itIndex = endIndex;
  18528. }
  18529. }
  18530. }
  18531. }
  18532. }
  18533. /*!
  18534. This method outputs the currently visible data range via \a begin and \a end. The returned range
  18535. will also never exceed \a rangeRestriction.
  18536. This method takes into account that the drawing of data lines at the axis rect border always
  18537. requires the points just outside the visible axis range. So \a begin and \a end may actually
  18538. indicate a range that contains one additional data point to the left and right of the visible
  18539. axis range.
  18540. */
  18541. void QCPGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
  18542. {
  18543. if (rangeRestriction.isEmpty())
  18544. {
  18545. end = mDataContainer->constEnd();
  18546. begin = end;
  18547. } else
  18548. {
  18549. QCPAxis *keyAxis = mKeyAxis.data();
  18550. QCPAxis *valueAxis = mValueAxis.data();
  18551. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  18552. // get visible data range:
  18553. begin = mDataContainer->findBegin(keyAxis->range().lower);
  18554. end = mDataContainer->findEnd(keyAxis->range().upper);
  18555. // limit lower/upperEnd to rangeRestriction:
  18556. mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
  18557. }
  18558. }
  18559. /*! \internal
  18560. This method goes through the passed points in \a lineData and returns a list of the segments
  18561. which don't contain NaN data points.
  18562. \a keyOrientation defines whether the \a x or \a y member of the passed QPointF is used to check
  18563. for NaN. If \a keyOrientation is \c Qt::Horizontal, the \a y member is checked, if it is \c
  18564. Qt::Vertical, the \a x member is checked.
  18565. \see getOverlappingSegments, drawFill
  18566. */
  18567. QVector<QCPDataRange> QCPGraph::getNonNanSegments(const QVector<QPointF> *lineData, Qt::Orientation keyOrientation) const
  18568. {
  18569. QVector<QCPDataRange> result;
  18570. const int n = lineData->size();
  18571. QCPDataRange currentSegment(-1, -1);
  18572. int i = 0;
  18573. if (keyOrientation == Qt::Horizontal)
  18574. {
  18575. while (i < n)
  18576. {
  18577. while (i < n && qIsNaN(lineData->at(i).y())) // seek next non-NaN data point
  18578. ++i;
  18579. if (i == n)
  18580. break;
  18581. currentSegment.setBegin(i++);
  18582. while (i < n && !qIsNaN(lineData->at(i).y())) // seek next NaN data point or end of data
  18583. ++i;
  18584. currentSegment.setEnd(i++);
  18585. result.append(currentSegment);
  18586. }
  18587. } else // keyOrientation == Qt::Vertical
  18588. {
  18589. while (i < n)
  18590. {
  18591. while (i < n && qIsNaN(lineData->at(i).x())) // seek next non-NaN data point
  18592. ++i;
  18593. if (i == n)
  18594. break;
  18595. currentSegment.setBegin(i++);
  18596. while (i < n && !qIsNaN(lineData->at(i).x())) // seek next NaN data point or end of data
  18597. ++i;
  18598. currentSegment.setEnd(i++);
  18599. result.append(currentSegment);
  18600. }
  18601. }
  18602. return result;
  18603. }
  18604. /*! \internal
  18605. This method takes two segment lists (e.g. created by \ref getNonNanSegments) \a thisSegments and
  18606. \a otherSegments, and their associated point data \a thisData and \a otherData.
  18607. It returns all pairs of segments (the first from \a thisSegments, the second from \a
  18608. otherSegments), which overlap in plot coordinates.
  18609. This method is useful in the case of a channel fill between two graphs, when only those non-NaN
  18610. segments which actually overlap in their key coordinate shall be considered for drawing a channel
  18611. fill polygon.
  18612. It is assumed that the passed segments in \a thisSegments are ordered ascending by index, and
  18613. that the segments don't overlap themselves. The same is assumed for the segments in \a
  18614. otherSegments. This is fulfilled when the segments are obtained via \ref getNonNanSegments.
  18615. \see getNonNanSegments, segmentsIntersect, drawFill, getChannelFillPolygon
  18616. */
  18617. QVector<QPair<QCPDataRange, QCPDataRange> > QCPGraph::getOverlappingSegments(QVector<QCPDataRange> thisSegments, const QVector<QPointF> *thisData, QVector<QCPDataRange> otherSegments, const QVector<QPointF> *otherData) const
  18618. {
  18619. QVector<QPair<QCPDataRange, QCPDataRange> > result;
  18620. if (thisData->isEmpty() || otherData->isEmpty() || thisSegments.isEmpty() || otherSegments.isEmpty())
  18621. return result;
  18622. int thisIndex = 0;
  18623. int otherIndex = 0;
  18624. const bool verticalKey = mKeyAxis->orientation() == Qt::Vertical;
  18625. while (thisIndex < thisSegments.size() && otherIndex < otherSegments.size())
  18626. {
  18627. if (thisSegments.at(thisIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow
  18628. {
  18629. ++thisIndex;
  18630. continue;
  18631. }
  18632. if (otherSegments.at(otherIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow
  18633. {
  18634. ++otherIndex;
  18635. continue;
  18636. }
  18637. double thisLower, thisUpper, otherLower, otherUpper;
  18638. if (!verticalKey)
  18639. {
  18640. thisLower = thisData->at(thisSegments.at(thisIndex).begin()).x();
  18641. thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).x();
  18642. otherLower = otherData->at(otherSegments.at(otherIndex).begin()).x();
  18643. otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).x();
  18644. } else
  18645. {
  18646. thisLower = thisData->at(thisSegments.at(thisIndex).begin()).y();
  18647. thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).y();
  18648. otherLower = otherData->at(otherSegments.at(otherIndex).begin()).y();
  18649. otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).y();
  18650. }
  18651. int bPrecedence;
  18652. if (segmentsIntersect(thisLower, thisUpper, otherLower, otherUpper, bPrecedence))
  18653. result.append(QPair<QCPDataRange, QCPDataRange>(thisSegments.at(thisIndex), otherSegments.at(otherIndex)));
  18654. if (bPrecedence <= 0) // otherSegment doesn't reach as far as thisSegment, so continue with next otherSegment, keeping current thisSegment
  18655. ++otherIndex;
  18656. else // otherSegment reaches further than thisSegment, so continue with next thisSegment, keeping current otherSegment
  18657. ++thisIndex;
  18658. }
  18659. return result;
  18660. }
  18661. /*! \internal
  18662. Returns whether the segments defined by the coordinates (aLower, aUpper) and (bLower, bUpper)
  18663. have overlap.
  18664. The output parameter \a bPrecedence indicates whether the \a b segment reaches farther than the
  18665. \a a segment or not. If \a bPrecedence returns 1, segment \a b reaches the farthest to higher
  18666. coordinates (i.e. bUpper > aUpper). If it returns -1, segment \a a reaches the farthest. Only if
  18667. both segment's upper bounds are identical, 0 is returned as \a bPrecedence.
  18668. It is assumed that the lower bounds always have smaller or equal values than the upper bounds.
  18669. \see getOverlappingSegments
  18670. */
  18671. bool QCPGraph::segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const
  18672. {
  18673. bPrecedence = 0;
  18674. if (aLower > bUpper)
  18675. {
  18676. bPrecedence = -1;
  18677. return false;
  18678. } else if (bLower > aUpper)
  18679. {
  18680. bPrecedence = 1;
  18681. return false;
  18682. } else
  18683. {
  18684. if (aUpper > bUpper)
  18685. bPrecedence = -1;
  18686. else if (aUpper < bUpper)
  18687. bPrecedence = 1;
  18688. return true;
  18689. }
  18690. }
  18691. /*! \internal
  18692. Returns the point which closes the fill polygon on the zero-value-line parallel to the key axis.
  18693. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates
  18694. is in positive or negative infinity. So this case is handled separately by just closing the fill
  18695. polygon on the axis which lies in the direction towards the zero value.
  18696. \a matchingDataPoint will provide the key (in pixels) of the returned point. Depending on whether
  18697. the key axis of this graph is horizontal or vertical, \a matchingDataPoint will provide the x or
  18698. y value of the returned point, respectively.
  18699. */
  18700. QPointF QCPGraph::getFillBasePoint(QPointF matchingDataPoint) const
  18701. {
  18702. QCPAxis *keyAxis = mKeyAxis.data();
  18703. QCPAxis *valueAxis = mValueAxis.data();
  18704. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  18705. QPointF result;
  18706. if (valueAxis->scaleType() == QCPAxis::stLinear)
  18707. {
  18708. if (keyAxis->orientation() == Qt::Horizontal)
  18709. {
  18710. result.setX(matchingDataPoint.x());
  18711. result.setY(valueAxis->coordToPixel(0));
  18712. } else // keyAxis->orientation() == Qt::Vertical
  18713. {
  18714. result.setX(valueAxis->coordToPixel(0));
  18715. result.setY(matchingDataPoint.y());
  18716. }
  18717. } else // valueAxis->mScaleType == QCPAxis::stLogarithmic
  18718. {
  18719. // In logarithmic scaling we can't just draw to value 0 so we just fill all the way
  18720. // to the axis which is in the direction towards 0
  18721. if (keyAxis->orientation() == Qt::Vertical)
  18722. {
  18723. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  18724. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  18725. result.setX(keyAxis->axisRect()->right());
  18726. else
  18727. result.setX(keyAxis->axisRect()->left());
  18728. result.setY(matchingDataPoint.y());
  18729. } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom)
  18730. {
  18731. result.setX(matchingDataPoint.x());
  18732. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  18733. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  18734. result.setY(keyAxis->axisRect()->top());
  18735. else
  18736. result.setY(keyAxis->axisRect()->bottom());
  18737. }
  18738. }
  18739. return result;
  18740. }
  18741. /*! \internal
  18742. Returns the polygon needed for drawing normal fills between this graph and the key axis.
  18743. Pass the graph's data points (in pixel coordinates) as \a lineData, and specify the \a segment
  18744. which shall be used for the fill. The collection of \a lineData points described by \a segment
  18745. must not contain NaN data points (see \ref getNonNanSegments).
  18746. The returned fill polygon will be closed at the key axis (the zero-value line) for linear value
  18747. axes. For logarithmic value axes the polygon will reach just beyond the corresponding axis rect
  18748. side (see \ref getFillBasePoint).
  18749. For increased performance (due to implicit sharing), keep the returned QPolygonF const.
  18750. \see drawFill, getNonNanSegments
  18751. */
  18752. const QPolygonF QCPGraph::getFillPolygon(const QVector<QPointF> *lineData, QCPDataRange segment) const
  18753. {
  18754. if (segment.size() < 2)
  18755. return QPolygonF();
  18756. QPolygonF result(segment.size()+2);
  18757. result[0] = getFillBasePoint(lineData->at(segment.begin()));
  18758. std::copy(lineData->constBegin()+segment.begin(), lineData->constBegin()+segment.end(), result.begin()+1);
  18759. result[result.size()-1] = getFillBasePoint(lineData->at(segment.end()-1));
  18760. return result;
  18761. }
  18762. /*! \internal
  18763. Returns the polygon needed for drawing (partial) channel fills between this graph and the graph
  18764. specified by \ref setChannelFillGraph.
  18765. The data points of this graph are passed as pixel coordinates via \a thisData, the data of the
  18766. other graph as \a otherData. The returned polygon will be calculated for the specified data
  18767. segments \a thisSegment and \a otherSegment, pertaining to the respective \a thisData and \a
  18768. otherData, respectively.
  18769. The passed \a thisSegment and \a otherSegment should correspond to the segment pairs returned by
  18770. \ref getOverlappingSegments, to make sure only segments that actually have key coordinate overlap
  18771. need to be processed here.
  18772. For increased performance due to implicit sharing, keep the returned QPolygonF const.
  18773. \see drawFill, getOverlappingSegments, getNonNanSegments
  18774. */
  18775. const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *thisData, QCPDataRange thisSegment, const QVector<QPointF> *otherData, QCPDataRange otherSegment) const
  18776. {
  18777. if (!mChannelFillGraph)
  18778. return QPolygonF();
  18779. QCPAxis *keyAxis = mKeyAxis.data();
  18780. QCPAxis *valueAxis = mValueAxis.data();
  18781. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); }
  18782. if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); }
  18783. if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation())
  18784. return QPolygonF(); // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis)
  18785. if (thisData->isEmpty()) return QPolygonF();
  18786. QVector<QPointF> thisSegmentData(thisSegment.size());
  18787. QVector<QPointF> otherSegmentData(otherSegment.size());
  18788. std::copy(thisData->constBegin()+thisSegment.begin(), thisData->constBegin()+thisSegment.end(), thisSegmentData.begin());
  18789. std::copy(otherData->constBegin()+otherSegment.begin(), otherData->constBegin()+otherSegment.end(), otherSegmentData.begin());
  18790. // pointers to be able to swap them, depending which data range needs cropping:
  18791. QVector<QPointF> *staticData = &thisSegmentData;
  18792. QVector<QPointF> *croppedData = &otherSegmentData;
  18793. // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType):
  18794. if (keyAxis->orientation() == Qt::Horizontal)
  18795. {
  18796. // x is key
  18797. // crop lower bound:
  18798. if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
  18799. qSwap(staticData, croppedData);
  18800. const int lowBound = findIndexBelowX(croppedData, staticData->first().x());
  18801. if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
  18802. croppedData->remove(0, lowBound);
  18803. // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
  18804. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18805. double slope;
  18806. if (!qFuzzyCompare(croppedData->at(1).x(), croppedData->at(0).x()))
  18807. slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x());
  18808. else
  18809. slope = 0;
  18810. (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x()));
  18811. (*croppedData)[0].setX(staticData->first().x());
  18812. // crop upper bound:
  18813. if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
  18814. qSwap(staticData, croppedData);
  18815. int highBound = findIndexAboveX(croppedData, staticData->last().x());
  18816. if (highBound == -1) return QPolygonF(); // key ranges have no overlap
  18817. croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
  18818. // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
  18819. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18820. const int li = croppedData->size()-1; // last index
  18821. if (!qFuzzyCompare(croppedData->at(li).x(), croppedData->at(li-1).x()))
  18822. slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x());
  18823. else
  18824. slope = 0;
  18825. (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x()));
  18826. (*croppedData)[li].setX(staticData->last().x());
  18827. } else // mKeyAxis->orientation() == Qt::Vertical
  18828. {
  18829. // y is key
  18830. // crop lower bound:
  18831. if (staticData->first().y() < croppedData->first().y()) // other one must be cropped
  18832. qSwap(staticData, croppedData);
  18833. int lowBound = findIndexBelowY(croppedData, staticData->first().y());
  18834. if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
  18835. croppedData->remove(0, lowBound);
  18836. // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
  18837. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18838. double slope;
  18839. if (!qFuzzyCompare(croppedData->at(1).y(), croppedData->at(0).y())) // avoid division by zero in step plots
  18840. slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y());
  18841. else
  18842. slope = 0;
  18843. (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y()));
  18844. (*croppedData)[0].setY(staticData->first().y());
  18845. // crop upper bound:
  18846. if (staticData->last().y() > croppedData->last().y()) // other one must be cropped
  18847. qSwap(staticData, croppedData);
  18848. int highBound = findIndexAboveY(croppedData, staticData->last().y());
  18849. if (highBound == -1) return QPolygonF(); // key ranges have no overlap
  18850. croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
  18851. // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
  18852. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18853. int li = croppedData->size()-1; // last index
  18854. if (!qFuzzyCompare(croppedData->at(li).y(), croppedData->at(li-1).y())) // avoid division by zero in step plots
  18855. slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y());
  18856. else
  18857. slope = 0;
  18858. (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y()));
  18859. (*croppedData)[li].setY(staticData->last().y());
  18860. }
  18861. // return joined:
  18862. for (int i=otherSegmentData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted
  18863. thisSegmentData << otherSegmentData.at(i);
  18864. return QPolygonF(thisSegmentData);
  18865. }
  18866. /*! \internal
  18867. Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in
  18868. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18869. axis is horizontal.
  18870. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18871. */
  18872. int QCPGraph::findIndexAboveX(const QVector<QPointF> *data, double x) const
  18873. {
  18874. for (int i=data->size()-1; i>=0; --i)
  18875. {
  18876. if (data->at(i).x() < x)
  18877. {
  18878. if (i<data->size()-1)
  18879. return i+1;
  18880. else
  18881. return data->size()-1;
  18882. }
  18883. }
  18884. return -1;
  18885. }
  18886. /*! \internal
  18887. Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in
  18888. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18889. axis is horizontal.
  18890. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18891. */
  18892. int QCPGraph::findIndexBelowX(const QVector<QPointF> *data, double x) const
  18893. {
  18894. for (int i=0; i<data->size(); ++i)
  18895. {
  18896. if (data->at(i).x() > x)
  18897. {
  18898. if (i>0)
  18899. return i-1;
  18900. else
  18901. return 0;
  18902. }
  18903. }
  18904. return -1;
  18905. }
  18906. /*! \internal
  18907. Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in
  18908. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18909. axis is vertical.
  18910. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18911. */
  18912. int QCPGraph::findIndexAboveY(const QVector<QPointF> *data, double y) const
  18913. {
  18914. for (int i=data->size()-1; i>=0; --i)
  18915. {
  18916. if (data->at(i).y() < y)
  18917. {
  18918. if (i<data->size()-1)
  18919. return i+1;
  18920. else
  18921. return data->size()-1;
  18922. }
  18923. }
  18924. return -1;
  18925. }
  18926. /*! \internal
  18927. Calculates the minimum distance in pixels the graph's representation has from the given \a
  18928. pixelPoint. This is used to determine whether the graph was clicked or not, e.g. in \ref
  18929. selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that if
  18930. the graph has a line representation, the returned distance may be smaller than the distance to
  18931. the \a closestData point, since the distance to the graph line is also taken into account.
  18932. If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape
  18933. is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns -1.0.
  18934. */
  18935. double QCPGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
  18936. {
  18937. closestData = mDataContainer->constEnd();
  18938. if (mDataContainer->isEmpty())
  18939. return -1.0;
  18940. if (mLineStyle == lsNone && mScatterStyle.isNone())
  18941. return -1.0;
  18942. // calculate minimum distances to graph data points and find closestData iterator:
  18943. double minDistSqr = (std::numeric_limits<double>::max)();
  18944. // determine which key range comes into question, taking selection tolerance around pos into account:
  18945. double posKeyMin, posKeyMax, dummy;
  18946. pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
  18947. pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
  18948. if (posKeyMin > posKeyMax)
  18949. qSwap(posKeyMin, posKeyMax);
  18950. // iterate over found data points and then choose the one with the shortest distance to pos:
  18951. QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
  18952. QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
  18953. for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
  18954. {
  18955. const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
  18956. if (currentDistSqr < minDistSqr)
  18957. {
  18958. minDistSqr = currentDistSqr;
  18959. closestData = it;
  18960. }
  18961. }
  18962. // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
  18963. if (mLineStyle != lsNone)
  18964. {
  18965. // line displayed, calculate distance to line segments:
  18966. QVector<QPointF> lineData;
  18967. getLines(&lineData, QCPDataRange(0, dataCount())); // don't limit data range further since with sharp data spikes, line segments may be closer to test point than segments with closer key coordinate
  18968. QCPVector2D p(pixelPoint);
  18969. const int step = mLineStyle==lsImpulse ? 2 : 1; // impulse plot differs from other line styles in that the lineData points are only pairwise connected
  18970. for (int i=0; i<lineData.size()-1; i+=step)
  18971. {
  18972. const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
  18973. if (currentDistSqr < minDistSqr)
  18974. minDistSqr = currentDistSqr;
  18975. }
  18976. }
  18977. return qSqrt(minDistSqr);
  18978. }
  18979. /*! \internal
  18980. Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in
  18981. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18982. axis is vertical.
  18983. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18984. */
  18985. int QCPGraph::findIndexBelowY(const QVector<QPointF> *data, double y) const
  18986. {
  18987. for (int i=0; i<data->size(); ++i)
  18988. {
  18989. if (data->at(i).y() > y)
  18990. {
  18991. if (i>0)
  18992. return i-1;
  18993. else
  18994. return 0;
  18995. }
  18996. }
  18997. return -1;
  18998. }
  18999. /* end of 'src/plottables/plottable-graph.cpp' */
  19000. /* including file 'src/plottables/plottable-curve.cpp' */
  19001. /* modified 2021-03-29T02:30:44, size 63851 */
  19002. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19003. //////////////////// QCPCurveData
  19004. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19005. /*! \class QCPCurveData
  19006. \brief Holds the data of one single data point for QCPCurve.
  19007. The stored data is:
  19008. \li \a t: the free ordering parameter of this curve point, like in the mathematical vector <em>(x(t), y(t))</em>. (This is the \a sortKey)
  19009. \li \a key: coordinate on the key axis of this curve point (this is the \a mainKey)
  19010. \li \a value: coordinate on the value axis of this curve point (this is the \a mainValue)
  19011. The container for storing multiple data points is \ref QCPCurveDataContainer. It is a typedef for
  19012. \ref QCPDataContainer with \ref QCPCurveData as the DataType template parameter. See the
  19013. documentation there for an explanation regarding the data type's generic methods.
  19014. \see QCPCurveDataContainer
  19015. */
  19016. /* start documentation of inline functions */
  19017. /*! \fn double QCPCurveData::sortKey() const
  19018. Returns the \a t member of this data point.
  19019. For a general explanation of what this method is good for in the context of the data container,
  19020. see the documentation of \ref QCPDataContainer.
  19021. */
  19022. /*! \fn static QCPCurveData QCPCurveData::fromSortKey(double sortKey)
  19023. Returns a data point with the specified \a sortKey (assigned to the data point's \a t member).
  19024. All other members are set to zero.
  19025. For a general explanation of what this method is good for in the context of the data container,
  19026. see the documentation of \ref QCPDataContainer.
  19027. */
  19028. /*! \fn static static bool QCPCurveData::sortKeyIsMainKey()
  19029. Since the member \a key is the data point key coordinate and the member \a t is the data ordering
  19030. parameter, this method returns false.
  19031. For a general explanation of what this method is good for in the context of the data container,
  19032. see the documentation of \ref QCPDataContainer.
  19033. */
  19034. /*! \fn double QCPCurveData::mainKey() const
  19035. Returns the \a key member of this data point.
  19036. For a general explanation of what this method is good for in the context of the data container,
  19037. see the documentation of \ref QCPDataContainer.
  19038. */
  19039. /*! \fn double QCPCurveData::mainValue() const
  19040. Returns the \a value member of this data point.
  19041. For a general explanation of what this method is good for in the context of the data container,
  19042. see the documentation of \ref QCPDataContainer.
  19043. */
  19044. /*! \fn QCPRange QCPCurveData::valueRange() const
  19045. Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
  19046. For a general explanation of what this method is good for in the context of the data container,
  19047. see the documentation of \ref QCPDataContainer.
  19048. */
  19049. /* end documentation of inline functions */
  19050. /*!
  19051. Constructs a curve data point with t, key and value set to zero.
  19052. */
  19053. QCPCurveData::QCPCurveData() :
  19054. t(0),
  19055. key(0),
  19056. value(0)
  19057. {
  19058. }
  19059. /*!
  19060. Constructs a curve data point with the specified \a t, \a key and \a value.
  19061. */
  19062. QCPCurveData::QCPCurveData(double t, double key, double value) :
  19063. t(t),
  19064. key(key),
  19065. value(value)
  19066. {
  19067. }
  19068. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19069. //////////////////// QCPCurve
  19070. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19071. /*! \class QCPCurve
  19072. \brief A plottable representing a parametric curve in a plot.
  19073. \image html QCPCurve.png
  19074. Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate,
  19075. so their visual representation can have \a loops. This is realized by introducing a third
  19076. coordinate \a t, which defines the order of the points described by the other two coordinates \a
  19077. x and \a y.
  19078. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  19079. also access and modify the curve's data via the \ref data method, which returns a pointer to the
  19080. internal \ref QCPCurveDataContainer.
  19081. Gaps in the curve can be created by adding data points with NaN as key and value
  19082. (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
  19083. separated.
  19084. \section qcpcurve-appearance Changing the appearance
  19085. The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush).
  19086. \section qcpcurve-usage Usage
  19087. Like all data representing objects in QCustomPlot, the QCPCurve is a plottable
  19088. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  19089. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  19090. Usually, you first create an instance:
  19091. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1
  19092. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  19093. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  19094. The newly created plottable can be modified, e.g.:
  19095. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2
  19096. */
  19097. /* start of documentation of inline functions */
  19098. /*! \fn QSharedPointer<QCPCurveDataContainer> QCPCurve::data() const
  19099. Returns a shared pointer to the internal data storage of type \ref QCPCurveDataContainer. You may
  19100. use it to directly manipulate the data, which may be more convenient and faster than using the
  19101. regular \ref setData or \ref addData methods.
  19102. */
  19103. /* end of documentation of inline functions */
  19104. /*!
  19105. Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  19106. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  19107. the same orientation. If either of these restrictions is violated, a corresponding message is
  19108. printed to the debug output (qDebug), the construction is not aborted, though.
  19109. The created QCPCurve is automatically registered with the QCustomPlot instance inferred from \a
  19110. keyAxis. This QCustomPlot instance takes ownership of the QCPCurve, so do not delete it manually
  19111. but use QCustomPlot::removePlottable() instead.
  19112. */
  19113. QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  19114. QCPAbstractPlottable1D<QCPCurveData>(keyAxis, valueAxis),
  19115. mScatterSkip{},
  19116. mLineStyle{}
  19117. {
  19118. // modify inherited properties from abstract plottable:
  19119. setPen(QPen(Qt::blue, 0));
  19120. setBrush(Qt::NoBrush);
  19121. setScatterStyle(QCPScatterStyle());
  19122. setLineStyle(lsLine);
  19123. setScatterSkip(0);
  19124. }
  19125. QCPCurve::~QCPCurve()
  19126. {
  19127. }
  19128. /*! \overload
  19129. Replaces the current data container with the provided \a data container.
  19130. Since a QSharedPointer is used, multiple QCPCurves may share the same data container safely.
  19131. Modifying the data in the container will then affect all curves that share the container. Sharing
  19132. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  19133. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-1
  19134. If you do not wish to share containers, but create a copy from an existing container, rather use
  19135. the \ref QCPDataContainer<DataType>::set method on the curve's data container directly:
  19136. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-2
  19137. \see addData
  19138. */
  19139. void QCPCurve::setData(QSharedPointer<QCPCurveDataContainer> data)
  19140. {
  19141. mDataContainer = data;
  19142. }
  19143. /*! \overload
  19144. Replaces the current data with the provided points in \a t, \a keys and \a values. The provided
  19145. vectors should have equal length. Else, the number of added points will be the size of the
  19146. smallest vector.
  19147. If you can guarantee that the passed data points are sorted by \a t in ascending order, you can
  19148. set \a alreadySorted to true, to improve performance by saving a sorting run.
  19149. \see addData
  19150. */
  19151. void QCPCurve::setData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  19152. {
  19153. mDataContainer->clear();
  19154. addData(t, keys, values, alreadySorted);
  19155. }
  19156. /*! \overload
  19157. Replaces the current data with the provided points in \a keys and \a values. The provided vectors
  19158. should have equal length. Else, the number of added points will be the size of the smallest
  19159. vector.
  19160. The t parameter of each data point will be set to the integer index of the respective key/value
  19161. pair.
  19162. \see addData
  19163. */
  19164. void QCPCurve::setData(const QVector<double> &keys, const QVector<double> &values)
  19165. {
  19166. mDataContainer->clear();
  19167. addData(keys, values);
  19168. }
  19169. /*!
  19170. Sets the visual appearance of single data points in the plot. If set to \ref
  19171. QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate
  19172. line style).
  19173. \see QCPScatterStyle, setLineStyle
  19174. */
  19175. void QCPCurve::setScatterStyle(const QCPScatterStyle &style)
  19176. {
  19177. mScatterStyle = style;
  19178. }
  19179. /*!
  19180. If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
  19181. scatter points are skipped/not drawn after every drawn scatter point.
  19182. This can be used to make the data appear sparser while for example still having a smooth line,
  19183. and to improve performance for very high density plots.
  19184. If \a skip is set to 0 (default), all scatter points are drawn.
  19185. \see setScatterStyle
  19186. */
  19187. void QCPCurve::setScatterSkip(int skip)
  19188. {
  19189. mScatterSkip = qMax(0, skip);
  19190. }
  19191. /*!
  19192. Sets how the single data points are connected in the plot or how they are represented visually
  19193. apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref
  19194. setScatterStyle to the desired scatter style.
  19195. \see setScatterStyle
  19196. */
  19197. void QCPCurve::setLineStyle(QCPCurve::LineStyle style)
  19198. {
  19199. mLineStyle = style;
  19200. }
  19201. /*! \overload
  19202. Adds the provided points in \a t, \a keys and \a values to the current data. The provided vectors
  19203. should have equal length. Else, the number of added points will be the size of the smallest
  19204. vector.
  19205. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  19206. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  19207. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19208. returns a pointer to the internal data container.
  19209. */
  19210. void QCPCurve::addData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  19211. {
  19212. if (t.size() != keys.size() || t.size() != values.size())
  19213. qDebug() << Q_FUNC_INFO << "ts, keys and values have different sizes:" << t.size() << keys.size() << values.size();
  19214. const int n = qMin(qMin(t.size(), keys.size()), values.size());
  19215. QVector<QCPCurveData> tempData(n);
  19216. QVector<QCPCurveData>::iterator it = tempData.begin();
  19217. const QVector<QCPCurveData>::iterator itEnd = tempData.end();
  19218. int i = 0;
  19219. while (it != itEnd)
  19220. {
  19221. it->t = t[i];
  19222. it->key = keys[i];
  19223. it->value = values[i];
  19224. ++it;
  19225. ++i;
  19226. }
  19227. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  19228. }
  19229. /*! \overload
  19230. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  19231. should have equal length. Else, the number of added points will be the size of the smallest
  19232. vector.
  19233. The t parameter of each data point will be set to the integer index of the respective key/value
  19234. pair.
  19235. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19236. returns a pointer to the internal data container.
  19237. */
  19238. void QCPCurve::addData(const QVector<double> &keys, const QVector<double> &values)
  19239. {
  19240. if (keys.size() != values.size())
  19241. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  19242. const int n = qMin(keys.size(), values.size());
  19243. double tStart;
  19244. if (!mDataContainer->isEmpty())
  19245. tStart = (mDataContainer->constEnd()-1)->t + 1.0;
  19246. else
  19247. tStart = 0;
  19248. QVector<QCPCurveData> tempData(n);
  19249. QVector<QCPCurveData>::iterator it = tempData.begin();
  19250. const QVector<QCPCurveData>::iterator itEnd = tempData.end();
  19251. int i = 0;
  19252. while (it != itEnd)
  19253. {
  19254. it->t = tStart + i;
  19255. it->key = keys[i];
  19256. it->value = values[i];
  19257. ++it;
  19258. ++i;
  19259. }
  19260. mDataContainer->add(tempData, true); // don't modify tempData beyond this to prevent copy on write
  19261. }
  19262. /*! \overload
  19263. Adds the provided data point as \a t, \a key and \a value to the current data.
  19264. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19265. returns a pointer to the internal data container.
  19266. */
  19267. void QCPCurve::addData(double t, double key, double value)
  19268. {
  19269. mDataContainer->add(QCPCurveData(t, key, value));
  19270. }
  19271. /*! \overload
  19272. Adds the provided data point as \a key and \a value to the current data.
  19273. The t parameter is generated automatically by increments of 1 for each point, starting at the
  19274. highest t of previously existing data or 0, if the curve data is empty.
  19275. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19276. returns a pointer to the internal data container.
  19277. */
  19278. void QCPCurve::addData(double key, double value)
  19279. {
  19280. if (!mDataContainer->isEmpty())
  19281. mDataContainer->add(QCPCurveData((mDataContainer->constEnd()-1)->t + 1.0, key, value));
  19282. else
  19283. mDataContainer->add(QCPCurveData(0.0, key, value));
  19284. }
  19285. /*!
  19286. Implements a selectTest specific to this plottable's point geometry.
  19287. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  19288. point to \a pos.
  19289. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  19290. */
  19291. double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  19292. {
  19293. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  19294. return -1;
  19295. if (!mKeyAxis || !mValueAxis)
  19296. return -1;
  19297. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  19298. {
  19299. QCPCurveDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  19300. double result = pointDistance(pos, closestDataPoint);
  19301. if (details)
  19302. {
  19303. int pointIndex = int( closestDataPoint-mDataContainer->constBegin() );
  19304. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  19305. }
  19306. return result;
  19307. } else
  19308. return -1;
  19309. }
  19310. /* inherits documentation from base class */
  19311. QCPRange QCPCurve::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  19312. {
  19313. return mDataContainer->keyRange(foundRange, inSignDomain);
  19314. }
  19315. /* inherits documentation from base class */
  19316. QCPRange QCPCurve::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  19317. {
  19318. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  19319. }
  19320. /* inherits documentation from base class */
  19321. void QCPCurve::draw(QCPPainter *painter)
  19322. {
  19323. if (mDataContainer->isEmpty()) return;
  19324. // allocate line vector:
  19325. QVector<QPointF> lines, scatters;
  19326. // loop over and draw segments of unselected/selected data:
  19327. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  19328. getDataSegments(selectedSegments, unselectedSegments);
  19329. allSegments << unselectedSegments << selectedSegments;
  19330. for (int i=0; i<allSegments.size(); ++i)
  19331. {
  19332. bool isSelectedSegment = i >= unselectedSegments.size();
  19333. // fill with curve data:
  19334. QPen finalCurvePen = mPen; // determine the final pen already here, because the line optimization depends on its stroke width
  19335. if (isSelectedSegment && mSelectionDecorator)
  19336. finalCurvePen = mSelectionDecorator->pen();
  19337. QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getCurveLines takes care)
  19338. getCurveLines(&lines, lineDataRange, finalCurvePen.widthF());
  19339. // check data validity if flag set:
  19340. #ifdef QCUSTOMPLOT_CHECK_DATA
  19341. for (QCPCurveDataContainer::const_iterator it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  19342. {
  19343. if (QCP::isInvalidData(it->t) ||
  19344. QCP::isInvalidData(it->key, it->value))
  19345. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
  19346. }
  19347. #endif
  19348. // draw curve fill:
  19349. applyFillAntialiasingHint(painter);
  19350. if (isSelectedSegment && mSelectionDecorator)
  19351. mSelectionDecorator->applyBrush(painter);
  19352. else
  19353. painter->setBrush(mBrush);
  19354. painter->setPen(Qt::NoPen);
  19355. if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
  19356. painter->drawPolygon(QPolygonF(lines));
  19357. // draw curve line:
  19358. if (mLineStyle != lsNone)
  19359. {
  19360. painter->setPen(finalCurvePen);
  19361. painter->setBrush(Qt::NoBrush);
  19362. drawCurveLine(painter, lines);
  19363. }
  19364. // draw scatters:
  19365. QCPScatterStyle finalScatterStyle = mScatterStyle;
  19366. if (isSelectedSegment && mSelectionDecorator)
  19367. finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
  19368. if (!finalScatterStyle.isNone())
  19369. {
  19370. getScatters(&scatters, allSegments.at(i), finalScatterStyle.size());
  19371. drawScatterPlot(painter, scatters, finalScatterStyle);
  19372. }
  19373. }
  19374. // draw other selection decoration that isn't just line/scatter pens and brushes:
  19375. if (mSelectionDecorator)
  19376. mSelectionDecorator->drawDecoration(painter, selection());
  19377. }
  19378. /* inherits documentation from base class */
  19379. void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  19380. {
  19381. // draw fill:
  19382. if (mBrush.style() != Qt::NoBrush)
  19383. {
  19384. applyFillAntialiasingHint(painter);
  19385. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  19386. }
  19387. // draw line vertically centered:
  19388. if (mLineStyle != lsNone)
  19389. {
  19390. applyDefaultAntialiasingHint(painter);
  19391. painter->setPen(mPen);
  19392. painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
  19393. }
  19394. // draw scatter symbol:
  19395. if (!mScatterStyle.isNone())
  19396. {
  19397. applyScattersAntialiasingHint(painter);
  19398. // scale scatter pixmap if it's too large to fit in legend icon rect:
  19399. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  19400. {
  19401. QCPScatterStyle scaledStyle(mScatterStyle);
  19402. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  19403. scaledStyle.applyTo(painter, mPen);
  19404. scaledStyle.drawShape(painter, QRectF(rect).center());
  19405. } else
  19406. {
  19407. mScatterStyle.applyTo(painter, mPen);
  19408. mScatterStyle.drawShape(painter, QRectF(rect).center());
  19409. }
  19410. }
  19411. }
  19412. /*! \internal
  19413. Draws lines between the points in \a lines, given in pixel coordinates.
  19414. \see drawScatterPlot, getCurveLines
  19415. */
  19416. void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector<QPointF> &lines) const
  19417. {
  19418. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  19419. {
  19420. applyDefaultAntialiasingHint(painter);
  19421. drawPolyline(painter, lines);
  19422. }
  19423. }
  19424. /*! \internal
  19425. Draws scatter symbols at every point passed in \a points, given in pixel coordinates. The
  19426. scatters will be drawn with \a painter and have the appearance as specified in \a style.
  19427. \see drawCurveLine, getCurveLines
  19428. */
  19429. void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &points, const QCPScatterStyle &style) const
  19430. {
  19431. // draw scatter point symbols:
  19432. applyScattersAntialiasingHint(painter);
  19433. style.applyTo(painter, mPen);
  19434. foreach (const QPointF &point, points)
  19435. if (!qIsNaN(point.x()) && !qIsNaN(point.y()))
  19436. style.drawShape(painter, point);
  19437. }
  19438. /*! \internal
  19439. Called by \ref draw to generate points in pixel coordinates which represent the line of the
  19440. curve.
  19441. Line segments that aren't visible in the current axis rect are handled in an optimized way. They
  19442. are projected onto a rectangle slightly larger than the visible axis rect and simplified
  19443. regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside
  19444. the visible axis rect by generating new temporary points on the outer rect if necessary.
  19445. \a lines will be filled with points in pixel coordinates, that can be drawn with \ref
  19446. drawCurveLine.
  19447. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  19448. conversion. In this function, the specified range may exceed the total data bounds without harm:
  19449. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  19450. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  19451. getDataSegments.
  19452. \a penWidth specifies the pen width that will be used to later draw the lines generated by this
  19453. function. This is needed here to calculate an accordingly wider margin around the axis rect when
  19454. performing the line optimization.
  19455. Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref
  19456. getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints.
  19457. \see drawCurveLine, drawScatterPlot
  19458. */
  19459. void QCPCurve::getCurveLines(QVector<QPointF> *lines, const QCPDataRange &dataRange, double penWidth) const
  19460. {
  19461. if (!lines) return;
  19462. lines->clear();
  19463. QCPAxis *keyAxis = mKeyAxis.data();
  19464. QCPAxis *valueAxis = mValueAxis.data();
  19465. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  19466. // add margins to rect to compensate for stroke width
  19467. const double strokeMargin = qMax(qreal(1.0), qreal(penWidth*0.75)); // stroke radius + 50% safety
  19468. const double keyMin = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*keyAxis->pixelOrientation());
  19469. const double keyMax = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*keyAxis->pixelOrientation());
  19470. const double valueMin = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)-strokeMargin*valueAxis->pixelOrientation());
  19471. const double valueMax = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)+strokeMargin*valueAxis->pixelOrientation());
  19472. QCPCurveDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  19473. QCPCurveDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  19474. mDataContainer->limitIteratorsToDataRange(itBegin, itEnd, dataRange);
  19475. if (itBegin == itEnd)
  19476. return;
  19477. QCPCurveDataContainer::const_iterator it = itBegin;
  19478. QCPCurveDataContainer::const_iterator prevIt = itEnd-1;
  19479. int prevRegion = getRegion(prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin);
  19480. QVector<QPointF> trailingPoints; // points that must be applied after all other points (are generated only when handling first point to get virtual segment between last and first point right)
  19481. while (it != itEnd)
  19482. {
  19483. const int currentRegion = getRegion(it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19484. if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R
  19485. {
  19486. if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal
  19487. {
  19488. QPointF crossA, crossB;
  19489. if (prevRegion == 5) // we're coming from R, so add this point optimized
  19490. {
  19491. lines->append(getOptimizedPoint(currentRegion, it->key, it->value, prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin));
  19492. // in the situations 5->1/7/9/3 the segment may leave R and directly cross through two outer regions. In these cases we need to add an additional corner point
  19493. *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19494. } else if (mayTraverse(prevRegion, currentRegion) &&
  19495. getTraverse(prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin, crossA, crossB))
  19496. {
  19497. // add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point:
  19498. QVector<QPointF> beforeTraverseCornerPoints, afterTraverseCornerPoints;
  19499. getTraverseCornerPoints(prevRegion, currentRegion, keyMin, valueMax, keyMax, valueMin, beforeTraverseCornerPoints, afterTraverseCornerPoints);
  19500. if (it != itBegin)
  19501. {
  19502. *lines << beforeTraverseCornerPoints;
  19503. lines->append(crossA);
  19504. lines->append(crossB);
  19505. *lines << afterTraverseCornerPoints;
  19506. } else
  19507. {
  19508. lines->append(crossB);
  19509. *lines << afterTraverseCornerPoints;
  19510. trailingPoints << beforeTraverseCornerPoints << crossA ;
  19511. }
  19512. } else // doesn't cross R, line is just moving around in outside regions, so only need to add optimized point(s) at the boundary corner(s)
  19513. {
  19514. *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19515. }
  19516. } else // segment does end in R, so we add previous point optimized and this point at original position
  19517. {
  19518. if (it == itBegin) // it is first point in curve and prevIt is last one. So save optimized point for adding it to the lineData in the end
  19519. trailingPoints << getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19520. else
  19521. lines->append(getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin));
  19522. lines->append(coordsToPixels(it->key, it->value));
  19523. }
  19524. } else // region didn't change
  19525. {
  19526. if (currentRegion == 5) // still in R, keep adding original points
  19527. {
  19528. lines->append(coordsToPixels(it->key, it->value));
  19529. } else // still outside R, no need to add anything
  19530. {
  19531. // see how this is not doing anything? That's the main optimization...
  19532. }
  19533. }
  19534. prevIt = it;
  19535. prevRegion = currentRegion;
  19536. ++it;
  19537. }
  19538. *lines << trailingPoints;
  19539. }
  19540. /*! \internal
  19541. Called by \ref draw to generate points in pixel coordinates which represent the scatters of the
  19542. curve. If a scatter skip is configured (\ref setScatterSkip), the returned points are accordingly
  19543. sparser.
  19544. Scatters that aren't visible in the current axis rect are optimized away.
  19545. \a scatters will be filled with points in pixel coordinates, that can be drawn with \ref
  19546. drawScatterPlot.
  19547. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  19548. conversion.
  19549. \a scatterWidth specifies the scatter width that will be used to later draw the scatters at pixel
  19550. coordinates generated by this function. This is needed here to calculate an accordingly wider
  19551. margin around the axis rect when performing the data point reduction.
  19552. \see draw, drawScatterPlot
  19553. */
  19554. void QCPCurve::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange, double scatterWidth) const
  19555. {
  19556. if (!scatters) return;
  19557. scatters->clear();
  19558. QCPAxis *keyAxis = mKeyAxis.data();
  19559. QCPAxis *valueAxis = mValueAxis.data();
  19560. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  19561. QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
  19562. QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
  19563. mDataContainer->limitIteratorsToDataRange(begin, end, dataRange);
  19564. if (begin == end)
  19565. return;
  19566. const int scatterModulo = mScatterSkip+1;
  19567. const bool doScatterSkip = mScatterSkip > 0;
  19568. int endIndex = int( end-mDataContainer->constBegin() );
  19569. QCPRange keyRange = keyAxis->range();
  19570. QCPRange valueRange = valueAxis->range();
  19571. // extend range to include width of scatter symbols:
  19572. keyRange.lower = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.lower)-scatterWidth*keyAxis->pixelOrientation());
  19573. keyRange.upper = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.upper)+scatterWidth*keyAxis->pixelOrientation());
  19574. valueRange.lower = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.lower)-scatterWidth*valueAxis->pixelOrientation());
  19575. valueRange.upper = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.upper)+scatterWidth*valueAxis->pixelOrientation());
  19576. QCPCurveDataContainer::const_iterator it = begin;
  19577. int itIndex = int( begin-mDataContainer->constBegin() );
  19578. while (doScatterSkip && it != end && itIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
  19579. {
  19580. ++itIndex;
  19581. ++it;
  19582. }
  19583. if (keyAxis->orientation() == Qt::Vertical)
  19584. {
  19585. while (it != end)
  19586. {
  19587. if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
  19588. scatters->append(QPointF(valueAxis->coordToPixel(it->value), keyAxis->coordToPixel(it->key)));
  19589. // advance iterator to next (non-skipped) data point:
  19590. if (!doScatterSkip)
  19591. ++it;
  19592. else
  19593. {
  19594. itIndex += scatterModulo;
  19595. if (itIndex < endIndex) // make sure we didn't jump over end
  19596. it += scatterModulo;
  19597. else
  19598. {
  19599. it = end;
  19600. itIndex = endIndex;
  19601. }
  19602. }
  19603. }
  19604. } else
  19605. {
  19606. while (it != end)
  19607. {
  19608. if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
  19609. scatters->append(QPointF(keyAxis->coordToPixel(it->key), valueAxis->coordToPixel(it->value)));
  19610. // advance iterator to next (non-skipped) data point:
  19611. if (!doScatterSkip)
  19612. ++it;
  19613. else
  19614. {
  19615. itIndex += scatterModulo;
  19616. if (itIndex < endIndex) // make sure we didn't jump over end
  19617. it += scatterModulo;
  19618. else
  19619. {
  19620. it = end;
  19621. itIndex = endIndex;
  19622. }
  19623. }
  19624. }
  19625. }
  19626. }
  19627. /*! \internal
  19628. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19629. It returns the region of the given point (\a key, \a value) with respect to a rectangle defined
  19630. by \a keyMin, \a keyMax, \a valueMin, and \a valueMax.
  19631. The regions are enumerated from top to bottom (\a valueMin to \a valueMax) and left to right (\a
  19632. keyMin to \a keyMax):
  19633. <table style="width:10em; text-align:center">
  19634. <tr><td>1</td><td>4</td><td>7</td></tr>
  19635. <tr><td>2</td><td style="border:1px solid black">5</td><td>8</td></tr>
  19636. <tr><td>3</td><td>6</td><td>9</td></tr>
  19637. </table>
  19638. With the rectangle being region 5, and the outer regions extending infinitely outwards. In the
  19639. curve optimization algorithm, region 5 is considered to be the visible portion of the plot.
  19640. */
  19641. int QCPCurve::getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
  19642. {
  19643. if (key < keyMin) // region 123
  19644. {
  19645. if (value > valueMax)
  19646. return 1;
  19647. else if (value < valueMin)
  19648. return 3;
  19649. else
  19650. return 2;
  19651. } else if (key > keyMax) // region 789
  19652. {
  19653. if (value > valueMax)
  19654. return 7;
  19655. else if (value < valueMin)
  19656. return 9;
  19657. else
  19658. return 8;
  19659. } else // region 456
  19660. {
  19661. if (value > valueMax)
  19662. return 4;
  19663. else if (value < valueMin)
  19664. return 6;
  19665. else
  19666. return 5;
  19667. }
  19668. }
  19669. /*! \internal
  19670. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19671. This method is used in case the current segment passes from inside the visible rect (region 5,
  19672. see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by
  19673. the line connecting (\a key, \a value) with (\a otherKey, \a otherValue).
  19674. It returns the intersection point of the segment with the border of region 5.
  19675. For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or
  19676. whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or
  19677. leaving it. It is important though that \a otherRegion correctly identifies the other region not
  19678. equal to 5.
  19679. */
  19680. QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
  19681. {
  19682. // The intersection point interpolation here is done in pixel coordinates, so we don't need to
  19683. // differentiate between different axis scale types. Note that the nomenclature
  19684. // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be
  19685. // different in pixel coordinates (horz/vert key axes, reversed ranges)
  19686. const double keyMinPx = mKeyAxis->coordToPixel(keyMin);
  19687. const double keyMaxPx = mKeyAxis->coordToPixel(keyMax);
  19688. const double valueMinPx = mValueAxis->coordToPixel(valueMin);
  19689. const double valueMaxPx = mValueAxis->coordToPixel(valueMax);
  19690. const double otherValuePx = mValueAxis->coordToPixel(otherValue);
  19691. const double valuePx = mValueAxis->coordToPixel(value);
  19692. const double otherKeyPx = mKeyAxis->coordToPixel(otherKey);
  19693. const double keyPx = mKeyAxis->coordToPixel(key);
  19694. double intersectKeyPx = keyMinPx; // initial key just a fail-safe
  19695. double intersectValuePx = valueMinPx; // initial value just a fail-safe
  19696. switch (otherRegion)
  19697. {
  19698. case 1: // top and left edge
  19699. {
  19700. intersectValuePx = valueMaxPx;
  19701. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19702. if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether top edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed)
  19703. {
  19704. intersectKeyPx = keyMinPx;
  19705. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19706. }
  19707. break;
  19708. }
  19709. case 2: // left edge
  19710. {
  19711. intersectKeyPx = keyMinPx;
  19712. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19713. break;
  19714. }
  19715. case 3: // bottom and left edge
  19716. {
  19717. intersectValuePx = valueMinPx;
  19718. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19719. if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether bottom edge is not intersected, then it must be left edge (qMin/qMax necessary since axes may be reversed)
  19720. {
  19721. intersectKeyPx = keyMinPx;
  19722. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19723. }
  19724. break;
  19725. }
  19726. case 4: // top edge
  19727. {
  19728. intersectValuePx = valueMaxPx;
  19729. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19730. break;
  19731. }
  19732. case 5:
  19733. {
  19734. break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table
  19735. }
  19736. case 6: // bottom edge
  19737. {
  19738. intersectValuePx = valueMinPx;
  19739. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19740. break;
  19741. }
  19742. case 7: // top and right edge
  19743. {
  19744. intersectValuePx = valueMaxPx;
  19745. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19746. if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether top edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed)
  19747. {
  19748. intersectKeyPx = keyMaxPx;
  19749. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19750. }
  19751. break;
  19752. }
  19753. case 8: // right edge
  19754. {
  19755. intersectKeyPx = keyMaxPx;
  19756. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19757. break;
  19758. }
  19759. case 9: // bottom and right edge
  19760. {
  19761. intersectValuePx = valueMinPx;
  19762. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19763. if (intersectKeyPx < qMin(keyMinPx, keyMaxPx) || intersectKeyPx > qMax(keyMinPx, keyMaxPx)) // check whether bottom edge is not intersected, then it must be right edge (qMin/qMax necessary since axes may be reversed)
  19764. {
  19765. intersectKeyPx = keyMaxPx;
  19766. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19767. }
  19768. break;
  19769. }
  19770. }
  19771. if (mKeyAxis->orientation() == Qt::Horizontal)
  19772. return {intersectKeyPx, intersectValuePx};
  19773. else
  19774. return {intersectValuePx, intersectKeyPx};
  19775. }
  19776. /*! \internal
  19777. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19778. In situations where a single segment skips over multiple regions it might become necessary to add
  19779. extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment
  19780. doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts.
  19781. This method provides these points that must be added, assuming the original segment doesn't
  19782. start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by
  19783. \ref getTraverseCornerPoints.)
  19784. For example, consider a segment which directly goes from region 4 to 2 but originally is far out
  19785. to the top left such that it doesn't cross region 5. Naively optimizing these points by
  19786. projecting them on the top and left borders of region 5 will create a segment that surely crosses
  19787. 5, creating a visual artifact in the plot. This method prevents this by providing extra points at
  19788. the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without
  19789. traversing 5.
  19790. */
  19791. QVector<QPointF> QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
  19792. {
  19793. QVector<QPointF> result;
  19794. switch (prevRegion)
  19795. {
  19796. case 1:
  19797. {
  19798. switch (currentRegion)
  19799. {
  19800. case 2: { result << coordsToPixels(keyMin, valueMax); break; }
  19801. case 4: { result << coordsToPixels(keyMin, valueMax); break; }
  19802. case 3: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); break; }
  19803. case 7: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); break; }
  19804. case 6: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19805. case 8: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19806. case 9: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
  19807. if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
  19808. { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
  19809. else
  19810. { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
  19811. break;
  19812. }
  19813. }
  19814. break;
  19815. }
  19816. case 2:
  19817. {
  19818. switch (currentRegion)
  19819. {
  19820. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19821. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19822. case 4: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19823. case 6: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19824. case 7: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
  19825. case 9: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
  19826. }
  19827. break;
  19828. }
  19829. case 3:
  19830. {
  19831. switch (currentRegion)
  19832. {
  19833. case 2: { result << coordsToPixels(keyMin, valueMin); break; }
  19834. case 6: { result << coordsToPixels(keyMin, valueMin); break; }
  19835. case 1: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); break; }
  19836. case 9: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); break; }
  19837. case 4: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19838. case 8: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19839. case 7: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
  19840. if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
  19841. { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
  19842. else
  19843. { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
  19844. break;
  19845. }
  19846. }
  19847. break;
  19848. }
  19849. case 4:
  19850. {
  19851. switch (currentRegion)
  19852. {
  19853. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19854. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19855. case 2: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19856. case 8: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19857. case 3: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
  19858. case 9: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
  19859. }
  19860. break;
  19861. }
  19862. case 5:
  19863. {
  19864. switch (currentRegion)
  19865. {
  19866. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19867. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19868. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19869. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19870. }
  19871. break;
  19872. }
  19873. case 6:
  19874. {
  19875. switch (currentRegion)
  19876. {
  19877. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19878. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19879. case 2: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19880. case 8: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19881. case 1: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
  19882. case 7: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
  19883. }
  19884. break;
  19885. }
  19886. case 7:
  19887. {
  19888. switch (currentRegion)
  19889. {
  19890. case 4: { result << coordsToPixels(keyMax, valueMax); break; }
  19891. case 8: { result << coordsToPixels(keyMax, valueMax); break; }
  19892. case 1: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); break; }
  19893. case 9: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); break; }
  19894. case 2: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19895. case 6: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19896. case 3: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
  19897. if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
  19898. { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
  19899. else
  19900. { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
  19901. break;
  19902. }
  19903. }
  19904. break;
  19905. }
  19906. case 8:
  19907. {
  19908. switch (currentRegion)
  19909. {
  19910. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19911. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19912. case 4: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19913. case 6: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19914. case 1: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
  19915. case 3: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
  19916. }
  19917. break;
  19918. }
  19919. case 9:
  19920. {
  19921. switch (currentRegion)
  19922. {
  19923. case 6: { result << coordsToPixels(keyMax, valueMin); break; }
  19924. case 8: { result << coordsToPixels(keyMax, valueMin); break; }
  19925. case 3: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); break; }
  19926. case 7: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); break; }
  19927. case 2: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19928. case 4: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19929. case 1: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points
  19930. if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
  19931. { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
  19932. else
  19933. { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
  19934. break;
  19935. }
  19936. }
  19937. break;
  19938. }
  19939. }
  19940. return result;
  19941. }
  19942. /*! \internal
  19943. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19944. This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref
  19945. getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion
  19946. nor \a currentRegion is 5 itself.
  19947. If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the
  19948. segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref
  19949. getTraverse).
  19950. */
  19951. bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const
  19952. {
  19953. switch (prevRegion)
  19954. {
  19955. case 1:
  19956. {
  19957. switch (currentRegion)
  19958. {
  19959. case 4:
  19960. case 7:
  19961. case 2:
  19962. case 3: return false;
  19963. default: return true;
  19964. }
  19965. }
  19966. case 2:
  19967. {
  19968. switch (currentRegion)
  19969. {
  19970. case 1:
  19971. case 3: return false;
  19972. default: return true;
  19973. }
  19974. }
  19975. case 3:
  19976. {
  19977. switch (currentRegion)
  19978. {
  19979. case 1:
  19980. case 2:
  19981. case 6:
  19982. case 9: return false;
  19983. default: return true;
  19984. }
  19985. }
  19986. case 4:
  19987. {
  19988. switch (currentRegion)
  19989. {
  19990. case 1:
  19991. case 7: return false;
  19992. default: return true;
  19993. }
  19994. }
  19995. case 5: return false; // should never occur
  19996. case 6:
  19997. {
  19998. switch (currentRegion)
  19999. {
  20000. case 3:
  20001. case 9: return false;
  20002. default: return true;
  20003. }
  20004. }
  20005. case 7:
  20006. {
  20007. switch (currentRegion)
  20008. {
  20009. case 1:
  20010. case 4:
  20011. case 8:
  20012. case 9: return false;
  20013. default: return true;
  20014. }
  20015. }
  20016. case 8:
  20017. {
  20018. switch (currentRegion)
  20019. {
  20020. case 7:
  20021. case 9: return false;
  20022. default: return true;
  20023. }
  20024. }
  20025. case 9:
  20026. {
  20027. switch (currentRegion)
  20028. {
  20029. case 3:
  20030. case 6:
  20031. case 8:
  20032. case 7: return false;
  20033. default: return true;
  20034. }
  20035. }
  20036. default: return true;
  20037. }
  20038. }
  20039. /*! \internal
  20040. This function is part of the curve optimization algorithm of \ref getCurveLines.
  20041. This method assumes that the \ref mayTraverse test has returned true, so there is a chance the
  20042. segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible
  20043. region 5.
  20044. The return value of this method indicates whether the segment actually traverses region 5 or not.
  20045. If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and
  20046. exit points of region 5. They will become the optimized points for that segment.
  20047. */
  20048. bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const
  20049. {
  20050. // The intersection point interpolation here is done in pixel coordinates, so we don't need to
  20051. // differentiate between different axis scale types. Note that the nomenclature
  20052. // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be
  20053. // different in pixel coordinates (horz/vert key axes, reversed ranges)
  20054. QList<QPointF> intersections;
  20055. const double valueMinPx = mValueAxis->coordToPixel(valueMin);
  20056. const double valueMaxPx = mValueAxis->coordToPixel(valueMax);
  20057. const double keyMinPx = mKeyAxis->coordToPixel(keyMin);
  20058. const double keyMaxPx = mKeyAxis->coordToPixel(keyMax);
  20059. const double keyPx = mKeyAxis->coordToPixel(key);
  20060. const double valuePx = mValueAxis->coordToPixel(value);
  20061. const double prevKeyPx = mKeyAxis->coordToPixel(prevKey);
  20062. const double prevValuePx = mValueAxis->coordToPixel(prevValue);
  20063. if (qFuzzyIsNull(keyPx-prevKeyPx)) // line is parallel to value axis
  20064. {
  20065. // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here
  20066. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMinPx) : QPointF(valueMinPx, keyPx)); // direction will be taken care of at end of method
  20067. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMaxPx) : QPointF(valueMaxPx, keyPx));
  20068. } else if (qFuzzyIsNull(valuePx-prevValuePx)) // line is parallel to key axis
  20069. {
  20070. // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here
  20071. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, valuePx) : QPointF(valuePx, keyMinPx)); // direction will be taken care of at end of method
  20072. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, valuePx) : QPointF(valuePx, keyMaxPx));
  20073. } else // line is skewed
  20074. {
  20075. double gamma;
  20076. double keyPerValuePx = (keyPx-prevKeyPx)/(valuePx-prevValuePx);
  20077. // check top of rect:
  20078. gamma = prevKeyPx + (valueMaxPx-prevValuePx)*keyPerValuePx;
  20079. if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed
  20080. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMaxPx) : QPointF(valueMaxPx, gamma));
  20081. // check bottom of rect:
  20082. gamma = prevKeyPx + (valueMinPx-prevValuePx)*keyPerValuePx;
  20083. if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed
  20084. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMinPx) : QPointF(valueMinPx, gamma));
  20085. const double valuePerKeyPx = 1.0/keyPerValuePx;
  20086. // check left of rect:
  20087. gamma = prevValuePx + (keyMinPx-prevKeyPx)*valuePerKeyPx;
  20088. if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed
  20089. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, gamma) : QPointF(gamma, keyMinPx));
  20090. // check right of rect:
  20091. gamma = prevValuePx + (keyMaxPx-prevKeyPx)*valuePerKeyPx;
  20092. if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed
  20093. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, gamma) : QPointF(gamma, keyMaxPx));
  20094. }
  20095. // handle cases where found points isn't exactly 2:
  20096. if (intersections.size() > 2)
  20097. {
  20098. // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between:
  20099. double distSqrMax = 0;
  20100. QPointF pv1, pv2;
  20101. for (int i=0; i<intersections.size()-1; ++i)
  20102. {
  20103. for (int k=i+1; k<intersections.size(); ++k)
  20104. {
  20105. QPointF distPoint = intersections.at(i)-intersections.at(k);
  20106. double distSqr = distPoint.x()*distPoint.x()+distPoint.y()+distPoint.y();
  20107. if (distSqr > distSqrMax)
  20108. {
  20109. pv1 = intersections.at(i);
  20110. pv2 = intersections.at(k);
  20111. distSqrMax = distSqr;
  20112. }
  20113. }
  20114. }
  20115. intersections = QList<QPointF>() << pv1 << pv2;
  20116. } else if (intersections.size() != 2)
  20117. {
  20118. // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment
  20119. return false;
  20120. }
  20121. // possibly re-sort points so optimized point segment has same direction as original segment:
  20122. double xDelta = keyPx-prevKeyPx;
  20123. double yDelta = valuePx-prevValuePx;
  20124. if (mKeyAxis->orientation() != Qt::Horizontal)
  20125. qSwap(xDelta, yDelta);
  20126. if (xDelta*(intersections.at(1).x()-intersections.at(0).x()) + yDelta*(intersections.at(1).y()-intersections.at(0).y()) < 0) // scalar product of both segments < 0 -> opposite direction
  20127. intersections.move(0, 1);
  20128. crossA = intersections.at(0);
  20129. crossB = intersections.at(1);
  20130. return true;
  20131. }
  20132. /*! \internal
  20133. This function is part of the curve optimization algorithm of \ref getCurveLines.
  20134. This method assumes that the \ref getTraverse test has returned true, so the segment definitely
  20135. traverses the visible region 5 when going from \a prevRegion to \a currentRegion.
  20136. In certain situations it is not sufficient to merely generate the entry and exit points of the
  20137. segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in
  20138. addition to traversing region 5, skips another region outside of region 5, which makes it
  20139. necessary to add an optimized corner point there (very similar to the job \ref
  20140. getOptimizedCornerPoints does for segments that are completely in outside regions and don't
  20141. traverse 5).
  20142. As an example, consider a segment going from region 1 to region 6, traversing the lower left
  20143. corner of region 5. In this configuration, the segment additionally crosses the border between
  20144. region 1 and 2 before entering region 5. This makes it necessary to add an additional point in
  20145. the top left corner, before adding the optimized traverse points. So in this case, the output
  20146. parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be
  20147. empty.
  20148. In some cases, such as when going from region 1 to 9, it may even be necessary to add additional
  20149. corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse
  20150. return the respective corner points.
  20151. */
  20152. void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double keyMin, double valueMax, double keyMax, double valueMin, QVector<QPointF> &beforeTraverse, QVector<QPointF> &afterTraverse) const
  20153. {
  20154. switch (prevRegion)
  20155. {
  20156. case 1:
  20157. {
  20158. switch (currentRegion)
  20159. {
  20160. case 6: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
  20161. case 9: { beforeTraverse << coordsToPixels(keyMin, valueMax); afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  20162. case 8: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
  20163. }
  20164. break;
  20165. }
  20166. case 2:
  20167. {
  20168. switch (currentRegion)
  20169. {
  20170. case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  20171. case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  20172. }
  20173. break;
  20174. }
  20175. case 3:
  20176. {
  20177. switch (currentRegion)
  20178. {
  20179. case 4: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
  20180. case 7: { beforeTraverse << coordsToPixels(keyMin, valueMin); afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  20181. case 8: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
  20182. }
  20183. break;
  20184. }
  20185. case 4:
  20186. {
  20187. switch (currentRegion)
  20188. {
  20189. case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  20190. case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  20191. }
  20192. break;
  20193. }
  20194. case 5: { break; } // shouldn't happen because this method only handles full traverses
  20195. case 6:
  20196. {
  20197. switch (currentRegion)
  20198. {
  20199. case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  20200. case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  20201. }
  20202. break;
  20203. }
  20204. case 7:
  20205. {
  20206. switch (currentRegion)
  20207. {
  20208. case 2: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
  20209. case 3: { beforeTraverse << coordsToPixels(keyMax, valueMax); afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  20210. case 6: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
  20211. }
  20212. break;
  20213. }
  20214. case 8:
  20215. {
  20216. switch (currentRegion)
  20217. {
  20218. case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  20219. case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  20220. }
  20221. break;
  20222. }
  20223. case 9:
  20224. {
  20225. switch (currentRegion)
  20226. {
  20227. case 2: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
  20228. case 1: { beforeTraverse << coordsToPixels(keyMax, valueMin); afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  20229. case 4: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
  20230. }
  20231. break;
  20232. }
  20233. }
  20234. }
  20235. /*! \internal
  20236. Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a
  20237. pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in
  20238. \ref selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that
  20239. if the curve has a line representation, the returned distance may be smaller than the distance to
  20240. the \a closestData point, since the distance to the curve line is also taken into account.
  20241. If either the curve has no data or if the line style is \ref lsNone and the scatter style's shape
  20242. is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the curve), returns
  20243. -1.0.
  20244. */
  20245. double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer::const_iterator &closestData) const
  20246. {
  20247. closestData = mDataContainer->constEnd();
  20248. if (mDataContainer->isEmpty())
  20249. return -1.0;
  20250. if (mLineStyle == lsNone && mScatterStyle.isNone())
  20251. return -1.0;
  20252. if (mDataContainer->size() == 1)
  20253. {
  20254. QPointF dataPoint = coordsToPixels(mDataContainer->constBegin()->key, mDataContainer->constBegin()->value);
  20255. closestData = mDataContainer->constBegin();
  20256. return QCPVector2D(dataPoint-pixelPoint).length();
  20257. }
  20258. // calculate minimum distances to curve data points and find closestData iterator:
  20259. double minDistSqr = (std::numeric_limits<double>::max)();
  20260. // iterate over found data points and then choose the one with the shortest distance to pos:
  20261. QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
  20262. QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
  20263. for (QCPCurveDataContainer::const_iterator it=begin; it!=end; ++it)
  20264. {
  20265. const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
  20266. if (currentDistSqr < minDistSqr)
  20267. {
  20268. minDistSqr = currentDistSqr;
  20269. closestData = it;
  20270. }
  20271. }
  20272. // calculate distance to line if there is one (if so, will probably be smaller than distance to closest data point):
  20273. if (mLineStyle != lsNone)
  20274. {
  20275. QVector<QPointF> lines;
  20276. getCurveLines(&lines, QCPDataRange(0, dataCount()), mParentPlot->selectionTolerance()*1.2); // optimized lines outside axis rect shouldn't respond to clicks at the edge, so use 1.2*tolerance as pen width
  20277. for (int i=0; i<lines.size()-1; ++i)
  20278. {
  20279. double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(lines.at(i), lines.at(i+1));
  20280. if (currentDistSqr < minDistSqr)
  20281. minDistSqr = currentDistSqr;
  20282. }
  20283. }
  20284. return qSqrt(minDistSqr);
  20285. }
  20286. /* end of 'src/plottables/plottable-curve.cpp' */
  20287. /* including file 'src/plottables/plottable-bars.cpp' */
  20288. /* modified 2021-03-29T02:30:44, size 43907 */
  20289. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20290. //////////////////// QCPBarsGroup
  20291. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20292. /*! \class QCPBarsGroup
  20293. \brief Groups multiple QCPBars together so they appear side by side
  20294. \image html QCPBarsGroup.png
  20295. When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable
  20296. to have them appearing next to each other at each key. This is what adding the respective QCPBars
  20297. plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each
  20298. other, see \ref QCPBars::moveAbove.)
  20299. \section qcpbarsgroup-usage Usage
  20300. To add a QCPBars plottable to the group, create a new group and then add the respective bars
  20301. intances:
  20302. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation
  20303. Alternatively to appending to the group like shown above, you can also set the group on the
  20304. QCPBars plottable via \ref QCPBars::setBarsGroup.
  20305. The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The
  20306. bars in this group appear in the plot in the order they were appended. To insert a bars plottable
  20307. at a certain index position, or to reposition a bars plottable which is already in the group, use
  20308. \ref insert.
  20309. To remove specific bars from the group, use either \ref remove or call \ref
  20310. QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable.
  20311. To clear the entire group, call \ref clear, or simply delete the group.
  20312. \section qcpbarsgroup-example Example
  20313. The image above is generated with the following code:
  20314. \snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example
  20315. */
  20316. /* start of documentation of inline functions */
  20317. /*! \fn QList<QCPBars*> QCPBarsGroup::bars() const
  20318. Returns all bars currently in this group.
  20319. \see bars(int index)
  20320. */
  20321. /*! \fn int QCPBarsGroup::size() const
  20322. Returns the number of QCPBars plottables that are part of this group.
  20323. */
  20324. /*! \fn bool QCPBarsGroup::isEmpty() const
  20325. Returns whether this bars group is empty.
  20326. \see size
  20327. */
  20328. /*! \fn bool QCPBarsGroup::contains(QCPBars *bars)
  20329. Returns whether the specified \a bars plottable is part of this group.
  20330. */
  20331. /* end of documentation of inline functions */
  20332. /*!
  20333. Constructs a new bars group for the specified QCustomPlot instance.
  20334. */
  20335. QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) :
  20336. QObject(parentPlot),
  20337. mParentPlot(parentPlot),
  20338. mSpacingType(stAbsolute),
  20339. mSpacing(4)
  20340. {
  20341. }
  20342. QCPBarsGroup::~QCPBarsGroup()
  20343. {
  20344. clear();
  20345. }
  20346. /*!
  20347. Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType.
  20348. The actual spacing can then be specified with \ref setSpacing.
  20349. \see setSpacing
  20350. */
  20351. void QCPBarsGroup::setSpacingType(SpacingType spacingType)
  20352. {
  20353. mSpacingType = spacingType;
  20354. }
  20355. /*!
  20356. Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is
  20357. defined by the current \ref SpacingType, which can be set with \ref setSpacingType.
  20358. \see setSpacingType
  20359. */
  20360. void QCPBarsGroup::setSpacing(double spacing)
  20361. {
  20362. mSpacing = spacing;
  20363. }
  20364. /*!
  20365. Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars
  20366. exists, returns \c nullptr.
  20367. \see bars(), size
  20368. */
  20369. QCPBars *QCPBarsGroup::bars(int index) const
  20370. {
  20371. if (index >= 0 && index < mBars.size())
  20372. {
  20373. return mBars.at(index);
  20374. } else
  20375. {
  20376. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  20377. return nullptr;
  20378. }
  20379. }
  20380. /*!
  20381. Removes all QCPBars plottables from this group.
  20382. \see isEmpty
  20383. */
  20384. void QCPBarsGroup::clear()
  20385. {
  20386. const QList<QCPBars*> oldBars = mBars;
  20387. foreach (QCPBars *bars, oldBars)
  20388. bars->setBarsGroup(nullptr); // removes itself from mBars via removeBars
  20389. }
  20390. /*!
  20391. Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref
  20392. QCPBars::setBarsGroup on the \a bars instance.
  20393. \see insert, remove
  20394. */
  20395. void QCPBarsGroup::append(QCPBars *bars)
  20396. {
  20397. if (!bars)
  20398. {
  20399. qDebug() << Q_FUNC_INFO << "bars is 0";
  20400. return;
  20401. }
  20402. if (!mBars.contains(bars))
  20403. bars->setBarsGroup(this);
  20404. else
  20405. qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast<quintptr>(bars);
  20406. }
  20407. /*!
  20408. Inserts the specified \a bars plottable into this group at the specified index position \a i.
  20409. This gives you full control over the ordering of the bars.
  20410. \a bars may already be part of this group. In that case, \a bars is just moved to the new index
  20411. position.
  20412. \see append, remove
  20413. */
  20414. void QCPBarsGroup::insert(int i, QCPBars *bars)
  20415. {
  20416. if (!bars)
  20417. {
  20418. qDebug() << Q_FUNC_INFO << "bars is 0";
  20419. return;
  20420. }
  20421. // first append to bars list normally:
  20422. if (!mBars.contains(bars))
  20423. bars->setBarsGroup(this);
  20424. // then move to according position:
  20425. mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1));
  20426. }
  20427. /*!
  20428. Removes the specified \a bars plottable from this group.
  20429. \see contains, clear
  20430. */
  20431. void QCPBarsGroup::remove(QCPBars *bars)
  20432. {
  20433. if (!bars)
  20434. {
  20435. qDebug() << Q_FUNC_INFO << "bars is 0";
  20436. return;
  20437. }
  20438. if (mBars.contains(bars))
  20439. bars->setBarsGroup(nullptr);
  20440. else
  20441. qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast<quintptr>(bars);
  20442. }
  20443. /*! \internal
  20444. Adds the specified \a bars to the internal mBars list of bars. This method does not change the
  20445. barsGroup property on \a bars.
  20446. \see unregisterBars
  20447. */
  20448. void QCPBarsGroup::registerBars(QCPBars *bars)
  20449. {
  20450. if (!mBars.contains(bars))
  20451. mBars.append(bars);
  20452. }
  20453. /*! \internal
  20454. Removes the specified \a bars from the internal mBars list of bars. This method does not change
  20455. the barsGroup property on \a bars.
  20456. \see registerBars
  20457. */
  20458. void QCPBarsGroup::unregisterBars(QCPBars *bars)
  20459. {
  20460. mBars.removeOne(bars);
  20461. }
  20462. /*! \internal
  20463. Returns the pixel offset in the key dimension the specified \a bars plottable should have at the
  20464. given key coordinate \a keyCoord. The offset is relative to the pixel position of the key
  20465. coordinate \a keyCoord.
  20466. */
  20467. double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord)
  20468. {
  20469. // find list of all base bars in case some mBars are stacked:
  20470. QList<const QCPBars*> baseBars;
  20471. foreach (const QCPBars *b, mBars)
  20472. {
  20473. while (b->barBelow())
  20474. b = b->barBelow();
  20475. if (!baseBars.contains(b))
  20476. baseBars.append(b);
  20477. }
  20478. // find base bar this "bars" is stacked on:
  20479. const QCPBars *thisBase = bars;
  20480. while (thisBase->barBelow())
  20481. thisBase = thisBase->barBelow();
  20482. // determine key pixel offset of this base bars considering all other base bars in this barsgroup:
  20483. double result = 0;
  20484. int index = baseBars.indexOf(thisBase);
  20485. if (index >= 0)
  20486. {
  20487. if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose)
  20488. {
  20489. return result;
  20490. } else
  20491. {
  20492. double lowerPixelWidth, upperPixelWidth;
  20493. int startIndex;
  20494. int dir = (index <= (baseBars.size()-1)/2) ? -1 : 1; // if bar is to lower keys of center, dir is negative
  20495. if (baseBars.size() % 2 == 0) // even number of bars
  20496. {
  20497. startIndex = baseBars.size()/2 + (dir < 0 ? -1 : 0);
  20498. result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing
  20499. } else // uneven number of bars
  20500. {
  20501. startIndex = (baseBars.size()-1)/2+dir;
  20502. baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  20503. result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar
  20504. result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing
  20505. }
  20506. for (int i = startIndex; i != index; i += dir) // add widths and spacings of bars in between center and our bars
  20507. {
  20508. baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  20509. result += qAbs(upperPixelWidth-lowerPixelWidth);
  20510. result += getPixelSpacing(baseBars.at(i), keyCoord);
  20511. }
  20512. // finally half of our bars width:
  20513. baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  20514. result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5;
  20515. // correct sign of result depending on orientation and direction of key axis:
  20516. result *= dir*thisBase->keyAxis()->pixelOrientation();
  20517. }
  20518. }
  20519. return result;
  20520. }
  20521. /*! \internal
  20522. Returns the spacing in pixels which is between this \a bars and the following one, both at the
  20523. key coordinate \a keyCoord.
  20524. \note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only
  20525. needed to get access to the key axis transformation and axis rect for the modes \ref
  20526. stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in
  20527. \ref stPlotCoords on a logarithmic axis.
  20528. */
  20529. double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord)
  20530. {
  20531. switch (mSpacingType)
  20532. {
  20533. case stAbsolute:
  20534. {
  20535. return mSpacing;
  20536. }
  20537. case stAxisRectRatio:
  20538. {
  20539. if (bars->keyAxis()->orientation() == Qt::Horizontal)
  20540. return bars->keyAxis()->axisRect()->width()*mSpacing;
  20541. else
  20542. return bars->keyAxis()->axisRect()->height()*mSpacing;
  20543. }
  20544. case stPlotCoords:
  20545. {
  20546. double keyPixel = bars->keyAxis()->coordToPixel(keyCoord);
  20547. return qAbs(bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel);
  20548. }
  20549. }
  20550. return 0;
  20551. }
  20552. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20553. //////////////////// QCPBarsData
  20554. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20555. /*! \class QCPBarsData
  20556. \brief Holds the data of one single data point (one bar) for QCPBars.
  20557. The stored data is:
  20558. \li \a key: coordinate on the key axis of this bar (this is the \a mainKey and the \a sortKey)
  20559. \li \a value: height coordinate on the value axis of this bar (this is the \a mainValue)
  20560. The container for storing multiple data points is \ref QCPBarsDataContainer. It is a typedef for
  20561. \ref QCPDataContainer with \ref QCPBarsData as the DataType template parameter. See the
  20562. documentation there for an explanation regarding the data type's generic methods.
  20563. \see QCPBarsDataContainer
  20564. */
  20565. /* start documentation of inline functions */
  20566. /*! \fn double QCPBarsData::sortKey() const
  20567. Returns the \a key member of this data point.
  20568. For a general explanation of what this method is good for in the context of the data container,
  20569. see the documentation of \ref QCPDataContainer.
  20570. */
  20571. /*! \fn static QCPBarsData QCPBarsData::fromSortKey(double sortKey)
  20572. Returns a data point with the specified \a sortKey. All other members are set to zero.
  20573. For a general explanation of what this method is good for in the context of the data container,
  20574. see the documentation of \ref QCPDataContainer.
  20575. */
  20576. /*! \fn static static bool QCPBarsData::sortKeyIsMainKey()
  20577. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  20578. this method returns true.
  20579. For a general explanation of what this method is good for in the context of the data container,
  20580. see the documentation of \ref QCPDataContainer.
  20581. */
  20582. /*! \fn double QCPBarsData::mainKey() const
  20583. Returns the \a key member of this data point.
  20584. For a general explanation of what this method is good for in the context of the data container,
  20585. see the documentation of \ref QCPDataContainer.
  20586. */
  20587. /*! \fn double QCPBarsData::mainValue() const
  20588. Returns the \a value member of this data point.
  20589. For a general explanation of what this method is good for in the context of the data container,
  20590. see the documentation of \ref QCPDataContainer.
  20591. */
  20592. /*! \fn QCPRange QCPBarsData::valueRange() const
  20593. Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
  20594. For a general explanation of what this method is good for in the context of the data container,
  20595. see the documentation of \ref QCPDataContainer.
  20596. */
  20597. /* end documentation of inline functions */
  20598. /*!
  20599. Constructs a bar data point with key and value set to zero.
  20600. */
  20601. QCPBarsData::QCPBarsData() :
  20602. key(0),
  20603. value(0)
  20604. {
  20605. }
  20606. /*!
  20607. Constructs a bar data point with the specified \a key and \a value.
  20608. */
  20609. QCPBarsData::QCPBarsData(double key, double value) :
  20610. key(key),
  20611. value(value)
  20612. {
  20613. }
  20614. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20615. //////////////////// QCPBars
  20616. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20617. /*! \class QCPBars
  20618. \brief A plottable representing a bar chart in a plot.
  20619. \image html QCPBars.png
  20620. To plot data, assign it with the \ref setData or \ref addData functions.
  20621. \section qcpbars-appearance Changing the appearance
  20622. The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush).
  20623. The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth.
  20624. Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other
  20625. (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear
  20626. stacked.
  20627. If you would like to group multiple QCPBars plottables together so they appear side by side as
  20628. shown below, use QCPBarsGroup.
  20629. \image html QCPBarsGroup.png
  20630. \section qcpbars-usage Usage
  20631. Like all data representing objects in QCustomPlot, the QCPBars is a plottable
  20632. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  20633. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  20634. Usually, you first create an instance:
  20635. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1
  20636. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  20637. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  20638. The newly created plottable can be modified, e.g.:
  20639. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-2
  20640. */
  20641. /* start of documentation of inline functions */
  20642. /*! \fn QSharedPointer<QCPBarsDataContainer> QCPBars::data() const
  20643. Returns a shared pointer to the internal data storage of type \ref QCPBarsDataContainer. You may
  20644. use it to directly manipulate the data, which may be more convenient and faster than using the
  20645. regular \ref setData or \ref addData methods.
  20646. */
  20647. /*! \fn QCPBars *QCPBars::barBelow() const
  20648. Returns the bars plottable that is directly below this bars plottable.
  20649. If there is no such plottable, returns \c nullptr.
  20650. \see barAbove, moveBelow, moveAbove
  20651. */
  20652. /*! \fn QCPBars *QCPBars::barAbove() const
  20653. Returns the bars plottable that is directly above this bars plottable.
  20654. If there is no such plottable, returns \c nullptr.
  20655. \see barBelow, moveBelow, moveAbove
  20656. */
  20657. /* end of documentation of inline functions */
  20658. /*!
  20659. Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  20660. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  20661. the same orientation. If either of these restrictions is violated, a corresponding message is
  20662. printed to the debug output (qDebug), the construction is not aborted, though.
  20663. The created QCPBars is automatically registered with the QCustomPlot instance inferred from \a
  20664. keyAxis. This QCustomPlot instance takes ownership of the QCPBars, so do not delete it manually
  20665. but use QCustomPlot::removePlottable() instead.
  20666. */
  20667. QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  20668. QCPAbstractPlottable1D<QCPBarsData>(keyAxis, valueAxis),
  20669. mWidth(0.75),
  20670. mWidthType(wtPlotCoords),
  20671. mBarsGroup(nullptr),
  20672. mBaseValue(0),
  20673. mStackingGap(1)
  20674. {
  20675. // modify inherited properties from abstract plottable:
  20676. mPen.setColor(Qt::blue);
  20677. mPen.setStyle(Qt::SolidLine);
  20678. mBrush.setColor(QColor(40, 50, 255, 30));
  20679. mBrush.setStyle(Qt::SolidPattern);
  20680. mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
  20681. }
  20682. QCPBars::~QCPBars()
  20683. {
  20684. setBarsGroup(nullptr);
  20685. if (mBarBelow || mBarAbove)
  20686. connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking
  20687. }
  20688. /*! \overload
  20689. Replaces the current data container with the provided \a data container.
  20690. Since a QSharedPointer is used, multiple QCPBars may share the same data container safely.
  20691. Modifying the data in the container will then affect all bars that share the container. Sharing
  20692. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  20693. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-1
  20694. If you do not wish to share containers, but create a copy from an existing container, rather use
  20695. the \ref QCPDataContainer<DataType>::set method on the bar's data container directly:
  20696. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-2
  20697. \see addData
  20698. */
  20699. void QCPBars::setData(QSharedPointer<QCPBarsDataContainer> data)
  20700. {
  20701. mDataContainer = data;
  20702. }
  20703. /*! \overload
  20704. Replaces the current data with the provided points in \a keys and \a values. The provided
  20705. vectors should have equal length. Else, the number of added points will be the size of the
  20706. smallest vector.
  20707. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  20708. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  20709. \see addData
  20710. */
  20711. void QCPBars::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  20712. {
  20713. mDataContainer->clear();
  20714. addData(keys, values, alreadySorted);
  20715. }
  20716. /*!
  20717. Sets the width of the bars.
  20718. How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...),
  20719. depends on the currently set width type, see \ref setWidthType and \ref WidthType.
  20720. */
  20721. void QCPBars::setWidth(double width)
  20722. {
  20723. mWidth = width;
  20724. }
  20725. /*!
  20726. Sets how the width of the bars is defined. See the documentation of \ref WidthType for an
  20727. explanation of the possible values for \a widthType.
  20728. The default value is \ref wtPlotCoords.
  20729. \see setWidth
  20730. */
  20731. void QCPBars::setWidthType(QCPBars::WidthType widthType)
  20732. {
  20733. mWidthType = widthType;
  20734. }
  20735. /*!
  20736. Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref
  20737. QCPBarsGroup::append.
  20738. To remove this QCPBars from any group, set \a barsGroup to \c nullptr.
  20739. */
  20740. void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup)
  20741. {
  20742. // deregister at old group:
  20743. if (mBarsGroup)
  20744. mBarsGroup->unregisterBars(this);
  20745. mBarsGroup = barsGroup;
  20746. // register at new group:
  20747. if (mBarsGroup)
  20748. mBarsGroup->registerBars(this);
  20749. }
  20750. /*!
  20751. Sets the base value of this bars plottable.
  20752. The base value defines where on the value coordinate the bars start. How far the bars extend from
  20753. the base value is given by their individual value data. For example, if the base value is set to
  20754. 1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at
  20755. 3.
  20756. For stacked bars, only the base value of the bottom-most QCPBars has meaning.
  20757. The default base value is 0.
  20758. */
  20759. void QCPBars::setBaseValue(double baseValue)
  20760. {
  20761. mBaseValue = baseValue;
  20762. }
  20763. /*!
  20764. If this bars plottable is stacked on top of another bars plottable (\ref moveAbove), this method
  20765. allows specifying a distance in \a pixels, by which the drawn bar rectangles will be separated by
  20766. the bars below it.
  20767. */
  20768. void QCPBars::setStackingGap(double pixels)
  20769. {
  20770. mStackingGap = pixels;
  20771. }
  20772. /*! \overload
  20773. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  20774. should have equal length. Else, the number of added points will be the size of the smallest
  20775. vector.
  20776. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  20777. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  20778. Alternatively, you can also access and modify the data directly via the \ref data method, which
  20779. returns a pointer to the internal data container.
  20780. */
  20781. void QCPBars::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  20782. {
  20783. if (keys.size() != values.size())
  20784. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  20785. const int n = qMin(keys.size(), values.size());
  20786. QVector<QCPBarsData> tempData(n);
  20787. QVector<QCPBarsData>::iterator it = tempData.begin();
  20788. const QVector<QCPBarsData>::iterator itEnd = tempData.end();
  20789. int i = 0;
  20790. while (it != itEnd)
  20791. {
  20792. it->key = keys[i];
  20793. it->value = values[i];
  20794. ++it;
  20795. ++i;
  20796. }
  20797. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  20798. }
  20799. /*! \overload
  20800. Adds the provided data point as \a key and \a value to the current data.
  20801. Alternatively, you can also access and modify the data directly via the \ref data method, which
  20802. returns a pointer to the internal data container.
  20803. */
  20804. void QCPBars::addData(double key, double value)
  20805. {
  20806. mDataContainer->add(QCPBarsData(key, value));
  20807. }
  20808. /*!
  20809. Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear
  20810. below the bars of \a bars. The move target \a bars must use the same key and value axis as this
  20811. plottable.
  20812. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  20813. has a bars object below itself, this bars object is inserted between the two. If this bars object
  20814. is already between two other bars, the two other bars will be stacked on top of each other after
  20815. the operation.
  20816. To remove this bars plottable from any stacking, set \a bars to \c nullptr.
  20817. \see moveBelow, barAbove, barBelow
  20818. */
  20819. void QCPBars::moveBelow(QCPBars *bars)
  20820. {
  20821. if (bars == this) return;
  20822. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
  20823. {
  20824. qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  20825. return;
  20826. }
  20827. // remove from stacking:
  20828. connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
  20829. // if new bar given, insert this bar below it:
  20830. if (bars)
  20831. {
  20832. if (bars->mBarBelow)
  20833. connectBars(bars->mBarBelow.data(), this);
  20834. connectBars(this, bars);
  20835. }
  20836. }
  20837. /*!
  20838. Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear
  20839. above the bars of \a bars. The move target \a bars must use the same key and value axis as this
  20840. plottable.
  20841. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  20842. has a bars object above itself, this bars object is inserted between the two. If this bars object
  20843. is already between two other bars, the two other bars will be stacked on top of each other after
  20844. the operation.
  20845. To remove this bars plottable from any stacking, set \a bars to \c nullptr.
  20846. \see moveBelow, barBelow, barAbove
  20847. */
  20848. void QCPBars::moveAbove(QCPBars *bars)
  20849. {
  20850. if (bars == this) return;
  20851. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
  20852. {
  20853. qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  20854. return;
  20855. }
  20856. // remove from stacking:
  20857. connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
  20858. // if new bar given, insert this bar above it:
  20859. if (bars)
  20860. {
  20861. if (bars->mBarAbove)
  20862. connectBars(this, bars->mBarAbove.data());
  20863. connectBars(bars, this);
  20864. }
  20865. }
  20866. /*!
  20867. \copydoc QCPPlottableInterface1D::selectTestRect
  20868. */
  20869. QCPDataSelection QCPBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
  20870. {
  20871. QCPDataSelection result;
  20872. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  20873. return result;
  20874. if (!mKeyAxis || !mValueAxis)
  20875. return result;
  20876. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  20877. getVisibleDataBounds(visibleBegin, visibleEnd);
  20878. for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  20879. {
  20880. if (rect.intersects(getBarRect(it->key, it->value)))
  20881. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  20882. }
  20883. result.simplify();
  20884. return result;
  20885. }
  20886. /*!
  20887. Implements a selectTest specific to this plottable's point geometry.
  20888. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  20889. point to \a pos.
  20890. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  20891. */
  20892. double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  20893. {
  20894. Q_UNUSED(details)
  20895. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  20896. return -1;
  20897. if (!mKeyAxis || !mValueAxis)
  20898. return -1;
  20899. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  20900. {
  20901. // get visible data range:
  20902. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  20903. getVisibleDataBounds(visibleBegin, visibleEnd);
  20904. for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  20905. {
  20906. if (getBarRect(it->key, it->value).contains(pos))
  20907. {
  20908. if (details)
  20909. {
  20910. int pointIndex = int(it-mDataContainer->constBegin());
  20911. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  20912. }
  20913. return mParentPlot->selectionTolerance()*0.99;
  20914. }
  20915. }
  20916. }
  20917. return -1;
  20918. }
  20919. /* inherits documentation from base class */
  20920. QCPRange QCPBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  20921. {
  20922. /* Note: If this QCPBars uses absolute pixels as width (or is in a QCPBarsGroup with spacing in
  20923. absolute pixels), using this method to adapt the key axis range to fit the bars into the
  20924. currently visible axis range will not work perfectly. Because in the moment the axis range is
  20925. changed to the new range, the fixed pixel widths/spacings will represent different coordinate
  20926. spans than before, which in turn would require a different key range to perfectly fit, and so on.
  20927. The only solution would be to iteratively approach the perfect fitting axis range, but the
  20928. mismatch isn't large enough in most applications, to warrant this here. If a user does need a
  20929. better fit, he should call the corresponding axis rescale multiple times in a row.
  20930. */
  20931. QCPRange range;
  20932. range = mDataContainer->keyRange(foundRange, inSignDomain);
  20933. // determine exact range of bars by including bar width and barsgroup offset:
  20934. if (foundRange && mKeyAxis)
  20935. {
  20936. double lowerPixelWidth, upperPixelWidth, keyPixel;
  20937. // lower range bound:
  20938. getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth);
  20939. keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth;
  20940. if (mBarsGroup)
  20941. keyPixel += mBarsGroup->keyPixelOffset(this, range.lower);
  20942. const double lowerCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
  20943. if (!qIsNaN(lowerCorrected) && qIsFinite(lowerCorrected) && range.lower > lowerCorrected)
  20944. range.lower = lowerCorrected;
  20945. // upper range bound:
  20946. getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth);
  20947. keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth;
  20948. if (mBarsGroup)
  20949. keyPixel += mBarsGroup->keyPixelOffset(this, range.upper);
  20950. const double upperCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
  20951. if (!qIsNaN(upperCorrected) && qIsFinite(upperCorrected) && range.upper < upperCorrected)
  20952. range.upper = upperCorrected;
  20953. }
  20954. return range;
  20955. }
  20956. /* inherits documentation from base class */
  20957. QCPRange QCPBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  20958. {
  20959. // Note: can't simply use mDataContainer->valueRange here because we need to
  20960. // take into account bar base value and possible stacking of multiple bars
  20961. QCPRange range;
  20962. range.lower = mBaseValue;
  20963. range.upper = mBaseValue;
  20964. bool haveLower = true; // set to true, because baseValue should always be visible in bar charts
  20965. bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts
  20966. QCPBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  20967. QCPBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  20968. if (inKeyRange != QCPRange())
  20969. {
  20970. itBegin = mDataContainer->findBegin(inKeyRange.lower, false);
  20971. itEnd = mDataContainer->findEnd(inKeyRange.upper, false);
  20972. }
  20973. for (QCPBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
  20974. {
  20975. const double current = it->value + getStackedBaseValue(it->key, it->value >= 0);
  20976. if (qIsNaN(current)) continue;
  20977. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  20978. {
  20979. if (current < range.lower || !haveLower)
  20980. {
  20981. range.lower = current;
  20982. haveLower = true;
  20983. }
  20984. if (current > range.upper || !haveUpper)
  20985. {
  20986. range.upper = current;
  20987. haveUpper = true;
  20988. }
  20989. }
  20990. }
  20991. foundRange = true; // return true because bar charts always have the 0-line visible
  20992. return range;
  20993. }
  20994. /* inherits documentation from base class */
  20995. QPointF QCPBars::dataPixelPosition(int index) const
  20996. {
  20997. if (index >= 0 && index < mDataContainer->size())
  20998. {
  20999. QCPAxis *keyAxis = mKeyAxis.data();
  21000. QCPAxis *valueAxis = mValueAxis.data();
  21001. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  21002. const QCPDataContainer<QCPBarsData>::const_iterator it = mDataContainer->constBegin()+index;
  21003. const double valuePixel = valueAxis->coordToPixel(getStackedBaseValue(it->key, it->value >= 0) + it->value);
  21004. const double keyPixel = keyAxis->coordToPixel(it->key) + (mBarsGroup ? mBarsGroup->keyPixelOffset(this, it->key) : 0);
  21005. if (keyAxis->orientation() == Qt::Horizontal)
  21006. return {keyPixel, valuePixel};
  21007. else
  21008. return {valuePixel, keyPixel};
  21009. } else
  21010. {
  21011. qDebug() << Q_FUNC_INFO << "Index out of bounds" << index;
  21012. return {};
  21013. }
  21014. }
  21015. /* inherits documentation from base class */
  21016. void QCPBars::draw(QCPPainter *painter)
  21017. {
  21018. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  21019. if (mDataContainer->isEmpty()) return;
  21020. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  21021. getVisibleDataBounds(visibleBegin, visibleEnd);
  21022. // loop over and draw segments of unselected/selected data:
  21023. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  21024. getDataSegments(selectedSegments, unselectedSegments);
  21025. allSegments << unselectedSegments << selectedSegments;
  21026. for (int i=0; i<allSegments.size(); ++i)
  21027. {
  21028. bool isSelectedSegment = i >= unselectedSegments.size();
  21029. QCPBarsDataContainer::const_iterator begin = visibleBegin;
  21030. QCPBarsDataContainer::const_iterator end = visibleEnd;
  21031. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  21032. if (begin == end)
  21033. continue;
  21034. for (QCPBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  21035. {
  21036. // check data validity if flag set:
  21037. #ifdef QCUSTOMPLOT_CHECK_DATA
  21038. if (QCP::isInvalidData(it->key, it->value))
  21039. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
  21040. #endif
  21041. // draw bar:
  21042. if (isSelectedSegment && mSelectionDecorator)
  21043. {
  21044. mSelectionDecorator->applyBrush(painter);
  21045. mSelectionDecorator->applyPen(painter);
  21046. } else
  21047. {
  21048. painter->setBrush(mBrush);
  21049. painter->setPen(mPen);
  21050. }
  21051. applyDefaultAntialiasingHint(painter);
  21052. painter->drawPolygon(getBarRect(it->key, it->value));
  21053. }
  21054. }
  21055. // draw other selection decoration that isn't just line/scatter pens and brushes:
  21056. if (mSelectionDecorator)
  21057. mSelectionDecorator->drawDecoration(painter, selection());
  21058. }
  21059. /* inherits documentation from base class */
  21060. void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  21061. {
  21062. // draw filled rect:
  21063. applyDefaultAntialiasingHint(painter);
  21064. painter->setBrush(mBrush);
  21065. painter->setPen(mPen);
  21066. QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
  21067. r.moveCenter(rect.center());
  21068. painter->drawRect(r);
  21069. }
  21070. /*! \internal
  21071. called by \ref draw to determine which data (key) range is visible at the current key axis range
  21072. setting, so only that needs to be processed. It also takes into account the bar width.
  21073. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  21074. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  21075. lower may still be just outside the visible range.
  21076. \a end returns an iterator one higher than the highest visible data point. Same as before, \a end
  21077. may also lie just outside of the visible range.
  21078. if the plottable contains no data, both \a begin and \a end point to constEnd.
  21079. */
  21080. void QCPBars::getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const
  21081. {
  21082. if (!mKeyAxis)
  21083. {
  21084. qDebug() << Q_FUNC_INFO << "invalid key axis";
  21085. begin = mDataContainer->constEnd();
  21086. end = mDataContainer->constEnd();
  21087. return;
  21088. }
  21089. if (mDataContainer->isEmpty())
  21090. {
  21091. begin = mDataContainer->constEnd();
  21092. end = mDataContainer->constEnd();
  21093. return;
  21094. }
  21095. // get visible data range as QMap iterators
  21096. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower);
  21097. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper);
  21098. double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower);
  21099. double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper);
  21100. bool isVisible = false;
  21101. // walk left from begin to find lower bar that actually is completely outside visible pixel range:
  21102. QCPBarsDataContainer::const_iterator it = begin;
  21103. while (it != mDataContainer->constBegin())
  21104. {
  21105. --it;
  21106. const QRectF barRect = getBarRect(it->key, it->value);
  21107. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  21108. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.left() <= lowerPixelBound));
  21109. else // keyaxis is vertical
  21110. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.bottom() >= lowerPixelBound));
  21111. if (isVisible)
  21112. begin = it;
  21113. else
  21114. break;
  21115. }
  21116. // walk right from ubound to find upper bar that actually is completely outside visible pixel range:
  21117. it = end;
  21118. while (it != mDataContainer->constEnd())
  21119. {
  21120. const QRectF barRect = getBarRect(it->key, it->value);
  21121. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  21122. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.right() >= upperPixelBound));
  21123. else // keyaxis is vertical
  21124. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.top() <= upperPixelBound));
  21125. if (isVisible)
  21126. end = it+1;
  21127. else
  21128. break;
  21129. ++it;
  21130. }
  21131. }
  21132. /*! \internal
  21133. Returns the rect in pixel coordinates of a single bar with the specified \a key and \a value. The
  21134. rect is shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref
  21135. setBaseValue), and to have non-overlapping border lines with the bars stacked below.
  21136. */
  21137. QRectF QCPBars::getBarRect(double key, double value) const
  21138. {
  21139. QCPAxis *keyAxis = mKeyAxis.data();
  21140. QCPAxis *valueAxis = mValueAxis.data();
  21141. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  21142. double lowerPixelWidth, upperPixelWidth;
  21143. getPixelWidth(key, lowerPixelWidth, upperPixelWidth);
  21144. double base = getStackedBaseValue(key, value >= 0);
  21145. double basePixel = valueAxis->coordToPixel(base);
  21146. double valuePixel = valueAxis->coordToPixel(base+value);
  21147. double keyPixel = keyAxis->coordToPixel(key);
  21148. if (mBarsGroup)
  21149. keyPixel += mBarsGroup->keyPixelOffset(this, key);
  21150. double bottomOffset = (mBarBelow && mPen != Qt::NoPen ? 1 : 0)*(mPen.isCosmetic() ? 1 : mPen.widthF());
  21151. bottomOffset += mBarBelow ? mStackingGap : 0;
  21152. bottomOffset *= (value<0 ? -1 : 1)*valueAxis->pixelOrientation();
  21153. if (qAbs(valuePixel-basePixel) <= qAbs(bottomOffset))
  21154. bottomOffset = valuePixel-basePixel;
  21155. if (keyAxis->orientation() == Qt::Horizontal)
  21156. {
  21157. return QRectF(QPointF(keyPixel+lowerPixelWidth, valuePixel), QPointF(keyPixel+upperPixelWidth, basePixel+bottomOffset)).normalized();
  21158. } else
  21159. {
  21160. return QRectF(QPointF(basePixel+bottomOffset, keyPixel+lowerPixelWidth), QPointF(valuePixel, keyPixel+upperPixelWidth)).normalized();
  21161. }
  21162. }
  21163. /*! \internal
  21164. This function is used to determine the width of the bar at coordinate \a key, according to the
  21165. specified width (\ref setWidth) and width type (\ref setWidthType).
  21166. The output parameters \a lower and \a upper return the number of pixels the bar extends to lower
  21167. and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a
  21168. lower is negative and \a upper positive).
  21169. */
  21170. void QCPBars::getPixelWidth(double key, double &lower, double &upper) const
  21171. {
  21172. lower = 0;
  21173. upper = 0;
  21174. switch (mWidthType)
  21175. {
  21176. case wtAbsolute:
  21177. {
  21178. upper = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  21179. lower = -upper;
  21180. break;
  21181. }
  21182. case wtAxisRectRatio:
  21183. {
  21184. if (mKeyAxis && mKeyAxis.data()->axisRect())
  21185. {
  21186. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  21187. upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  21188. else
  21189. upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  21190. lower = -upper;
  21191. } else
  21192. qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
  21193. break;
  21194. }
  21195. case wtPlotCoords:
  21196. {
  21197. if (mKeyAxis)
  21198. {
  21199. double keyPixel = mKeyAxis.data()->coordToPixel(key);
  21200. upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
  21201. lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel;
  21202. // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by
  21203. // coordinate transform which includes range direction
  21204. } else
  21205. qDebug() << Q_FUNC_INFO << "No key axis defined";
  21206. break;
  21207. }
  21208. }
  21209. }
  21210. /*! \internal
  21211. This function is called to find at which value to start drawing the base of a bar at \a key, when
  21212. it is stacked on top of another QCPBars (e.g. with \ref moveAbove).
  21213. positive and negative bars are separated per stack (positive are stacked above baseValue upwards,
  21214. negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the
  21215. bar for which we need the base value is negative, set \a positive to false.
  21216. */
  21217. double QCPBars::getStackedBaseValue(double key, bool positive) const
  21218. {
  21219. if (mBarBelow)
  21220. {
  21221. double max = 0; // don't initialize with mBaseValue here because only base value of bottom-most bar has meaning in a bar stack
  21222. // find bars of mBarBelow that are approximately at key and find largest one:
  21223. double epsilon = qAbs(key)*(sizeof(key)==4 ? 1e-6 : 1e-14); // should be safe even when changed to use float at some point
  21224. if (key == 0)
  21225. epsilon = (sizeof(key)==4 ? 1e-6 : 1e-14);
  21226. QCPBarsDataContainer::const_iterator it = mBarBelow.data()->mDataContainer->findBegin(key-epsilon);
  21227. QCPBarsDataContainer::const_iterator itEnd = mBarBelow.data()->mDataContainer->findEnd(key+epsilon);
  21228. while (it != itEnd)
  21229. {
  21230. if (it->key > key-epsilon && it->key < key+epsilon)
  21231. {
  21232. if ((positive && it->value > max) ||
  21233. (!positive && it->value < max))
  21234. max = it->value;
  21235. }
  21236. ++it;
  21237. }
  21238. // recurse down the bar-stack to find the total height:
  21239. return max + mBarBelow.data()->getStackedBaseValue(key, positive);
  21240. } else
  21241. return mBaseValue;
  21242. }
  21243. /*! \internal
  21244. Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s)
  21245. currently above lower and below upper will become disconnected to lower/upper.
  21246. If lower is zero, upper will be disconnected at the bottom.
  21247. If upper is zero, lower will be disconnected at the top.
  21248. */
  21249. void QCPBars::connectBars(QCPBars *lower, QCPBars *upper)
  21250. {
  21251. if (!lower && !upper) return;
  21252. if (!lower) // disconnect upper at bottom
  21253. {
  21254. // disconnect old bar below upper:
  21255. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  21256. upper->mBarBelow.data()->mBarAbove = nullptr;
  21257. upper->mBarBelow = nullptr;
  21258. } else if (!upper) // disconnect lower at top
  21259. {
  21260. // disconnect old bar above lower:
  21261. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  21262. lower->mBarAbove.data()->mBarBelow = nullptr;
  21263. lower->mBarAbove = nullptr;
  21264. } else // connect lower and upper
  21265. {
  21266. // disconnect old bar above lower:
  21267. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  21268. lower->mBarAbove.data()->mBarBelow = nullptr;
  21269. // disconnect old bar below upper:
  21270. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  21271. upper->mBarBelow.data()->mBarAbove = nullptr;
  21272. lower->mBarAbove = upper;
  21273. upper->mBarBelow = lower;
  21274. }
  21275. }
  21276. /* end of 'src/plottables/plottable-bars.cpp' */
  21277. /* including file 'src/plottables/plottable-statisticalbox.cpp' */
  21278. /* modified 2021-03-29T02:30:44, size 28951 */
  21279. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21280. //////////////////// QCPStatisticalBoxData
  21281. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21282. /*! \class QCPStatisticalBoxData
  21283. \brief Holds the data of one single data point for QCPStatisticalBox.
  21284. The stored data is:
  21285. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  21286. \li \a minimum: the position of the lower whisker, typically the minimum measurement of the
  21287. sample that's not considered an outlier.
  21288. \li \a lowerQuartile: the lower end of the box. The lower and the upper quartiles are the two
  21289. statistical quartiles around the median of the sample, they should contain 50% of the sample
  21290. data.
  21291. \li \a median: the value of the median mark inside the quartile box. The median separates the
  21292. sample data in half (50% of the sample data is below/above the median). (This is the \a mainValue)
  21293. \li \a upperQuartile: the upper end of the box. The lower and the upper quartiles are the two
  21294. statistical quartiles around the median of the sample, they should contain 50% of the sample
  21295. data.
  21296. \li \a maximum: the position of the upper whisker, typically the maximum measurement of the
  21297. sample that's not considered an outlier.
  21298. \li \a outliers: a QVector of outlier values that will be drawn as scatter points at the \a key
  21299. coordinate of this data point (see \ref QCPStatisticalBox::setOutlierStyle)
  21300. The container for storing multiple data points is \ref QCPStatisticalBoxDataContainer. It is a
  21301. typedef for \ref QCPDataContainer with \ref QCPStatisticalBoxData as the DataType template
  21302. parameter. See the documentation there for an explanation regarding the data type's generic
  21303. methods.
  21304. \see QCPStatisticalBoxDataContainer
  21305. */
  21306. /* start documentation of inline functions */
  21307. /*! \fn double QCPStatisticalBoxData::sortKey() const
  21308. Returns the \a key member of this data point.
  21309. For a general explanation of what this method is good for in the context of the data container,
  21310. see the documentation of \ref QCPDataContainer.
  21311. */
  21312. /*! \fn static QCPStatisticalBoxData QCPStatisticalBoxData::fromSortKey(double sortKey)
  21313. Returns a data point with the specified \a sortKey. All other members are set to zero.
  21314. For a general explanation of what this method is good for in the context of the data container,
  21315. see the documentation of \ref QCPDataContainer.
  21316. */
  21317. /*! \fn static static bool QCPStatisticalBoxData::sortKeyIsMainKey()
  21318. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  21319. this method returns true.
  21320. For a general explanation of what this method is good for in the context of the data container,
  21321. see the documentation of \ref QCPDataContainer.
  21322. */
  21323. /*! \fn double QCPStatisticalBoxData::mainKey() const
  21324. Returns the \a key member of this data point.
  21325. For a general explanation of what this method is good for in the context of the data container,
  21326. see the documentation of \ref QCPDataContainer.
  21327. */
  21328. /*! \fn double QCPStatisticalBoxData::mainValue() const
  21329. Returns the \a median member of this data point.
  21330. For a general explanation of what this method is good for in the context of the data container,
  21331. see the documentation of \ref QCPDataContainer.
  21332. */
  21333. /*! \fn QCPRange QCPStatisticalBoxData::valueRange() const
  21334. Returns a QCPRange spanning from the \a minimum to the \a maximum member of this statistical box
  21335. data point, possibly further expanded by outliers.
  21336. For a general explanation of what this method is good for in the context of the data container,
  21337. see the documentation of \ref QCPDataContainer.
  21338. */
  21339. /* end documentation of inline functions */
  21340. /*!
  21341. Constructs a data point with key and all values set to zero.
  21342. */
  21343. QCPStatisticalBoxData::QCPStatisticalBoxData() :
  21344. key(0),
  21345. minimum(0),
  21346. lowerQuartile(0),
  21347. median(0),
  21348. upperQuartile(0),
  21349. maximum(0)
  21350. {
  21351. }
  21352. /*!
  21353. Constructs a data point with the specified \a key, \a minimum, \a lowerQuartile, \a median, \a
  21354. upperQuartile, \a maximum and optionally a number of \a outliers.
  21355. */
  21356. QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers) :
  21357. key(key),
  21358. minimum(minimum),
  21359. lowerQuartile(lowerQuartile),
  21360. median(median),
  21361. upperQuartile(upperQuartile),
  21362. maximum(maximum),
  21363. outliers(outliers)
  21364. {
  21365. }
  21366. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21367. //////////////////// QCPStatisticalBox
  21368. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21369. /*! \class QCPStatisticalBox
  21370. \brief A plottable representing a single statistical box in a plot.
  21371. \image html QCPStatisticalBox.png
  21372. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  21373. also access and modify the data via the \ref data method, which returns a pointer to the internal
  21374. \ref QCPStatisticalBoxDataContainer.
  21375. Additionally each data point can itself have a list of outliers, drawn as scatter points at the
  21376. key coordinate of the respective statistical box data point. They can either be set by using the
  21377. respective \ref addData(double,double,double,double,double,double,const QVector<double>&)
  21378. "addData" method or accessing the individual data points through \ref data, and setting the
  21379. <tt>QVector<double> outliers</tt> of the data points directly.
  21380. \section qcpstatisticalbox-appearance Changing the appearance
  21381. The appearance of each data point box, ranging from the lower to the upper quartile, is
  21382. controlled via \ref setPen and \ref setBrush. You may change the width of the boxes with \ref
  21383. setWidth in plot coordinates.
  21384. Each data point's visual representation also consists of two whiskers. Whiskers are the lines
  21385. which reach from the upper quartile to the maximum, and from the lower quartile to the minimum.
  21386. The appearance of the whiskers can be modified with: \ref setWhiskerPen, \ref setWhiskerBarPen,
  21387. \ref setWhiskerWidth. The whisker width is the width of the bar perpendicular to the whisker at
  21388. the top (for maximum) and bottom (for minimum). If the whisker pen is changed, make sure to set
  21389. the \c capStyle to \c Qt::FlatCap. Otherwise the backbone line might exceed the whisker bars by a
  21390. few pixels due to the pen cap being not perfectly flat.
  21391. The median indicator line inside the box has its own pen, \ref setMedianPen.
  21392. The outlier data points are drawn as normal scatter points. Their look can be controlled with
  21393. \ref setOutlierStyle
  21394. \section qcpstatisticalbox-usage Usage
  21395. Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable
  21396. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  21397. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  21398. Usually, you first create an instance:
  21399. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1
  21400. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  21401. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  21402. The newly created plottable can be modified, e.g.:
  21403. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-2
  21404. */
  21405. /* start documentation of inline functions */
  21406. /*! \fn QSharedPointer<QCPStatisticalBoxDataContainer> QCPStatisticalBox::data() const
  21407. Returns a shared pointer to the internal data storage of type \ref
  21408. QCPStatisticalBoxDataContainer. You may use it to directly manipulate the data, which may be more
  21409. convenient and faster than using the regular \ref setData or \ref addData methods.
  21410. */
  21411. /* end documentation of inline functions */
  21412. /*!
  21413. Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its
  21414. value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and
  21415. not have the same orientation. If either of these restrictions is violated, a corresponding
  21416. message is printed to the debug output (qDebug), the construction is not aborted, though.
  21417. The created QCPStatisticalBox is automatically registered with the QCustomPlot instance inferred
  21418. from \a keyAxis. This QCustomPlot instance takes ownership of the QCPStatisticalBox, so do not
  21419. delete it manually but use QCustomPlot::removePlottable() instead.
  21420. */
  21421. QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  21422. QCPAbstractPlottable1D<QCPStatisticalBoxData>(keyAxis, valueAxis),
  21423. mWidth(0.5),
  21424. mWhiskerWidth(0.2),
  21425. mWhiskerPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap),
  21426. mWhiskerBarPen(Qt::black),
  21427. mWhiskerAntialiased(false),
  21428. mMedianPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap),
  21429. mOutlierStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)
  21430. {
  21431. setPen(QPen(Qt::black));
  21432. setBrush(Qt::NoBrush);
  21433. }
  21434. /*! \overload
  21435. Replaces the current data container with the provided \a data container.
  21436. Since a QSharedPointer is used, multiple QCPStatisticalBoxes may share the same data container
  21437. safely. Modifying the data in the container will then affect all statistical boxes that share the
  21438. container. Sharing can be achieved by simply exchanging the data containers wrapped in shared
  21439. pointers:
  21440. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-1
  21441. If you do not wish to share containers, but create a copy from an existing container, rather use
  21442. the \ref QCPDataContainer<DataType>::set method on the statistical box data container directly:
  21443. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-2
  21444. \see addData
  21445. */
  21446. void QCPStatisticalBox::setData(QSharedPointer<QCPStatisticalBoxDataContainer> data)
  21447. {
  21448. mDataContainer = data;
  21449. }
  21450. /*! \overload
  21451. Replaces the current data with the provided points in \a keys, \a minimum, \a lowerQuartile, \a
  21452. median, \a upperQuartile and \a maximum. The provided vectors should have equal length. Else, the
  21453. number of added points will be the size of the smallest vector.
  21454. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  21455. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  21456. \see addData
  21457. */
  21458. void QCPStatisticalBox::setData(const QVector<double> &keys, const QVector<double> &minimum, const QVector<double> &lowerQuartile, const QVector<double> &median, const QVector<double> &upperQuartile, const QVector<double> &maximum, bool alreadySorted)
  21459. {
  21460. mDataContainer->clear();
  21461. addData(keys, minimum, lowerQuartile, median, upperQuartile, maximum, alreadySorted);
  21462. }
  21463. /*!
  21464. Sets the width of the boxes in key coordinates.
  21465. \see setWhiskerWidth
  21466. */
  21467. void QCPStatisticalBox::setWidth(double width)
  21468. {
  21469. mWidth = width;
  21470. }
  21471. /*!
  21472. Sets the width of the whiskers in key coordinates.
  21473. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  21474. quartile to the minimum.
  21475. \see setWidth
  21476. */
  21477. void QCPStatisticalBox::setWhiskerWidth(double width)
  21478. {
  21479. mWhiskerWidth = width;
  21480. }
  21481. /*!
  21482. Sets the pen used for drawing the whisker backbone.
  21483. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  21484. quartile to the minimum.
  21485. Make sure to set the \c capStyle of the passed \a pen to \c Qt::FlatCap. Otherwise the backbone
  21486. line might exceed the whisker bars by a few pixels due to the pen cap being not perfectly flat.
  21487. \see setWhiskerBarPen
  21488. */
  21489. void QCPStatisticalBox::setWhiskerPen(const QPen &pen)
  21490. {
  21491. mWhiskerPen = pen;
  21492. }
  21493. /*!
  21494. Sets the pen used for drawing the whisker bars. Those are the lines parallel to the key axis at
  21495. each end of the whisker backbone.
  21496. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  21497. quartile to the minimum.
  21498. \see setWhiskerPen
  21499. */
  21500. void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen)
  21501. {
  21502. mWhiskerBarPen = pen;
  21503. }
  21504. /*!
  21505. Sets whether the statistical boxes whiskers are drawn with antialiasing or not.
  21506. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
  21507. QCustomPlot::setNotAntialiasedElements.
  21508. */
  21509. void QCPStatisticalBox::setWhiskerAntialiased(bool enabled)
  21510. {
  21511. mWhiskerAntialiased = enabled;
  21512. }
  21513. /*!
  21514. Sets the pen used for drawing the median indicator line inside the statistical boxes.
  21515. */
  21516. void QCPStatisticalBox::setMedianPen(const QPen &pen)
  21517. {
  21518. mMedianPen = pen;
  21519. }
  21520. /*!
  21521. Sets the appearance of the outlier data points.
  21522. Outliers can be specified with the method
  21523. \ref addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
  21524. */
  21525. void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style)
  21526. {
  21527. mOutlierStyle = style;
  21528. }
  21529. /*! \overload
  21530. Adds the provided points in \a keys, \a minimum, \a lowerQuartile, \a median, \a upperQuartile and
  21531. \a maximum to the current data. The provided vectors should have equal length. Else, the number
  21532. of added points will be the size of the smallest vector.
  21533. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  21534. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  21535. Alternatively, you can also access and modify the data directly via the \ref data method, which
  21536. returns a pointer to the internal data container.
  21537. */
  21538. void QCPStatisticalBox::addData(const QVector<double> &keys, const QVector<double> &minimum, const QVector<double> &lowerQuartile, const QVector<double> &median, const QVector<double> &upperQuartile, const QVector<double> &maximum, bool alreadySorted)
  21539. {
  21540. if (keys.size() != minimum.size() || minimum.size() != lowerQuartile.size() || lowerQuartile.size() != median.size() ||
  21541. median.size() != upperQuartile.size() || upperQuartile.size() != maximum.size() || maximum.size() != keys.size())
  21542. qDebug() << Q_FUNC_INFO << "keys, minimum, lowerQuartile, median, upperQuartile, maximum have different sizes:"
  21543. << keys.size() << minimum.size() << lowerQuartile.size() << median.size() << upperQuartile.size() << maximum.size();
  21544. const int n = qMin(keys.size(), qMin(minimum.size(), qMin(lowerQuartile.size(), qMin(median.size(), qMin(upperQuartile.size(), maximum.size())))));
  21545. QVector<QCPStatisticalBoxData> tempData(n);
  21546. QVector<QCPStatisticalBoxData>::iterator it = tempData.begin();
  21547. const QVector<QCPStatisticalBoxData>::iterator itEnd = tempData.end();
  21548. int i = 0;
  21549. while (it != itEnd)
  21550. {
  21551. it->key = keys[i];
  21552. it->minimum = minimum[i];
  21553. it->lowerQuartile = lowerQuartile[i];
  21554. it->median = median[i];
  21555. it->upperQuartile = upperQuartile[i];
  21556. it->maximum = maximum[i];
  21557. ++it;
  21558. ++i;
  21559. }
  21560. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  21561. }
  21562. /*! \overload
  21563. Adds the provided data point as \a key, \a minimum, \a lowerQuartile, \a median, \a upperQuartile
  21564. and \a maximum to the current data.
  21565. Alternatively, you can also access and modify the data directly via the \ref data method, which
  21566. returns a pointer to the internal data container.
  21567. */
  21568. void QCPStatisticalBox::addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
  21569. {
  21570. mDataContainer->add(QCPStatisticalBoxData(key, minimum, lowerQuartile, median, upperQuartile, maximum, outliers));
  21571. }
  21572. /*!
  21573. \copydoc QCPPlottableInterface1D::selectTestRect
  21574. */
  21575. QCPDataSelection QCPStatisticalBox::selectTestRect(const QRectF &rect, bool onlySelectable) const
  21576. {
  21577. QCPDataSelection result;
  21578. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  21579. return result;
  21580. if (!mKeyAxis || !mValueAxis)
  21581. return result;
  21582. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  21583. getVisibleDataBounds(visibleBegin, visibleEnd);
  21584. for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  21585. {
  21586. if (rect.intersects(getQuartileBox(it)))
  21587. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  21588. }
  21589. result.simplify();
  21590. return result;
  21591. }
  21592. /*!
  21593. Implements a selectTest specific to this plottable's point geometry.
  21594. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  21595. point to \a pos.
  21596. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  21597. */
  21598. double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  21599. {
  21600. Q_UNUSED(details)
  21601. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  21602. return -1;
  21603. if (!mKeyAxis || !mValueAxis)
  21604. return -1;
  21605. if (mKeyAxis->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  21606. {
  21607. // get visible data range:
  21608. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  21609. QCPStatisticalBoxDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  21610. getVisibleDataBounds(visibleBegin, visibleEnd);
  21611. double minDistSqr = (std::numeric_limits<double>::max)();
  21612. for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  21613. {
  21614. if (getQuartileBox(it).contains(pos)) // quartile box
  21615. {
  21616. double currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  21617. if (currentDistSqr < minDistSqr)
  21618. {
  21619. minDistSqr = currentDistSqr;
  21620. closestDataPoint = it;
  21621. }
  21622. } else // whiskers
  21623. {
  21624. const QVector<QLineF> whiskerBackbones = getWhiskerBackboneLines(it);
  21625. const QCPVector2D posVec(pos);
  21626. foreach (const QLineF &backbone, whiskerBackbones)
  21627. {
  21628. double currentDistSqr = posVec.distanceSquaredToLine(backbone);
  21629. if (currentDistSqr < minDistSqr)
  21630. {
  21631. minDistSqr = currentDistSqr;
  21632. closestDataPoint = it;
  21633. }
  21634. }
  21635. }
  21636. }
  21637. if (details)
  21638. {
  21639. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  21640. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  21641. }
  21642. return qSqrt(minDistSqr);
  21643. }
  21644. return -1;
  21645. }
  21646. /* inherits documentation from base class */
  21647. QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  21648. {
  21649. QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
  21650. // determine exact range by including width of bars/flags:
  21651. if (foundRange)
  21652. {
  21653. if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0)
  21654. range.lower -= mWidth*0.5;
  21655. if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0)
  21656. range.upper += mWidth*0.5;
  21657. }
  21658. return range;
  21659. }
  21660. /* inherits documentation from base class */
  21661. QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  21662. {
  21663. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  21664. }
  21665. /* inherits documentation from base class */
  21666. void QCPStatisticalBox::draw(QCPPainter *painter)
  21667. {
  21668. if (mDataContainer->isEmpty()) return;
  21669. QCPAxis *keyAxis = mKeyAxis.data();
  21670. QCPAxis *valueAxis = mValueAxis.data();
  21671. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  21672. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  21673. getVisibleDataBounds(visibleBegin, visibleEnd);
  21674. // loop over and draw segments of unselected/selected data:
  21675. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  21676. getDataSegments(selectedSegments, unselectedSegments);
  21677. allSegments << unselectedSegments << selectedSegments;
  21678. for (int i=0; i<allSegments.size(); ++i)
  21679. {
  21680. bool isSelectedSegment = i >= unselectedSegments.size();
  21681. QCPStatisticalBoxDataContainer::const_iterator begin = visibleBegin;
  21682. QCPStatisticalBoxDataContainer::const_iterator end = visibleEnd;
  21683. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  21684. if (begin == end)
  21685. continue;
  21686. for (QCPStatisticalBoxDataContainer::const_iterator it=begin; it!=end; ++it)
  21687. {
  21688. // check data validity if flag set:
  21689. # ifdef QCUSTOMPLOT_CHECK_DATA
  21690. if (QCP::isInvalidData(it->key, it->minimum) ||
  21691. QCP::isInvalidData(it->lowerQuartile, it->median) ||
  21692. QCP::isInvalidData(it->upperQuartile, it->maximum))
  21693. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range has invalid data." << "Plottable name:" << name();
  21694. for (int i=0; i<it->outliers.size(); ++i)
  21695. if (QCP::isInvalidData(it->outliers.at(i)))
  21696. qDebug() << Q_FUNC_INFO << "Data point outlier at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
  21697. # endif
  21698. if (isSelectedSegment && mSelectionDecorator)
  21699. {
  21700. mSelectionDecorator->applyPen(painter);
  21701. mSelectionDecorator->applyBrush(painter);
  21702. } else
  21703. {
  21704. painter->setPen(mPen);
  21705. painter->setBrush(mBrush);
  21706. }
  21707. QCPScatterStyle finalOutlierStyle = mOutlierStyle;
  21708. if (isSelectedSegment && mSelectionDecorator)
  21709. finalOutlierStyle = mSelectionDecorator->getFinalScatterStyle(mOutlierStyle);
  21710. drawStatisticalBox(painter, it, finalOutlierStyle);
  21711. }
  21712. }
  21713. // draw other selection decoration that isn't just line/scatter pens and brushes:
  21714. if (mSelectionDecorator)
  21715. mSelectionDecorator->drawDecoration(painter, selection());
  21716. }
  21717. /* inherits documentation from base class */
  21718. void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  21719. {
  21720. // draw filled rect:
  21721. applyDefaultAntialiasingHint(painter);
  21722. painter->setPen(mPen);
  21723. painter->setBrush(mBrush);
  21724. QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
  21725. r.moveCenter(rect.center());
  21726. painter->drawRect(r);
  21727. }
  21728. /*!
  21729. Draws the graphical representation of a single statistical box with the data given by the
  21730. iterator \a it with the provided \a painter.
  21731. If the statistical box has a set of outlier data points, they are drawn with \a outlierStyle.
  21732. \see getQuartileBox, getWhiskerBackboneLines, getWhiskerBarLines
  21733. */
  21734. void QCPStatisticalBox::drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const
  21735. {
  21736. // draw quartile box:
  21737. applyDefaultAntialiasingHint(painter);
  21738. const QRectF quartileBox = getQuartileBox(it);
  21739. painter->drawRect(quartileBox);
  21740. // draw median line with cliprect set to quartile box:
  21741. painter->save();
  21742. painter->setClipRect(quartileBox, Qt::IntersectClip);
  21743. painter->setPen(mMedianPen);
  21744. painter->drawLine(QLineF(coordsToPixels(it->key-mWidth*0.5, it->median), coordsToPixels(it->key+mWidth*0.5, it->median)));
  21745. painter->restore();
  21746. // draw whisker lines:
  21747. applyAntialiasingHint(painter, mWhiskerAntialiased, QCP::aePlottables);
  21748. painter->setPen(mWhiskerPen);
  21749. painter->drawLines(getWhiskerBackboneLines(it));
  21750. painter->setPen(mWhiskerBarPen);
  21751. painter->drawLines(getWhiskerBarLines(it));
  21752. // draw outliers:
  21753. applyScattersAntialiasingHint(painter);
  21754. outlierStyle.applyTo(painter, mPen);
  21755. for (int i=0; i<it->outliers.size(); ++i)
  21756. outlierStyle.drawShape(painter, coordsToPixels(it->key, it->outliers.at(i)));
  21757. }
  21758. /*! \internal
  21759. called by \ref draw to determine which data (key) range is visible at the current key axis range
  21760. setting, so only that needs to be processed. It also takes into account the bar width.
  21761. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  21762. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  21763. lower may still be just outside the visible range.
  21764. \a end returns an iterator one higher than the highest visible data point. Same as before, \a end
  21765. may also lie just outside of the visible range.
  21766. if the plottable contains no data, both \a begin and \a end point to constEnd.
  21767. */
  21768. void QCPStatisticalBox::getVisibleDataBounds(QCPStatisticalBoxDataContainer::const_iterator &begin, QCPStatisticalBoxDataContainer::const_iterator &end) const
  21769. {
  21770. if (!mKeyAxis)
  21771. {
  21772. qDebug() << Q_FUNC_INFO << "invalid key axis";
  21773. begin = mDataContainer->constEnd();
  21774. end = mDataContainer->constEnd();
  21775. return;
  21776. }
  21777. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of box to include partially visible data points
  21778. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of box to include partially visible data points
  21779. }
  21780. /*! \internal
  21781. Returns the box in plot coordinates (keys in x, values in y of the returned rect) that covers the
  21782. value range from the lower to the upper quartile, of the data given by \a it.
  21783. \see drawStatisticalBox, getWhiskerBackboneLines, getWhiskerBarLines
  21784. */
  21785. QRectF QCPStatisticalBox::getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const
  21786. {
  21787. QRectF result;
  21788. result.setTopLeft(coordsToPixels(it->key-mWidth*0.5, it->upperQuartile));
  21789. result.setBottomRight(coordsToPixels(it->key+mWidth*0.5, it->lowerQuartile));
  21790. return result;
  21791. }
  21792. /*! \internal
  21793. Returns the whisker backbones (keys in x, values in y of the returned lines) that cover the value
  21794. range from the minimum to the lower quartile, and from the upper quartile to the maximum of the
  21795. data given by \a it.
  21796. \see drawStatisticalBox, getQuartileBox, getWhiskerBarLines
  21797. */
  21798. QVector<QLineF> QCPStatisticalBox::getWhiskerBackboneLines(QCPStatisticalBoxDataContainer::const_iterator it) const
  21799. {
  21800. QVector<QLineF> result(2);
  21801. result[0].setPoints(coordsToPixels(it->key, it->lowerQuartile), coordsToPixels(it->key, it->minimum)); // min backbone
  21802. result[1].setPoints(coordsToPixels(it->key, it->upperQuartile), coordsToPixels(it->key, it->maximum)); // max backbone
  21803. return result;
  21804. }
  21805. /*! \internal
  21806. Returns the whisker bars (keys in x, values in y of the returned lines) that are placed at the
  21807. end of the whisker backbones, at the minimum and maximum of the data given by \a it.
  21808. \see drawStatisticalBox, getQuartileBox, getWhiskerBackboneLines
  21809. */
  21810. QVector<QLineF> QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataContainer::const_iterator it) const
  21811. {
  21812. QVector<QLineF> result(2);
  21813. result[0].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->minimum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->minimum)); // min bar
  21814. result[1].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->maximum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->maximum)); // max bar
  21815. return result;
  21816. }
  21817. /* end of 'src/plottables/plottable-statisticalbox.cpp' */
  21818. /* including file 'src/plottables/plottable-colormap.cpp' */
  21819. /* modified 2021-03-29T02:30:44, size 48149 */
  21820. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21821. //////////////////// QCPColorMapData
  21822. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21823. /*! \class QCPColorMapData
  21824. \brief Holds the two-dimensional data of a QCPColorMap plottable.
  21825. This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref
  21826. QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a
  21827. color, depending on the value.
  21828. The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize).
  21829. Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref
  21830. setKeyRange, \ref setValueRange).
  21831. The data cells can be accessed in two ways: They can be directly addressed by an integer index
  21832. with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot
  21833. coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are
  21834. provided by the functions \ref coordToCell and \ref cellToCoord.
  21835. A \ref QCPColorMapData also holds an on-demand two-dimensional array of alpha values which (if
  21836. allocated) has the same size as the data map. It can be accessed via \ref setAlpha, \ref
  21837. fillAlpha and \ref clearAlpha. The memory for the alpha map is only allocated if needed, i.e. on
  21838. the first call of \ref setAlpha. \ref clearAlpha restores full opacity and frees the alpha map.
  21839. This class also buffers the minimum and maximum values that are in the data set, to provide
  21840. QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value
  21841. that is greater than the current maximum increases this maximum to the new value. However,
  21842. setting the cell that currently holds the maximum value to a smaller value doesn't decrease the
  21843. maximum again, because finding the true new maximum would require going through the entire data
  21844. array, which might be time consuming. The same holds for the data minimum. This functionality is
  21845. given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the
  21846. true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience
  21847. parameter \a recalculateDataBounds which may be set to true to automatically call \ref
  21848. recalculateDataBounds internally.
  21849. */
  21850. /* start of documentation of inline functions */
  21851. /*! \fn bool QCPColorMapData::isEmpty() const
  21852. Returns whether this instance carries no data. This is equivalent to having a size where at least
  21853. one of the dimensions is 0 (see \ref setSize).
  21854. */
  21855. /* end of documentation of inline functions */
  21856. /*!
  21857. Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction
  21858. and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap
  21859. at the coordinates \a keyRange and \a valueRange.
  21860. \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange
  21861. */
  21862. QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) :
  21863. mKeySize(0),
  21864. mValueSize(0),
  21865. mKeyRange(keyRange),
  21866. mValueRange(valueRange),
  21867. mIsEmpty(true),
  21868. mData(nullptr),
  21869. mAlpha(nullptr),
  21870. mDataModified(true)
  21871. {
  21872. setSize(keySize, valueSize);
  21873. fill(0);
  21874. }
  21875. QCPColorMapData::~QCPColorMapData()
  21876. {
  21877. delete[] mData;
  21878. delete[] mAlpha;
  21879. }
  21880. /*!
  21881. Constructs a new QCPColorMapData instance copying the data and range of \a other.
  21882. */
  21883. QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) :
  21884. mKeySize(0),
  21885. mValueSize(0),
  21886. mIsEmpty(true),
  21887. mData(nullptr),
  21888. mAlpha(nullptr),
  21889. mDataModified(true)
  21890. {
  21891. *this = other;
  21892. }
  21893. /*!
  21894. Overwrites this color map data instance with the data stored in \a other. The alpha map state is
  21895. transferred, too.
  21896. */
  21897. QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other)
  21898. {
  21899. if (&other != this)
  21900. {
  21901. const int keySize = other.keySize();
  21902. const int valueSize = other.valueSize();
  21903. if (!other.mAlpha && mAlpha)
  21904. clearAlpha();
  21905. setSize(keySize, valueSize);
  21906. if (other.mAlpha && !mAlpha)
  21907. createAlpha(false);
  21908. setRange(other.keyRange(), other.valueRange());
  21909. if (!isEmpty())
  21910. {
  21911. memcpy(mData, other.mData, sizeof(mData[0])*size_t(keySize*valueSize));
  21912. if (mAlpha)
  21913. memcpy(mAlpha, other.mAlpha, sizeof(mAlpha[0])*size_t(keySize*valueSize));
  21914. }
  21915. mDataBounds = other.mDataBounds;
  21916. mDataModified = true;
  21917. }
  21918. return *this;
  21919. }
  21920. /* undocumented getter */
  21921. double QCPColorMapData::data(double key, double value)
  21922. {
  21923. int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
  21924. int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
  21925. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  21926. return mData[valueCell*mKeySize + keyCell];
  21927. else
  21928. return 0;
  21929. }
  21930. /* undocumented getter */
  21931. double QCPColorMapData::cell(int keyIndex, int valueIndex)
  21932. {
  21933. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  21934. return mData[valueIndex*mKeySize + keyIndex];
  21935. else
  21936. return 0;
  21937. }
  21938. /*!
  21939. Returns the alpha map value of the cell with the indices \a keyIndex and \a valueIndex.
  21940. If this color map data doesn't have an alpha map (because \ref setAlpha was never called after
  21941. creation or after a call to \ref clearAlpha), returns 255, which corresponds to full opacity.
  21942. \see setAlpha
  21943. */
  21944. unsigned char QCPColorMapData::alpha(int keyIndex, int valueIndex)
  21945. {
  21946. if (mAlpha && keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  21947. return mAlpha[valueIndex*mKeySize + keyIndex];
  21948. else
  21949. return 255;
  21950. }
  21951. /*!
  21952. Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in
  21953. the value dimension.
  21954. The current data is discarded and the map cells are set to 0, unless the map had already the
  21955. requested size.
  21956. Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref
  21957. isEmpty returns true.
  21958. \see setRange, setKeySize, setValueSize
  21959. */
  21960. void QCPColorMapData::setSize(int keySize, int valueSize)
  21961. {
  21962. if (keySize != mKeySize || valueSize != mValueSize)
  21963. {
  21964. mKeySize = keySize;
  21965. mValueSize = valueSize;
  21966. delete[] mData;
  21967. mIsEmpty = mKeySize == 0 || mValueSize == 0;
  21968. if (!mIsEmpty)
  21969. {
  21970. #ifdef __EXCEPTIONS
  21971. try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
  21972. #endif
  21973. mData = new double[size_t(mKeySize*mValueSize)];
  21974. #ifdef __EXCEPTIONS
  21975. } catch (...) { mData = nullptr; }
  21976. #endif
  21977. if (mData)
  21978. fill(0);
  21979. else
  21980. qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
  21981. } else
  21982. mData = nullptr;
  21983. if (mAlpha) // if we had an alpha map, recreate it with new size
  21984. createAlpha();
  21985. mDataModified = true;
  21986. }
  21987. }
  21988. /*!
  21989. Resizes the data array to have \a keySize cells in the key dimension.
  21990. The current data is discarded and the map cells are set to 0, unless the map had already the
  21991. requested size.
  21992. Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true.
  21993. \see setKeyRange, setSize, setValueSize
  21994. */
  21995. void QCPColorMapData::setKeySize(int keySize)
  21996. {
  21997. setSize(keySize, mValueSize);
  21998. }
  21999. /*!
  22000. Resizes the data array to have \a valueSize cells in the value dimension.
  22001. The current data is discarded and the map cells are set to 0, unless the map had already the
  22002. requested size.
  22003. Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true.
  22004. \see setValueRange, setSize, setKeySize
  22005. */
  22006. void QCPColorMapData::setValueSize(int valueSize)
  22007. {
  22008. setSize(mKeySize, valueSize);
  22009. }
  22010. /*!
  22011. Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area
  22012. covered by the color map in plot coordinates.
  22013. The outer cells will be centered on the range boundaries given to this function. For example, if
  22014. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  22015. be cells centered on the key coordinates 2, 2.5 and 3.
  22016. \see setSize
  22017. */
  22018. void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange)
  22019. {
  22020. setKeyRange(keyRange);
  22021. setValueRange(valueRange);
  22022. }
  22023. /*!
  22024. Sets the coordinate range the data shall be distributed over in the key dimension. Together with
  22025. the value range, This defines the rectangular area covered by the color map in plot coordinates.
  22026. The outer cells will be centered on the range boundaries given to this function. For example, if
  22027. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  22028. be cells centered on the key coordinates 2, 2.5 and 3.
  22029. \see setRange, setValueRange, setSize
  22030. */
  22031. void QCPColorMapData::setKeyRange(const QCPRange &keyRange)
  22032. {
  22033. mKeyRange = keyRange;
  22034. }
  22035. /*!
  22036. Sets the coordinate range the data shall be distributed over in the value dimension. Together with
  22037. the key range, This defines the rectangular area covered by the color map in plot coordinates.
  22038. The outer cells will be centered on the range boundaries given to this function. For example, if
  22039. the value size (\ref setValueSize) is 3 and \a valueRange is set to <tt>QCPRange(2, 3)</tt> there
  22040. will be cells centered on the value coordinates 2, 2.5 and 3.
  22041. \see setRange, setKeyRange, setSize
  22042. */
  22043. void QCPColorMapData::setValueRange(const QCPRange &valueRange)
  22044. {
  22045. mValueRange = valueRange;
  22046. }
  22047. /*!
  22048. Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a
  22049. z.
  22050. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22051. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22052. you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
  22053. determine the cell index. Rather directly access the cell index with \ref
  22054. QCPColorMapData::setCell.
  22055. \see setCell, setRange
  22056. */
  22057. void QCPColorMapData::setData(double key, double value, double z)
  22058. {
  22059. int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
  22060. int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
  22061. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  22062. {
  22063. mData[valueCell*mKeySize + keyCell] = z;
  22064. if (z < mDataBounds.lower)
  22065. mDataBounds.lower = z;
  22066. if (z > mDataBounds.upper)
  22067. mDataBounds.upper = z;
  22068. mDataModified = true;
  22069. }
  22070. }
  22071. /*!
  22072. Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices
  22073. enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see
  22074. \ref setSize).
  22075. In the standard plot configuration (horizontal key axis and vertical value axis, both not
  22076. range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with
  22077. indices (keySize-1, valueSize-1) is in the top right corner of the color map.
  22078. \see setData, setSize
  22079. */
  22080. void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z)
  22081. {
  22082. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  22083. {
  22084. mData[valueIndex*mKeySize + keyIndex] = z;
  22085. if (z < mDataBounds.lower)
  22086. mDataBounds.lower = z;
  22087. if (z > mDataBounds.upper)
  22088. mDataBounds.upper = z;
  22089. mDataModified = true;
  22090. } else
  22091. qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
  22092. }
  22093. /*!
  22094. Sets the alpha of the color map cell given by \a keyIndex and \a valueIndex to \a alpha. A value
  22095. of 0 for \a alpha results in a fully transparent cell, and a value of 255 results in a fully
  22096. opaque cell.
  22097. If an alpha map doesn't exist yet for this color map data, it will be created here. If you wish
  22098. to restore full opacity and free any allocated memory of the alpha map, call \ref clearAlpha.
  22099. Note that the cell-wise alpha which can be configured here is independent of any alpha configured
  22100. in the color map's gradient (\ref QCPColorGradient). If a cell is affected both by the cell-wise
  22101. and gradient alpha, the alpha values will be blended accordingly during rendering of the color
  22102. map.
  22103. \see fillAlpha, clearAlpha
  22104. */
  22105. void QCPColorMapData::setAlpha(int keyIndex, int valueIndex, unsigned char alpha)
  22106. {
  22107. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  22108. {
  22109. if (mAlpha || createAlpha())
  22110. {
  22111. mAlpha[valueIndex*mKeySize + keyIndex] = alpha;
  22112. mDataModified = true;
  22113. }
  22114. } else
  22115. qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
  22116. }
  22117. /*!
  22118. Goes through the data and updates the buffered minimum and maximum data values.
  22119. Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange
  22120. and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten
  22121. with a smaller or larger value respectively, since the buffered maximum/minimum values have been
  22122. updated the last time. Why this is the case is explained in the class description (\ref
  22123. QCPColorMapData).
  22124. Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a
  22125. recalculateDataBounds for convenience. Setting this to true will call this method for you, before
  22126. doing the rescale.
  22127. */
  22128. void QCPColorMapData::recalculateDataBounds()
  22129. {
  22130. if (mKeySize > 0 && mValueSize > 0)
  22131. {
  22132. double minHeight = mData[0];
  22133. double maxHeight = mData[0];
  22134. const int dataCount = mValueSize*mKeySize;
  22135. for (int i=0; i<dataCount; ++i)
  22136. {
  22137. if (mData[i] > maxHeight)
  22138. maxHeight = mData[i];
  22139. if (mData[i] < minHeight)
  22140. minHeight = mData[i];
  22141. }
  22142. mDataBounds.lower = minHeight;
  22143. mDataBounds.upper = maxHeight;
  22144. }
  22145. }
  22146. /*!
  22147. Frees the internal data memory.
  22148. This is equivalent to calling \ref setSize "setSize(0, 0)".
  22149. */
  22150. void QCPColorMapData::clear()
  22151. {
  22152. setSize(0, 0);
  22153. }
  22154. /*!
  22155. Frees the internal alpha map. The color map will have full opacity again.
  22156. */
  22157. void QCPColorMapData::clearAlpha()
  22158. {
  22159. if (mAlpha)
  22160. {
  22161. delete[] mAlpha;
  22162. mAlpha = nullptr;
  22163. mDataModified = true;
  22164. }
  22165. }
  22166. /*!
  22167. Sets all cells to the value \a z.
  22168. */
  22169. void QCPColorMapData::fill(double z)
  22170. {
  22171. const int dataCount = mValueSize*mKeySize;
  22172. for (int i=0; i<dataCount; ++i)
  22173. mData[i] = z;
  22174. mDataBounds = QCPRange(z, z);
  22175. mDataModified = true;
  22176. }
  22177. /*!
  22178. Sets the opacity of all color map cells to \a alpha. A value of 0 for \a alpha results in a fully
  22179. transparent color map, and a value of 255 results in a fully opaque color map.
  22180. If you wish to restore opacity to 100% and free any used memory for the alpha map, rather use
  22181. \ref clearAlpha.
  22182. \see setAlpha
  22183. */
  22184. void QCPColorMapData::fillAlpha(unsigned char alpha)
  22185. {
  22186. if (mAlpha || createAlpha(false))
  22187. {
  22188. const int dataCount = mValueSize*mKeySize;
  22189. for (int i=0; i<dataCount; ++i)
  22190. mAlpha[i] = alpha;
  22191. mDataModified = true;
  22192. }
  22193. }
  22194. /*!
  22195. Transforms plot coordinates given by \a key and \a value to cell indices of this QCPColorMapData
  22196. instance. The resulting cell indices are returned via the output parameters \a keyIndex and \a
  22197. valueIndex.
  22198. The retrieved key/value cell indices can then be used for example with \ref setCell.
  22199. If you are only interested in a key or value index, you may pass \c nullptr as \a valueIndex or
  22200. \a keyIndex.
  22201. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22202. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22203. you shouldn't use the \ref QCPColorMapData::coordToCell method as it uses a linear transformation to
  22204. determine the cell index.
  22205. \see cellToCoord, QCPAxis::coordToPixel
  22206. */
  22207. void QCPColorMapData::coordToCell(double key, double value, int *keyIndex, int *valueIndex) const
  22208. {
  22209. if (keyIndex)
  22210. *keyIndex = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5 );
  22211. if (valueIndex)
  22212. *valueIndex = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
  22213. }
  22214. /*!
  22215. Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices of this QCPColorMapData
  22216. instance. The resulting coordinates are returned via the output parameters \a key and \a
  22217. value.
  22218. If you are only interested in a key or value coordinate, you may pass \c nullptr as \a key or \a
  22219. value.
  22220. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22221. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22222. you shouldn't use the \ref QCPColorMapData::cellToCoord method as it uses a linear transformation to
  22223. determine the cell index.
  22224. \see coordToCell, QCPAxis::pixelToCoord
  22225. */
  22226. void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const
  22227. {
  22228. if (key)
  22229. *key = keyIndex/double(mKeySize-1)*(mKeyRange.upper-mKeyRange.lower)+mKeyRange.lower;
  22230. if (value)
  22231. *value = valueIndex/double(mValueSize-1)*(mValueRange.upper-mValueRange.lower)+mValueRange.lower;
  22232. }
  22233. /*! \internal
  22234. Allocates the internal alpha map with the current data map key/value size and, if \a
  22235. initializeOpaque is true, initializes all values to 255. If \a initializeOpaque is false, the
  22236. values are not initialized at all. In this case, the alpha map should be initialized manually,
  22237. e.g. with \ref fillAlpha.
  22238. If an alpha map exists already, it is deleted first. If this color map is empty (has either key
  22239. or value size zero, see \ref isEmpty), the alpha map is cleared.
  22240. The return value indicates the existence of the alpha map after the call. So this method returns
  22241. true if the data map isn't empty and an alpha map was successfully allocated.
  22242. */
  22243. bool QCPColorMapData::createAlpha(bool initializeOpaque)
  22244. {
  22245. clearAlpha();
  22246. if (isEmpty())
  22247. return false;
  22248. #ifdef __EXCEPTIONS
  22249. try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
  22250. #endif
  22251. mAlpha = new unsigned char[size_t(mKeySize*mValueSize)];
  22252. #ifdef __EXCEPTIONS
  22253. } catch (...) { mAlpha = nullptr; }
  22254. #endif
  22255. if (mAlpha)
  22256. {
  22257. if (initializeOpaque)
  22258. fillAlpha(255);
  22259. return true;
  22260. } else
  22261. {
  22262. qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
  22263. return false;
  22264. }
  22265. }
  22266. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22267. //////////////////// QCPColorMap
  22268. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22269. /*! \class QCPColorMap
  22270. \brief A plottable representing a two-dimensional color map in a plot.
  22271. \image html QCPColorMap.png
  22272. The data is stored in the class \ref QCPColorMapData, which can be accessed via the data()
  22273. method.
  22274. A color map has three dimensions to represent a data point: The \a key dimension, the \a value
  22275. dimension and the \a data dimension. As with other plottables such as graphs, \a key and \a value
  22276. correspond to two orthogonal axes on the QCustomPlot surface that you specify in the QCPColorMap
  22277. constructor. The \a data dimension however is encoded as the color of the point at (\a key, \a
  22278. value).
  22279. Set the number of points (or \a cells) in the key/value dimension via \ref
  22280. QCPColorMapData::setSize. The plot coordinate range over which these points will be displayed is
  22281. specified via \ref QCPColorMapData::setRange. The first cell will be centered on the lower range
  22282. boundary and the last cell will be centered on the upper range boundary. The data can be set by
  22283. either accessing the cells directly with QCPColorMapData::setCell or by addressing the cells via
  22284. their plot coordinates with \ref QCPColorMapData::setData. If possible, you should prefer
  22285. setCell, since it doesn't need to do any coordinate transformation and thus performs a bit
  22286. better.
  22287. The cell with index (0, 0) is at the bottom left, if the color map uses normal (i.e. not reversed)
  22288. key and value axes.
  22289. To show the user which colors correspond to which \a data values, a \ref QCPColorScale is
  22290. typically placed to the right of the axis rect. See the documentation there for details on how to
  22291. add and use a color scale.
  22292. \section qcpcolormap-appearance Changing the appearance
  22293. Most important to the appearance is the color gradient, which can be specified via \ref
  22294. setGradient. See the documentation of \ref QCPColorGradient for details on configuring a color
  22295. gradient.
  22296. The \a data range that is mapped to the colors of the gradient can be specified with \ref
  22297. setDataRange. To make the data range encompass the whole data set minimum to maximum, call \ref
  22298. rescaleDataRange. If your data may contain NaN values, use \ref QCPColorGradient::setNanHandling
  22299. to define how they are displayed.
  22300. \section qcpcolormap-transparency Transparency
  22301. Transparency in color maps can be achieved by two mechanisms. On one hand, you can specify alpha
  22302. values for color stops of the \ref QCPColorGradient, via the regular QColor interface. This will
  22303. cause the color map data which gets mapped to colors around those color stops to appear with the
  22304. accordingly interpolated transparency.
  22305. On the other hand you can also directly apply an alpha value to each cell independent of its
  22306. data, by using the alpha map feature of \ref QCPColorMapData. The relevant methods are \ref
  22307. QCPColorMapData::setAlpha, QCPColorMapData::fillAlpha and \ref QCPColorMapData::clearAlpha().
  22308. The two transparencies will be joined together in the plot and otherwise not interfere with each
  22309. other. They are mixed in a multiplicative matter, so an alpha of e.g. 50% (128/255) in both modes
  22310. simultaneously, will result in a total transparency of 25% (64/255).
  22311. \section qcpcolormap-usage Usage
  22312. Like all data representing objects in QCustomPlot, the QCPColorMap is a plottable
  22313. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  22314. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  22315. Usually, you first create an instance:
  22316. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-1
  22317. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  22318. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  22319. The newly created plottable can be modified, e.g.:
  22320. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-2
  22321. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22322. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22323. you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
  22324. determine the cell index. Rather directly access the cell index with \ref
  22325. QCPColorMapData::setCell.
  22326. */
  22327. /* start documentation of inline functions */
  22328. /*! \fn QCPColorMapData *QCPColorMap::data() const
  22329. Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to
  22330. modify data points (cells) and the color map key/value range.
  22331. \see setData
  22332. */
  22333. /* end documentation of inline functions */
  22334. /* start documentation of signals */
  22335. /*! \fn void QCPColorMap::dataRangeChanged(const QCPRange &newRange);
  22336. This signal is emitted when the data range changes.
  22337. \see setDataRange
  22338. */
  22339. /*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  22340. This signal is emitted when the data scale type changes.
  22341. \see setDataScaleType
  22342. */
  22343. /*! \fn void QCPColorMap::gradientChanged(const QCPColorGradient &newGradient);
  22344. This signal is emitted when the gradient changes.
  22345. \see setGradient
  22346. */
  22347. /* end documentation of signals */
  22348. /*!
  22349. Constructs a color map with the specified \a keyAxis and \a valueAxis.
  22350. The created QCPColorMap is automatically registered with the QCustomPlot instance inferred from
  22351. \a keyAxis. This QCustomPlot instance takes ownership of the QCPColorMap, so do not delete it
  22352. manually but use QCustomPlot::removePlottable() instead.
  22353. */
  22354. QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  22355. QCPAbstractPlottable(keyAxis, valueAxis),
  22356. mDataScaleType(QCPAxis::stLinear),
  22357. mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))),
  22358. mGradient(QCPColorGradient::gpCold),
  22359. mInterpolate(true),
  22360. mTightBoundary(false),
  22361. mMapImageInvalidated(true)
  22362. {
  22363. }
  22364. QCPColorMap::~QCPColorMap()
  22365. {
  22366. delete mMapData;
  22367. }
  22368. /*!
  22369. Replaces the current \ref data with the provided \a data.
  22370. If \a copy is set to true, the \a data object will only be copied. if false, the color map
  22371. takes ownership of the passed data and replaces the internal data pointer with it. This is
  22372. significantly faster than copying for large datasets.
  22373. */
  22374. void QCPColorMap::setData(QCPColorMapData *data, bool copy)
  22375. {
  22376. if (mMapData == data)
  22377. {
  22378. qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
  22379. return;
  22380. }
  22381. if (copy)
  22382. {
  22383. *mMapData = *data;
  22384. } else
  22385. {
  22386. delete mMapData;
  22387. mMapData = data;
  22388. }
  22389. mMapImageInvalidated = true;
  22390. }
  22391. /*!
  22392. Sets the data range of this color map to \a dataRange. The data range defines which data values
  22393. are mapped to the color gradient.
  22394. To make the data range span the full range of the data set, use \ref rescaleDataRange.
  22395. \see QCPColorScale::setDataRange
  22396. */
  22397. void QCPColorMap::setDataRange(const QCPRange &dataRange)
  22398. {
  22399. if (!QCPRange::validRange(dataRange)) return;
  22400. if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
  22401. {
  22402. if (mDataScaleType == QCPAxis::stLogarithmic)
  22403. mDataRange = dataRange.sanitizedForLogScale();
  22404. else
  22405. mDataRange = dataRange.sanitizedForLinScale();
  22406. mMapImageInvalidated = true;
  22407. Q_EMIT dataRangeChanged(mDataRange);
  22408. }
  22409. }
  22410. /*!
  22411. Sets whether the data is correlated with the color gradient linearly or logarithmically.
  22412. \see QCPColorScale::setDataScaleType
  22413. */
  22414. void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType)
  22415. {
  22416. if (mDataScaleType != scaleType)
  22417. {
  22418. mDataScaleType = scaleType;
  22419. mMapImageInvalidated = true;
  22420. Q_EMIT dataScaleTypeChanged(mDataScaleType);
  22421. if (mDataScaleType == QCPAxis::stLogarithmic)
  22422. setDataRange(mDataRange.sanitizedForLogScale());
  22423. }
  22424. }
  22425. /*!
  22426. Sets the color gradient that is used to represent the data. For more details on how to create an
  22427. own gradient or use one of the preset gradients, see \ref QCPColorGradient.
  22428. The colors defined by the gradient will be used to represent data values in the currently set
  22429. data range, see \ref setDataRange. Data points that are outside this data range will either be
  22430. colored uniformly with the respective gradient boundary color, or the gradient will repeat,
  22431. depending on \ref QCPColorGradient::setPeriodic.
  22432. \see QCPColorScale::setGradient
  22433. */
  22434. void QCPColorMap::setGradient(const QCPColorGradient &gradient)
  22435. {
  22436. if (mGradient != gradient)
  22437. {
  22438. mGradient = gradient;
  22439. mMapImageInvalidated = true;
  22440. Q_EMIT gradientChanged(mGradient);
  22441. }
  22442. }
  22443. /*!
  22444. Sets whether the color map image shall use bicubic interpolation when displaying the color map
  22445. shrinked or expanded, and not at a 1:1 pixel-to-data scale.
  22446. \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled"
  22447. */
  22448. void QCPColorMap::setInterpolate(bool enabled)
  22449. {
  22450. mInterpolate = enabled;
  22451. mMapImageInvalidated = true; // because oversampling factors might need to change
  22452. }
  22453. /*!
  22454. Sets whether the outer most data rows and columns are clipped to the specified key and value
  22455. range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange).
  22456. if \a enabled is set to false, the data points at the border of the color map are drawn with the
  22457. same width and height as all other data points. Since the data points are represented by
  22458. rectangles of one color centered on the data coordinate, this means that the shown color map
  22459. extends by half a data point over the specified key/value range in each direction.
  22460. \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled"
  22461. */
  22462. void QCPColorMap::setTightBoundary(bool enabled)
  22463. {
  22464. mTightBoundary = enabled;
  22465. }
  22466. /*!
  22467. Associates the color scale \a colorScale with this color map.
  22468. This means that both the color scale and the color map synchronize their gradient, data range and
  22469. data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps
  22470. can be associated with one single color scale. This causes the color maps to also synchronize
  22471. those properties, via the mutual color scale.
  22472. This function causes the color map to adopt the current color gradient, data range and data scale
  22473. type of \a colorScale. After this call, you may change these properties at either the color map
  22474. or the color scale, and the setting will be applied to both.
  22475. Pass \c nullptr as \a colorScale to disconnect the color scale from this color map again.
  22476. */
  22477. void QCPColorMap::setColorScale(QCPColorScale *colorScale)
  22478. {
  22479. if (mColorScale) // unconnect signals from old color scale
  22480. {
  22481. disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
  22482. disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22483. disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
  22484. disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  22485. disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
  22486. disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22487. }
  22488. mColorScale = colorScale;
  22489. if (mColorScale) // connect signals to new color scale
  22490. {
  22491. setGradient(mColorScale.data()->gradient());
  22492. setDataRange(mColorScale.data()->dataRange());
  22493. setDataScaleType(mColorScale.data()->dataScaleType());
  22494. connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
  22495. connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22496. connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
  22497. connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  22498. connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
  22499. connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22500. }
  22501. }
  22502. /*!
  22503. Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the
  22504. current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods,
  22505. only for the third data dimension of the color map.
  22506. The minimum and maximum values of the data set are buffered in the internal QCPColorMapData
  22507. instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref
  22508. QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For
  22509. performance reasons, however, they are only updated in an expanding fashion. So the buffered
  22510. maximum can only increase and the buffered minimum can only decrease. In consequence, changes to
  22511. the data that actually lower the maximum of the data set (by overwriting the cell holding the
  22512. current maximum with a smaller value), aren't recognized and the buffered maximum overestimates
  22513. the true maximum of the data set. The same happens for the buffered minimum. To recalculate the
  22514. true minimum and maximum by explicitly looking at each cell, the method
  22515. QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a
  22516. recalculateDataBounds calls this method before setting the data range to the buffered minimum and
  22517. maximum.
  22518. \see setDataRange
  22519. */
  22520. void QCPColorMap::rescaleDataRange(bool recalculateDataBounds)
  22521. {
  22522. if (recalculateDataBounds)
  22523. mMapData->recalculateDataBounds();
  22524. setDataRange(mMapData->dataBounds());
  22525. }
  22526. /*!
  22527. Takes the current appearance of the color map and updates the legend icon, which is used to
  22528. represent this color map in the legend (see \ref QCPLegend).
  22529. The \a transformMode specifies whether the rescaling is done by a faster, low quality image
  22530. scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm
  22531. (Qt::SmoothTransformation).
  22532. The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to
  22533. the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured
  22534. legend icon size, the thumb will be rescaled during drawing of the legend item.
  22535. \see setDataRange
  22536. */
  22537. void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize)
  22538. {
  22539. if (mMapImage.isNull() && !data()->isEmpty())
  22540. updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet)
  22541. if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again
  22542. {
  22543. bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  22544. bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  22545. mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode);
  22546. }
  22547. }
  22548. /* inherits documentation from base class */
  22549. double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  22550. {
  22551. Q_UNUSED(details)
  22552. if ((onlySelectable && mSelectable == QCP::stNone) || mMapData->isEmpty())
  22553. return -1;
  22554. if (!mKeyAxis || !mValueAxis)
  22555. return -1;
  22556. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  22557. {
  22558. double posKey, posValue;
  22559. pixelsToCoords(pos, posKey, posValue);
  22560. if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue))
  22561. {
  22562. if (details)
  22563. details->setValue(QCPDataSelection(QCPDataRange(0, 1))); // temporary solution, to facilitate whole-plottable selection. Replace in future version with segmented 2D selection.
  22564. return mParentPlot->selectionTolerance()*0.99;
  22565. }
  22566. }
  22567. return -1;
  22568. }
  22569. /* inherits documentation from base class */
  22570. QCPRange QCPColorMap::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  22571. {
  22572. foundRange = true;
  22573. QCPRange result = mMapData->keyRange();
  22574. result.normalize();
  22575. if (inSignDomain == QCP::sdPositive)
  22576. {
  22577. if (result.lower <= 0 && result.upper > 0)
  22578. result.lower = result.upper*1e-3;
  22579. else if (result.lower <= 0 && result.upper <= 0)
  22580. foundRange = false;
  22581. } else if (inSignDomain == QCP::sdNegative)
  22582. {
  22583. if (result.upper >= 0 && result.lower < 0)
  22584. result.upper = result.lower*1e-3;
  22585. else if (result.upper >= 0 && result.lower >= 0)
  22586. foundRange = false;
  22587. }
  22588. return result;
  22589. }
  22590. /* inherits documentation from base class */
  22591. QCPRange QCPColorMap::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  22592. {
  22593. if (inKeyRange != QCPRange())
  22594. {
  22595. if (mMapData->keyRange().upper < inKeyRange.lower || mMapData->keyRange().lower > inKeyRange.upper)
  22596. {
  22597. foundRange = false;
  22598. return {};
  22599. }
  22600. }
  22601. foundRange = true;
  22602. QCPRange result = mMapData->valueRange();
  22603. result.normalize();
  22604. if (inSignDomain == QCP::sdPositive)
  22605. {
  22606. if (result.lower <= 0 && result.upper > 0)
  22607. result.lower = result.upper*1e-3;
  22608. else if (result.lower <= 0 && result.upper <= 0)
  22609. foundRange = false;
  22610. } else if (inSignDomain == QCP::sdNegative)
  22611. {
  22612. if (result.upper >= 0 && result.lower < 0)
  22613. result.upper = result.lower*1e-3;
  22614. else if (result.upper >= 0 && result.lower >= 0)
  22615. foundRange = false;
  22616. }
  22617. return result;
  22618. }
  22619. /*! \internal
  22620. Updates the internal map image buffer by going through the internal \ref QCPColorMapData and
  22621. turning the data values into color pixels with \ref QCPColorGradient::colorize.
  22622. This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image
  22623. has been invalidated for a different reason (e.g. a change of the data range with \ref
  22624. setDataRange).
  22625. If the map cell count is low, the image created will be oversampled in order to avoid a
  22626. QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images
  22627. without smooth transform enabled. Accordingly, oversampling isn't performed if \ref
  22628. setInterpolate is true.
  22629. */
  22630. void QCPColorMap::updateMapImage()
  22631. {
  22632. QCPAxis *keyAxis = mKeyAxis.data();
  22633. if (!keyAxis) return;
  22634. if (mMapData->isEmpty()) return;
  22635. const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
  22636. const int keySize = mMapData->keySize();
  22637. const int valueSize = mMapData->valueSize();
  22638. int keyOversamplingFactor = mInterpolate ? 1 : int(1.0+100.0/double(keySize)); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on
  22639. int valueOversamplingFactor = mInterpolate ? 1 : int(1.0+100.0/double(valueSize)); // make mMapImage have at least size 100, factor becomes 1 if size > 200 or interpolation is on
  22640. // resize mMapImage to correct dimensions including possible oversampling factors, according to key/value axes orientation:
  22641. if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.width() != keySize*keyOversamplingFactor || mMapImage.height() != valueSize*valueOversamplingFactor))
  22642. mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), format);
  22643. else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor))
  22644. mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), format);
  22645. if (mMapImage.isNull())
  22646. {
  22647. qDebug() << Q_FUNC_INFO << "Couldn't create map image (possibly too large for memory)";
  22648. mMapImage = QImage(QSize(10, 10), format);
  22649. mMapImage.fill(Qt::black);
  22650. } else
  22651. {
  22652. QImage *localMapImage = &mMapImage; // this is the image on which the colorization operates. Either the final mMapImage, or if we need oversampling, mUndersampledMapImage
  22653. if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
  22654. {
  22655. // resize undersampled map image to actual key/value cell sizes:
  22656. if (keyAxis->orientation() == Qt::Horizontal && (mUndersampledMapImage.width() != keySize || mUndersampledMapImage.height() != valueSize))
  22657. mUndersampledMapImage = QImage(QSize(keySize, valueSize), format);
  22658. else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize))
  22659. mUndersampledMapImage = QImage(QSize(valueSize, keySize), format);
  22660. localMapImage = &mUndersampledMapImage; // make the colorization run on the undersampled image
  22661. } else if (!mUndersampledMapImage.isNull())
  22662. mUndersampledMapImage = QImage(); // don't need oversampling mechanism anymore (map size has changed) but mUndersampledMapImage still has nonzero size, free it
  22663. const double *rawData = mMapData->mData;
  22664. const unsigned char *rawAlpha = mMapData->mAlpha;
  22665. if (keyAxis->orientation() == Qt::Horizontal)
  22666. {
  22667. const int lineCount = valueSize;
  22668. const int rowCount = keySize;
  22669. for (int line=0; line<lineCount; ++line)
  22670. {
  22671. QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system)
  22672. if (rawAlpha)
  22673. mGradient.colorize(rawData+line*rowCount, rawAlpha+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
  22674. else
  22675. mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic);
  22676. }
  22677. } else // keyAxis->orientation() == Qt::Vertical
  22678. {
  22679. const int lineCount = keySize;
  22680. const int rowCount = valueSize;
  22681. for (int line=0; line<lineCount; ++line)
  22682. {
  22683. QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system)
  22684. if (rawAlpha)
  22685. mGradient.colorize(rawData+line, rawAlpha+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
  22686. else
  22687. mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic);
  22688. }
  22689. }
  22690. if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
  22691. {
  22692. if (keyAxis->orientation() == Qt::Horizontal)
  22693. mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
  22694. else
  22695. mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
  22696. }
  22697. }
  22698. mMapData->mDataModified = false;
  22699. mMapImageInvalidated = false;
  22700. }
  22701. /* inherits documentation from base class */
  22702. void QCPColorMap::draw(QCPPainter *painter)
  22703. {
  22704. if (mMapData->isEmpty()) return;
  22705. if (!mKeyAxis || !mValueAxis) return;
  22706. applyDefaultAntialiasingHint(painter);
  22707. if (mMapData->mDataModified || mMapImageInvalidated)
  22708. updateMapImage();
  22709. // use buffer if painting vectorized (PDF):
  22710. const bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized);
  22711. QCPPainter *localPainter = painter; // will be redirected to paint on mapBuffer if painting vectorized
  22712. QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map portion/buffer will end up in
  22713. QPixmap mapBuffer;
  22714. if (useBuffer)
  22715. {
  22716. const double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps
  22717. mapBufferTarget = painter->clipRegion().boundingRect();
  22718. mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize());
  22719. mapBuffer.fill(Qt::transparent);
  22720. localPainter = new QCPPainter(&mapBuffer);
  22721. localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio);
  22722. localPainter->translate(-mapBufferTarget.topLeft());
  22723. }
  22724. QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
  22725. coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
  22726. // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary):
  22727. double halfCellWidth = 0; // in pixels
  22728. double halfCellHeight = 0; // in pixels
  22729. if (keyAxis()->orientation() == Qt::Horizontal)
  22730. {
  22731. if (mMapData->keySize() > 1)
  22732. halfCellWidth = 0.5*imageRect.width()/double(mMapData->keySize()-1);
  22733. if (mMapData->valueSize() > 1)
  22734. halfCellHeight = 0.5*imageRect.height()/double(mMapData->valueSize()-1);
  22735. } else // keyAxis orientation is Qt::Vertical
  22736. {
  22737. if (mMapData->keySize() > 1)
  22738. halfCellHeight = 0.5*imageRect.height()/double(mMapData->keySize()-1);
  22739. if (mMapData->valueSize() > 1)
  22740. halfCellWidth = 0.5*imageRect.width()/double(mMapData->valueSize()-1);
  22741. }
  22742. imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight);
  22743. const bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  22744. const bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  22745. const bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform);
  22746. localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate);
  22747. QRegion clipBackup;
  22748. if (mTightBoundary)
  22749. {
  22750. clipBackup = localPainter->clipRegion();
  22751. QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
  22752. coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
  22753. localPainter->setClipRect(tightClipRect, Qt::IntersectClip);
  22754. }
  22755. localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY));
  22756. if (mTightBoundary)
  22757. localPainter->setClipRegion(clipBackup);
  22758. localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup);
  22759. if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter
  22760. {
  22761. delete localPainter;
  22762. painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer);
  22763. }
  22764. }
  22765. /* inherits documentation from base class */
  22766. void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  22767. {
  22768. applyDefaultAntialiasingHint(painter);
  22769. // draw map thumbnail:
  22770. if (!mLegendIcon.isNull())
  22771. {
  22772. QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation);
  22773. QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height());
  22774. iconRect.moveCenter(rect.center());
  22775. painter->drawPixmap(iconRect.topLeft(), scaledIcon);
  22776. }
  22777. /*
  22778. // draw frame:
  22779. painter->setBrush(Qt::NoBrush);
  22780. painter->setPen(Qt::black);
  22781. painter->drawRect(rect.adjusted(1, 1, 0, 0));
  22782. */
  22783. }
  22784. /* end of 'src/plottables/plottable-colormap.cpp' */
  22785. /* including file 'src/plottables/plottable-financial.cpp' */
  22786. /* modified 2021-03-29T02:30:44, size 42914 */
  22787. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22788. //////////////////// QCPFinancialData
  22789. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22790. /*! \class QCPFinancialData
  22791. \brief Holds the data of one single data point for QCPFinancial.
  22792. The stored data is:
  22793. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  22794. \li \a open: The opening value at the data point (this is the \a mainValue)
  22795. \li \a high: The high/maximum value at the data point
  22796. \li \a low: The low/minimum value at the data point
  22797. \li \a close: The closing value at the data point
  22798. The container for storing multiple data points is \ref QCPFinancialDataContainer. It is a typedef
  22799. for \ref QCPDataContainer with \ref QCPFinancialData as the DataType template parameter. See the
  22800. documentation there for an explanation regarding the data type's generic methods.
  22801. \see QCPFinancialDataContainer
  22802. */
  22803. /* start documentation of inline functions */
  22804. /*! \fn double QCPFinancialData::sortKey() const
  22805. Returns the \a key member of this data point.
  22806. For a general explanation of what this method is good for in the context of the data container,
  22807. see the documentation of \ref QCPDataContainer.
  22808. */
  22809. /*! \fn static QCPFinancialData QCPFinancialData::fromSortKey(double sortKey)
  22810. Returns a data point with the specified \a sortKey. All other members are set to zero.
  22811. For a general explanation of what this method is good for in the context of the data container,
  22812. see the documentation of \ref QCPDataContainer.
  22813. */
  22814. /*! \fn static static bool QCPFinancialData::sortKeyIsMainKey()
  22815. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  22816. this method returns true.
  22817. For a general explanation of what this method is good for in the context of the data container,
  22818. see the documentation of \ref QCPDataContainer.
  22819. */
  22820. /*! \fn double QCPFinancialData::mainKey() const
  22821. Returns the \a key member of this data point.
  22822. For a general explanation of what this method is good for in the context of the data container,
  22823. see the documentation of \ref QCPDataContainer.
  22824. */
  22825. /*! \fn double QCPFinancialData::mainValue() const
  22826. Returns the \a open member of this data point.
  22827. For a general explanation of what this method is good for in the context of the data container,
  22828. see the documentation of \ref QCPDataContainer.
  22829. */
  22830. /*! \fn QCPRange QCPFinancialData::valueRange() const
  22831. Returns a QCPRange spanning from the \a low to the \a high value of this data point.
  22832. For a general explanation of what this method is good for in the context of the data container,
  22833. see the documentation of \ref QCPDataContainer.
  22834. */
  22835. /* end documentation of inline functions */
  22836. /*!
  22837. Constructs a data point with key and all values set to zero.
  22838. */
  22839. QCPFinancialData::QCPFinancialData() :
  22840. key(0),
  22841. open(0),
  22842. high(0),
  22843. low(0),
  22844. close(0)
  22845. {
  22846. }
  22847. /*!
  22848. Constructs a data point with the specified \a key and OHLC values.
  22849. */
  22850. QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) :
  22851. key(key),
  22852. open(open),
  22853. high(high),
  22854. low(low),
  22855. close(close)
  22856. {
  22857. }
  22858. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22859. //////////////////// QCPFinancial
  22860. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22861. /*! \class QCPFinancial
  22862. \brief A plottable representing a financial stock chart
  22863. \image html QCPFinancial.png
  22864. This plottable represents time series data binned to certain intervals, mainly used for stock
  22865. charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be
  22866. set via \ref setChartStyle.
  22867. The data is passed via \ref setData as a set of open/high/low/close values at certain keys
  22868. (typically times). This means the data must be already binned appropriately. If data is only
  22869. available as a series of values (e.g. \a price against \a time), you can use the static
  22870. convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed
  22871. to \ref setData.
  22872. The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and \ref
  22873. setWidthType. A typical choice is to set the width type to \ref wtPlotCoords (the default) and
  22874. the width to (or slightly less than) one time bin interval width.
  22875. \section qcpfinancial-appearance Changing the appearance
  22876. Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored,
  22877. lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush).
  22878. If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are
  22879. represented with a different pen and brush than negative changes (\a close < \a open). These can
  22880. be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref
  22881. setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection
  22882. however, the normal selected pen/brush (provided by the \ref selectionDecorator) is used,
  22883. irrespective of whether the chart is single- or two-colored.
  22884. \section qcpfinancial-usage Usage
  22885. Like all data representing objects in QCustomPlot, the QCPFinancial is a plottable
  22886. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  22887. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  22888. Usually, you first create an instance:
  22889. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-1
  22890. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot
  22891. instance takes ownership of the plottable, so do not delete it manually but use
  22892. QCustomPlot::removePlottable() instead. The newly created plottable can be modified, e.g.:
  22893. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-2
  22894. Here we have used the static helper method \ref timeSeriesToOhlc, to turn a time-price data
  22895. series into a 24-hour binned open-high-low-close data series as QCPFinancial uses.
  22896. */
  22897. /* start of documentation of inline functions */
  22898. /*! \fn QCPFinancialDataContainer *QCPFinancial::data() const
  22899. Returns a pointer to the internal data storage of type \ref QCPFinancialDataContainer. You may
  22900. use it to directly manipulate the data, which may be more convenient and faster than using the
  22901. regular \ref setData or \ref addData methods, in certain situations.
  22902. */
  22903. /* end of documentation of inline functions */
  22904. /*!
  22905. Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  22906. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  22907. the same orientation. If either of these restrictions is violated, a corresponding message is
  22908. printed to the debug output (qDebug), the construction is not aborted, though.
  22909. The created QCPFinancial is automatically registered with the QCustomPlot instance inferred from \a
  22910. keyAxis. This QCustomPlot instance takes ownership of the QCPFinancial, so do not delete it manually
  22911. but use QCustomPlot::removePlottable() instead.
  22912. */
  22913. QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  22914. QCPAbstractPlottable1D<QCPFinancialData>(keyAxis, valueAxis),
  22915. mChartStyle(csCandlestick),
  22916. mWidth(0.5),
  22917. mWidthType(wtPlotCoords),
  22918. mTwoColored(true),
  22919. mBrushPositive(QBrush(QColor(50, 160, 0))),
  22920. mBrushNegative(QBrush(QColor(180, 0, 15))),
  22921. mPenPositive(QPen(QColor(40, 150, 0))),
  22922. mPenNegative(QPen(QColor(170, 5, 5)))
  22923. {
  22924. mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
  22925. }
  22926. QCPFinancial::~QCPFinancial()
  22927. {
  22928. }
  22929. /*! \overload
  22930. Replaces the current data container with the provided \a data container.
  22931. Since a QSharedPointer is used, multiple QCPFinancials may share the same data container safely.
  22932. Modifying the data in the container will then affect all financials that share the container.
  22933. Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers:
  22934. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-1
  22935. If you do not wish to share containers, but create a copy from an existing container, rather use
  22936. the \ref QCPDataContainer<DataType>::set method on the financial's data container directly:
  22937. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-2
  22938. \see addData, timeSeriesToOhlc
  22939. */
  22940. void QCPFinancial::setData(QSharedPointer<QCPFinancialDataContainer> data)
  22941. {
  22942. mDataContainer = data;
  22943. }
  22944. /*! \overload
  22945. Replaces the current data with the provided points in \a keys, \a open, \a high, \a low and \a
  22946. close. The provided vectors should have equal length. Else, the number of added points will be
  22947. the size of the smallest vector.
  22948. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  22949. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  22950. \see addData, timeSeriesToOhlc
  22951. */
  22952. void QCPFinancial::setData(const QVector<double> &keys, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close, bool alreadySorted)
  22953. {
  22954. mDataContainer->clear();
  22955. addData(keys, open, high, low, close, alreadySorted);
  22956. }
  22957. /*!
  22958. Sets which representation style shall be used to display the OHLC data.
  22959. */
  22960. void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style)
  22961. {
  22962. mChartStyle = style;
  22963. }
  22964. /*!
  22965. Sets the width of the individual bars/candlesticks to \a width in plot key coordinates.
  22966. A typical choice is to set it to (or slightly less than) one bin interval width.
  22967. */
  22968. void QCPFinancial::setWidth(double width)
  22969. {
  22970. mWidth = width;
  22971. }
  22972. /*!
  22973. Sets how the width of the financial bars is defined. See the documentation of \ref WidthType for
  22974. an explanation of the possible values for \a widthType.
  22975. The default value is \ref wtPlotCoords.
  22976. \see setWidth
  22977. */
  22978. void QCPFinancial::setWidthType(QCPFinancial::WidthType widthType)
  22979. {
  22980. mWidthType = widthType;
  22981. }
  22982. /*!
  22983. Sets whether this chart shall contrast positive from negative trends per data point by using two
  22984. separate colors to draw the respective bars/candlesticks.
  22985. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  22986. setBrush).
  22987. \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative
  22988. */
  22989. void QCPFinancial::setTwoColored(bool twoColored)
  22990. {
  22991. mTwoColored = twoColored;
  22992. }
  22993. /*!
  22994. If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
  22995. of data points with a positive trend (i.e. bars/candlesticks with close >= open).
  22996. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  22997. setBrush).
  22998. \see setBrushNegative, setPenPositive, setPenNegative
  22999. */
  23000. void QCPFinancial::setBrushPositive(const QBrush &brush)
  23001. {
  23002. mBrushPositive = brush;
  23003. }
  23004. /*!
  23005. If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
  23006. of data points with a negative trend (i.e. bars/candlesticks with close < open).
  23007. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23008. setBrush).
  23009. \see setBrushPositive, setPenNegative, setPenPositive
  23010. */
  23011. void QCPFinancial::setBrushNegative(const QBrush &brush)
  23012. {
  23013. mBrushNegative = brush;
  23014. }
  23015. /*!
  23016. If \ref setTwoColored is set to true, this function controls the pen that is used to draw
  23017. outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open).
  23018. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23019. setBrush).
  23020. \see setPenNegative, setBrushPositive, setBrushNegative
  23021. */
  23022. void QCPFinancial::setPenPositive(const QPen &pen)
  23023. {
  23024. mPenPositive = pen;
  23025. }
  23026. /*!
  23027. If \ref setTwoColored is set to true, this function controls the pen that is used to draw
  23028. outlines of data points with a negative trend (i.e. bars/candlesticks with close < open).
  23029. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23030. setBrush).
  23031. \see setPenPositive, setBrushNegative, setBrushPositive
  23032. */
  23033. void QCPFinancial::setPenNegative(const QPen &pen)
  23034. {
  23035. mPenNegative = pen;
  23036. }
  23037. /*! \overload
  23038. Adds the provided points in \a keys, \a open, \a high, \a low and \a close to the current data.
  23039. The provided vectors should have equal length. Else, the number of added points will be the size
  23040. of the smallest vector.
  23041. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  23042. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  23043. Alternatively, you can also access and modify the data directly via the \ref data method, which
  23044. returns a pointer to the internal data container.
  23045. \see timeSeriesToOhlc
  23046. */
  23047. void QCPFinancial::addData(const QVector<double> &keys, const QVector<double> &open, const QVector<double> &high, const QVector<double> &low, const QVector<double> &close, bool alreadySorted)
  23048. {
  23049. if (keys.size() != open.size() || open.size() != high.size() || high.size() != low.size() || low.size() != close.size() || close.size() != keys.size())
  23050. qDebug() << Q_FUNC_INFO << "keys, open, high, low, close have different sizes:" << keys.size() << open.size() << high.size() << low.size() << close.size();
  23051. const int n = qMin(keys.size(), qMin(open.size(), qMin(high.size(), qMin(low.size(), close.size()))));
  23052. QVector<QCPFinancialData> tempData(n);
  23053. QVector<QCPFinancialData>::iterator it = tempData.begin();
  23054. const QVector<QCPFinancialData>::iterator itEnd = tempData.end();
  23055. int i = 0;
  23056. while (it != itEnd)
  23057. {
  23058. it->key = keys[i];
  23059. it->open = open[i];
  23060. it->high = high[i];
  23061. it->low = low[i];
  23062. it->close = close[i];
  23063. ++it;
  23064. ++i;
  23065. }
  23066. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  23067. }
  23068. /*! \overload
  23069. Adds the provided data point as \a key, \a open, \a high, \a low and \a close to the current
  23070. data.
  23071. Alternatively, you can also access and modify the data directly via the \ref data method, which
  23072. returns a pointer to the internal data container.
  23073. \see timeSeriesToOhlc
  23074. */
  23075. void QCPFinancial::addData(double key, double open, double high, double low, double close)
  23076. {
  23077. mDataContainer->add(QCPFinancialData(key, open, high, low, close));
  23078. }
  23079. /*!
  23080. \copydoc QCPPlottableInterface1D::selectTestRect
  23081. */
  23082. QCPDataSelection QCPFinancial::selectTestRect(const QRectF &rect, bool onlySelectable) const
  23083. {
  23084. QCPDataSelection result;
  23085. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23086. return result;
  23087. if (!mKeyAxis || !mValueAxis)
  23088. return result;
  23089. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  23090. getVisibleDataBounds(visibleBegin, visibleEnd);
  23091. for (QCPFinancialDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  23092. {
  23093. if (rect.intersects(selectionHitBox(it)))
  23094. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  23095. }
  23096. result.simplify();
  23097. return result;
  23098. }
  23099. /*!
  23100. Implements a selectTest specific to this plottable's point geometry.
  23101. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  23102. point to \a pos.
  23103. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  23104. */
  23105. double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  23106. {
  23107. Q_UNUSED(details)
  23108. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23109. return -1;
  23110. if (!mKeyAxis || !mValueAxis)
  23111. return -1;
  23112. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  23113. {
  23114. // get visible data range:
  23115. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  23116. QCPFinancialDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  23117. getVisibleDataBounds(visibleBegin, visibleEnd);
  23118. // perform select test according to configured style:
  23119. double result = -1;
  23120. switch (mChartStyle)
  23121. {
  23122. case QCPFinancial::csOhlc:
  23123. result = ohlcSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
  23124. case QCPFinancial::csCandlestick:
  23125. result = candlestickSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
  23126. }
  23127. if (details)
  23128. {
  23129. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  23130. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  23131. }
  23132. return result;
  23133. }
  23134. return -1;
  23135. }
  23136. /* inherits documentation from base class */
  23137. QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  23138. {
  23139. QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
  23140. // determine exact range by including width of bars/flags:
  23141. if (foundRange)
  23142. {
  23143. if (inSignDomain != QCP::sdPositive || range.lower-mWidth*0.5 > 0)
  23144. range.lower -= mWidth*0.5;
  23145. if (inSignDomain != QCP::sdNegative || range.upper+mWidth*0.5 < 0)
  23146. range.upper += mWidth*0.5;
  23147. }
  23148. return range;
  23149. }
  23150. /* inherits documentation from base class */
  23151. QCPRange QCPFinancial::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  23152. {
  23153. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  23154. }
  23155. /*!
  23156. A convenience function that converts time series data (\a value against \a time) to OHLC binned
  23157. data points. The return value can then be passed on to \ref QCPFinancialDataContainer::set(const
  23158. QCPFinancialDataContainer&).
  23159. The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given.
  23160. For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour
  23161. each, set \a timeBinSize to 3600.
  23162. \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The
  23163. value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys.
  23164. It merely defines the mathematical offset/phase of the bins that will be used to process the
  23165. data.
  23166. */
  23167. QCPFinancialDataContainer QCPFinancial::timeSeriesToOhlc(const QVector<double> &time, const QVector<double> &value, double timeBinSize, double timeBinOffset)
  23168. {
  23169. QCPFinancialDataContainer data;
  23170. int count = qMin(time.size(), value.size());
  23171. if (count == 0)
  23172. return QCPFinancialDataContainer();
  23173. QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first());
  23174. int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5);
  23175. for (int i=0; i<count; ++i)
  23176. {
  23177. int index = qFloor((time.at(i)-timeBinOffset)/timeBinSize+0.5);
  23178. if (currentBinIndex == index) // data point still in current bin, extend high/low:
  23179. {
  23180. if (value.at(i) < currentBinData.low) currentBinData.low = value.at(i);
  23181. if (value.at(i) > currentBinData.high) currentBinData.high = value.at(i);
  23182. if (i == count-1) // last data point is in current bin, finalize bin:
  23183. {
  23184. currentBinData.close = value.at(i);
  23185. currentBinData.key = timeBinOffset+(index)*timeBinSize;
  23186. data.add(currentBinData);
  23187. }
  23188. } else // data point not anymore in current bin, set close of old and open of new bin, and add old to map:
  23189. {
  23190. // finalize current bin:
  23191. currentBinData.close = value.at(i-1);
  23192. currentBinData.key = timeBinOffset+(index-1)*timeBinSize;
  23193. data.add(currentBinData);
  23194. // start next bin:
  23195. currentBinIndex = index;
  23196. currentBinData.open = value.at(i);
  23197. currentBinData.high = value.at(i);
  23198. currentBinData.low = value.at(i);
  23199. }
  23200. }
  23201. return data;
  23202. }
  23203. /* inherits documentation from base class */
  23204. void QCPFinancial::draw(QCPPainter *painter)
  23205. {
  23206. // get visible data range:
  23207. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  23208. getVisibleDataBounds(visibleBegin, visibleEnd);
  23209. // loop over and draw segments of unselected/selected data:
  23210. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  23211. getDataSegments(selectedSegments, unselectedSegments);
  23212. allSegments << unselectedSegments << selectedSegments;
  23213. for (int i=0; i<allSegments.size(); ++i)
  23214. {
  23215. bool isSelectedSegment = i >= unselectedSegments.size();
  23216. QCPFinancialDataContainer::const_iterator begin = visibleBegin;
  23217. QCPFinancialDataContainer::const_iterator end = visibleEnd;
  23218. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  23219. if (begin == end)
  23220. continue;
  23221. // draw data segment according to configured style:
  23222. switch (mChartStyle)
  23223. {
  23224. case QCPFinancial::csOhlc:
  23225. drawOhlcPlot(painter, begin, end, isSelectedSegment); break;
  23226. case QCPFinancial::csCandlestick:
  23227. drawCandlestickPlot(painter, begin, end, isSelectedSegment); break;
  23228. }
  23229. }
  23230. // draw other selection decoration that isn't just line/scatter pens and brushes:
  23231. if (mSelectionDecorator)
  23232. mSelectionDecorator->drawDecoration(painter, selection());
  23233. }
  23234. /* inherits documentation from base class */
  23235. void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  23236. {
  23237. painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing
  23238. if (mChartStyle == csOhlc)
  23239. {
  23240. if (mTwoColored)
  23241. {
  23242. // draw upper left half icon with positive color:
  23243. painter->setBrush(mBrushPositive);
  23244. painter->setPen(mPenPositive);
  23245. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
  23246. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23247. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  23248. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  23249. // draw bottom right half icon with negative color:
  23250. painter->setBrush(mBrushNegative);
  23251. painter->setPen(mPenNegative);
  23252. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
  23253. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23254. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  23255. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  23256. } else
  23257. {
  23258. painter->setBrush(mBrush);
  23259. painter->setPen(mPen);
  23260. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23261. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  23262. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  23263. }
  23264. } else if (mChartStyle == csCandlestick)
  23265. {
  23266. if (mTwoColored)
  23267. {
  23268. // draw upper left half icon with positive color:
  23269. painter->setBrush(mBrushPositive);
  23270. painter->setPen(mPenPositive);
  23271. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
  23272. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  23273. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23274. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  23275. // draw bottom right half icon with negative color:
  23276. painter->setBrush(mBrushNegative);
  23277. painter->setPen(mPenNegative);
  23278. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
  23279. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  23280. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23281. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  23282. } else
  23283. {
  23284. painter->setBrush(mBrush);
  23285. painter->setPen(mPen);
  23286. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  23287. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23288. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  23289. }
  23290. }
  23291. }
  23292. /*! \internal
  23293. Draws the data from \a begin to \a end-1 as OHLC bars with the provided \a painter.
  23294. This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc.
  23295. */
  23296. void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
  23297. {
  23298. QCPAxis *keyAxis = mKeyAxis.data();
  23299. QCPAxis *valueAxis = mValueAxis.data();
  23300. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  23301. if (keyAxis->orientation() == Qt::Horizontal)
  23302. {
  23303. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23304. {
  23305. if (isSelected && mSelectionDecorator)
  23306. mSelectionDecorator->applyPen(painter);
  23307. else if (mTwoColored)
  23308. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23309. else
  23310. painter->setPen(mPen);
  23311. double keyPixel = keyAxis->coordToPixel(it->key);
  23312. double openPixel = valueAxis->coordToPixel(it->open);
  23313. double closePixel = valueAxis->coordToPixel(it->close);
  23314. // draw backbone:
  23315. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(it->low)));
  23316. // draw open:
  23317. double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
  23318. painter->drawLine(QPointF(keyPixel-pixelWidth, openPixel), QPointF(keyPixel, openPixel));
  23319. // draw close:
  23320. painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+pixelWidth, closePixel));
  23321. }
  23322. } else
  23323. {
  23324. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23325. {
  23326. if (isSelected && mSelectionDecorator)
  23327. mSelectionDecorator->applyPen(painter);
  23328. else if (mTwoColored)
  23329. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23330. else
  23331. painter->setPen(mPen);
  23332. double keyPixel = keyAxis->coordToPixel(it->key);
  23333. double openPixel = valueAxis->coordToPixel(it->open);
  23334. double closePixel = valueAxis->coordToPixel(it->close);
  23335. // draw backbone:
  23336. painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(it->low), keyPixel));
  23337. // draw open:
  23338. double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
  23339. painter->drawLine(QPointF(openPixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel));
  23340. // draw close:
  23341. painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+pixelWidth));
  23342. }
  23343. }
  23344. }
  23345. /*! \internal
  23346. Draws the data from \a begin to \a end-1 as Candlesticks with the provided \a painter.
  23347. This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick.
  23348. */
  23349. void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
  23350. {
  23351. QCPAxis *keyAxis = mKeyAxis.data();
  23352. QCPAxis *valueAxis = mValueAxis.data();
  23353. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  23354. if (keyAxis->orientation() == Qt::Horizontal)
  23355. {
  23356. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23357. {
  23358. if (isSelected && mSelectionDecorator)
  23359. {
  23360. mSelectionDecorator->applyPen(painter);
  23361. mSelectionDecorator->applyBrush(painter);
  23362. } else if (mTwoColored)
  23363. {
  23364. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23365. painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
  23366. } else
  23367. {
  23368. painter->setPen(mPen);
  23369. painter->setBrush(mBrush);
  23370. }
  23371. double keyPixel = keyAxis->coordToPixel(it->key);
  23372. double openPixel = valueAxis->coordToPixel(it->open);
  23373. double closePixel = valueAxis->coordToPixel(it->close);
  23374. // draw high:
  23375. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
  23376. // draw low:
  23377. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
  23378. // draw open-close box:
  23379. double pixelWidth = getPixelWidth(it->key, keyPixel);
  23380. painter->drawRect(QRectF(QPointF(keyPixel-pixelWidth, closePixel), QPointF(keyPixel+pixelWidth, openPixel)));
  23381. }
  23382. } else // keyAxis->orientation() == Qt::Vertical
  23383. {
  23384. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23385. {
  23386. if (isSelected && mSelectionDecorator)
  23387. {
  23388. mSelectionDecorator->applyPen(painter);
  23389. mSelectionDecorator->applyBrush(painter);
  23390. } else if (mTwoColored)
  23391. {
  23392. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23393. painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
  23394. } else
  23395. {
  23396. painter->setPen(mPen);
  23397. painter->setBrush(mBrush);
  23398. }
  23399. double keyPixel = keyAxis->coordToPixel(it->key);
  23400. double openPixel = valueAxis->coordToPixel(it->open);
  23401. double closePixel = valueAxis->coordToPixel(it->close);
  23402. // draw high:
  23403. painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
  23404. // draw low:
  23405. painter->drawLine(QPointF(valueAxis->coordToPixel(it->low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
  23406. // draw open-close box:
  23407. double pixelWidth = getPixelWidth(it->key, keyPixel);
  23408. painter->drawRect(QRectF(QPointF(closePixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel+pixelWidth)));
  23409. }
  23410. }
  23411. }
  23412. /*! \internal
  23413. This function is used to determine the width of the bar at coordinate \a key, according to the
  23414. specified width (\ref setWidth) and width type (\ref setWidthType). Provide the pixel position of
  23415. \a key in \a keyPixel (because usually this was already calculated via \ref QCPAxis::coordToPixel
  23416. when this function is called).
  23417. It returns the number of pixels the bar extends to higher keys, relative to the \a key
  23418. coordinate. So with a non-reversed horizontal axis, the return value is positive. With a reversed
  23419. horizontal axis, the return value is negative. This is important so the open/close flags on the
  23420. \ref csOhlc bar are drawn to the correct side.
  23421. */
  23422. double QCPFinancial::getPixelWidth(double key, double keyPixel) const
  23423. {
  23424. double result = 0;
  23425. switch (mWidthType)
  23426. {
  23427. case wtAbsolute:
  23428. {
  23429. if (mKeyAxis)
  23430. result = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  23431. break;
  23432. }
  23433. case wtAxisRectRatio:
  23434. {
  23435. if (mKeyAxis && mKeyAxis.data()->axisRect())
  23436. {
  23437. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  23438. result = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  23439. else
  23440. result = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  23441. } else
  23442. qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
  23443. break;
  23444. }
  23445. case wtPlotCoords:
  23446. {
  23447. if (mKeyAxis)
  23448. result = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
  23449. else
  23450. qDebug() << Q_FUNC_INFO << "No key axis defined";
  23451. break;
  23452. }
  23453. }
  23454. return result;
  23455. }
  23456. /*! \internal
  23457. This method is a helper function for \ref selectTest. It is used to test for selection when the
  23458. chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end.
  23459. Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
  23460. representation of the plottable, and \a closestDataPoint will point to the respective data point.
  23461. */
  23462. double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
  23463. {
  23464. closestDataPoint = mDataContainer->constEnd();
  23465. QCPAxis *keyAxis = mKeyAxis.data();
  23466. QCPAxis *valueAxis = mValueAxis.data();
  23467. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  23468. double minDistSqr = (std::numeric_limits<double>::max)();
  23469. if (keyAxis->orientation() == Qt::Horizontal)
  23470. {
  23471. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23472. {
  23473. double keyPixel = keyAxis->coordToPixel(it->key);
  23474. // calculate distance to backbone:
  23475. double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)));
  23476. if (currentDistSqr < minDistSqr)
  23477. {
  23478. minDistSqr = currentDistSqr;
  23479. closestDataPoint = it;
  23480. }
  23481. }
  23482. } else // keyAxis->orientation() == Qt::Vertical
  23483. {
  23484. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23485. {
  23486. double keyPixel = keyAxis->coordToPixel(it->key);
  23487. // calculate distance to backbone:
  23488. double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel));
  23489. if (currentDistSqr < minDistSqr)
  23490. {
  23491. minDistSqr = currentDistSqr;
  23492. closestDataPoint = it;
  23493. }
  23494. }
  23495. }
  23496. return qSqrt(minDistSqr);
  23497. }
  23498. /*! \internal
  23499. This method is a helper function for \ref selectTest. It is used to test for selection when the
  23500. chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a
  23501. end.
  23502. Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
  23503. representation of the plottable, and \a closestDataPoint will point to the respective data point.
  23504. */
  23505. double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
  23506. {
  23507. closestDataPoint = mDataContainer->constEnd();
  23508. QCPAxis *keyAxis = mKeyAxis.data();
  23509. QCPAxis *valueAxis = mValueAxis.data();
  23510. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  23511. double minDistSqr = (std::numeric_limits<double>::max)();
  23512. if (keyAxis->orientation() == Qt::Horizontal)
  23513. {
  23514. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23515. {
  23516. double currentDistSqr;
  23517. // determine whether pos is in open-close-box:
  23518. QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
  23519. QCPRange boxValueRange(it->close, it->open);
  23520. double posKey, posValue;
  23521. pixelsToCoords(pos, posKey, posValue);
  23522. if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
  23523. {
  23524. currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  23525. } else
  23526. {
  23527. // calculate distance to high/low lines:
  23528. double keyPixel = keyAxis->coordToPixel(it->key);
  23529. double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
  23530. double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
  23531. currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
  23532. }
  23533. if (currentDistSqr < minDistSqr)
  23534. {
  23535. minDistSqr = currentDistSqr;
  23536. closestDataPoint = it;
  23537. }
  23538. }
  23539. } else // keyAxis->orientation() == Qt::Vertical
  23540. {
  23541. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23542. {
  23543. double currentDistSqr;
  23544. // determine whether pos is in open-close-box:
  23545. QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
  23546. QCPRange boxValueRange(it->close, it->open);
  23547. double posKey, posValue;
  23548. pixelsToCoords(pos, posKey, posValue);
  23549. if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
  23550. {
  23551. currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  23552. } else
  23553. {
  23554. // calculate distance to high/low lines:
  23555. double keyPixel = keyAxis->coordToPixel(it->key);
  23556. double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
  23557. double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
  23558. currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
  23559. }
  23560. if (currentDistSqr < minDistSqr)
  23561. {
  23562. minDistSqr = currentDistSqr;
  23563. closestDataPoint = it;
  23564. }
  23565. }
  23566. }
  23567. return qSqrt(minDistSqr);
  23568. }
  23569. /*! \internal
  23570. called by the drawing methods to determine which data (key) range is visible at the current key
  23571. axis range setting, so only that needs to be processed.
  23572. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  23573. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  23574. begin may still be just outside the visible range.
  23575. \a end returns the iterator just above the highest data point that needs to be taken into
  23576. account. Same as before, \a end may also lie just outside of the visible range
  23577. if the plottable contains no data, both \a begin and \a end point to \c constEnd.
  23578. */
  23579. void QCPFinancial::getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const
  23580. {
  23581. if (!mKeyAxis)
  23582. {
  23583. qDebug() << Q_FUNC_INFO << "invalid key axis";
  23584. begin = mDataContainer->constEnd();
  23585. end = mDataContainer->constEnd();
  23586. return;
  23587. }
  23588. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of ohlc/candlestick to include partially visible data points
  23589. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of ohlc/candlestick to include partially visible data points
  23590. }
  23591. /*! \internal
  23592. Returns the hit box in pixel coordinates that will be used for data selection with the selection
  23593. rect (\ref selectTestRect), of the data point given by \a it.
  23594. */
  23595. QRectF QCPFinancial::selectionHitBox(QCPFinancialDataContainer::const_iterator it) const
  23596. {
  23597. QCPAxis *keyAxis = mKeyAxis.data();
  23598. QCPAxis *valueAxis = mValueAxis.data();
  23599. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  23600. double keyPixel = keyAxis->coordToPixel(it->key);
  23601. double highPixel = valueAxis->coordToPixel(it->high);
  23602. double lowPixel = valueAxis->coordToPixel(it->low);
  23603. double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it->key-mWidth*0.5);
  23604. if (keyAxis->orientation() == Qt::Horizontal)
  23605. return QRectF(keyPixel-keyWidthPixels, highPixel, keyWidthPixels*2, lowPixel-highPixel).normalized();
  23606. else
  23607. return QRectF(highPixel, keyPixel-keyWidthPixels, lowPixel-highPixel, keyWidthPixels*2).normalized();
  23608. }
  23609. /* end of 'src/plottables/plottable-financial.cpp' */
  23610. /* including file 'src/plottables/plottable-errorbar.cpp' */
  23611. /* modified 2021-03-29T02:30:44, size 37679 */
  23612. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23613. //////////////////// QCPErrorBarsData
  23614. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23615. /*! \class QCPErrorBarsData
  23616. \brief Holds the data of one single error bar for QCPErrorBars.
  23617. The stored data is:
  23618. \li \a errorMinus: how much the error bar extends towards negative coordinates from the data
  23619. point position
  23620. \li \a errorPlus: how much the error bar extends towards positive coordinates from the data point
  23621. position
  23622. The container for storing the error bar information is \ref QCPErrorBarsDataContainer. It is a
  23623. typedef for <tt>QVector<\ref QCPErrorBarsData></tt>.
  23624. \see QCPErrorBarsDataContainer
  23625. */
  23626. /*!
  23627. Constructs an error bar with errors set to zero.
  23628. */
  23629. QCPErrorBarsData::QCPErrorBarsData() :
  23630. errorMinus(0),
  23631. errorPlus(0)
  23632. {
  23633. }
  23634. /*!
  23635. Constructs an error bar with equal \a error in both negative and positive direction.
  23636. */
  23637. QCPErrorBarsData::QCPErrorBarsData(double error) :
  23638. errorMinus(error),
  23639. errorPlus(error)
  23640. {
  23641. }
  23642. /*!
  23643. Constructs an error bar with negative and positive errors set to \a errorMinus and \a errorPlus,
  23644. respectively.
  23645. */
  23646. QCPErrorBarsData::QCPErrorBarsData(double errorMinus, double errorPlus) :
  23647. errorMinus(errorMinus),
  23648. errorPlus(errorPlus)
  23649. {
  23650. }
  23651. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23652. //////////////////// QCPErrorBars
  23653. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23654. /*! \class QCPErrorBars
  23655. \brief A plottable that adds a set of error bars to other plottables.
  23656. \image html QCPErrorBars.png
  23657. The \ref QCPErrorBars plottable can be attached to other one-dimensional plottables (e.g. \ref
  23658. QCPGraph, \ref QCPCurve, \ref QCPBars, etc.) and equips them with error bars.
  23659. Use \ref setDataPlottable to define for which plottable the \ref QCPErrorBars shall display the
  23660. error bars. The orientation of the error bars can be controlled with \ref setErrorType.
  23661. By using \ref setData, you can supply the actual error data, either as symmetric error or
  23662. plus/minus asymmetric errors. \ref QCPErrorBars only stores the error data. The absolute
  23663. key/value position of each error bar will be adopted from the configured data plottable. The
  23664. error data of the \ref QCPErrorBars are associated one-to-one via their index to the data points
  23665. of the data plottable. You can directly access and manipulate the error bar data via \ref data.
  23666. Set either of the plus/minus errors to NaN (<tt>qQNaN()</tt> or
  23667. <tt>std::numeric_limits<double>::quiet_NaN()</tt>) to not show the respective error bar on the data point at
  23668. that index.
  23669. \section qcperrorbars-appearance Changing the appearance
  23670. The appearance of the error bars is defined by the pen (\ref setPen), and the width of the
  23671. whiskers (\ref setWhiskerWidth). Further, the error bar backbones may leave a gap around the data
  23672. point center to prevent that error bars are drawn too close to or even through scatter points.
  23673. This gap size can be controlled via \ref setSymbolGap.
  23674. */
  23675. /* start of documentation of inline functions */
  23676. /*! \fn QSharedPointer<QCPErrorBarsDataContainer> QCPErrorBars::data() const
  23677. Returns a shared pointer to the internal data storage of type \ref QCPErrorBarsDataContainer. You
  23678. may use it to directly manipulate the error values, which may be more convenient and faster than
  23679. using the regular \ref setData methods.
  23680. */
  23681. /* end of documentation of inline functions */
  23682. /*!
  23683. Constructs an error bars plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  23684. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  23685. the same orientation. If either of these restrictions is violated, a corresponding message is
  23686. printed to the debug output (qDebug), the construction is not aborted, though.
  23687. It is also important that the \a keyAxis and \a valueAxis are the same for the error bars
  23688. plottable and the data plottable that the error bars shall be drawn on (\ref setDataPlottable).
  23689. The created \ref QCPErrorBars is automatically registered with the QCustomPlot instance inferred
  23690. from \a keyAxis. This QCustomPlot instance takes ownership of the \ref QCPErrorBars, so do not
  23691. delete it manually but use \ref QCustomPlot::removePlottable() instead.
  23692. */
  23693. QCPErrorBars::QCPErrorBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  23694. QCPAbstractPlottable(keyAxis, valueAxis),
  23695. mDataContainer(new QVector<QCPErrorBarsData>),
  23696. mErrorType(etValueError),
  23697. mWhiskerWidth(9),
  23698. mSymbolGap(10)
  23699. {
  23700. setPen(QPen(Qt::black, 0));
  23701. setBrush(Qt::NoBrush);
  23702. }
  23703. QCPErrorBars::~QCPErrorBars()
  23704. {
  23705. }
  23706. /*! \overload
  23707. Replaces the current data container with the provided \a data container.
  23708. Since a QSharedPointer is used, multiple \ref QCPErrorBars instances may share the same data
  23709. container safely. Modifying the data in the container will then affect all \ref QCPErrorBars
  23710. instances that share the container. Sharing can be achieved by simply exchanging the data
  23711. containers wrapped in shared pointers:
  23712. \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-1
  23713. If you do not wish to share containers, but create a copy from an existing container, assign the
  23714. data containers directly:
  23715. \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-2
  23716. (This uses different notation compared with other plottables, because the \ref QCPErrorBars
  23717. uses a \c QVector<QCPErrorBarsData> as its data container, instead of a \ref QCPDataContainer.)
  23718. \see addData
  23719. */
  23720. void QCPErrorBars::setData(QSharedPointer<QCPErrorBarsDataContainer> data)
  23721. {
  23722. mDataContainer = data;
  23723. }
  23724. /*! \overload
  23725. Sets symmetrical error values as specified in \a error. The errors will be associated one-to-one
  23726. by the data point index to the associated data plottable (\ref setDataPlottable).
  23727. You can directly access and manipulate the error bar data via \ref data.
  23728. \see addData
  23729. */
  23730. void QCPErrorBars::setData(const QVector<double> &error)
  23731. {
  23732. mDataContainer->clear();
  23733. addData(error);
  23734. }
  23735. /*! \overload
  23736. Sets asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
  23737. associated one-to-one by the data point index to the associated data plottable (\ref
  23738. setDataPlottable).
  23739. You can directly access and manipulate the error bar data via \ref data.
  23740. \see addData
  23741. */
  23742. void QCPErrorBars::setData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
  23743. {
  23744. mDataContainer->clear();
  23745. addData(errorMinus, errorPlus);
  23746. }
  23747. /*!
  23748. Sets the data plottable to which the error bars will be applied. The error values specified e.g.
  23749. via \ref setData will be associated one-to-one by the data point index to the data points of \a
  23750. plottable. This means that the error bars will adopt the key/value coordinates of the data point
  23751. with the same index.
  23752. The passed \a plottable must be a one-dimensional plottable, i.e. it must implement the \ref
  23753. QCPPlottableInterface1D. Further, it must not be a \ref QCPErrorBars instance itself. If either
  23754. of these restrictions is violated, a corresponding qDebug output is generated, and the data
  23755. plottable of this \ref QCPErrorBars instance is set to zero.
  23756. For proper display, care must also be taken that the key and value axes of the \a plottable match
  23757. those configured for this \ref QCPErrorBars instance.
  23758. */
  23759. void QCPErrorBars::setDataPlottable(QCPAbstractPlottable *plottable)
  23760. {
  23761. if (plottable && qobject_cast<QCPErrorBars*>(plottable))
  23762. {
  23763. mDataPlottable = nullptr;
  23764. qDebug() << Q_FUNC_INFO << "can't set another QCPErrorBars instance as data plottable";
  23765. return;
  23766. }
  23767. if (plottable && !plottable->interface1D())
  23768. {
  23769. mDataPlottable = nullptr;
  23770. qDebug() << Q_FUNC_INFO << "passed plottable doesn't implement 1d interface, can't associate with QCPErrorBars";
  23771. return;
  23772. }
  23773. mDataPlottable = plottable;
  23774. }
  23775. /*!
  23776. Sets in which orientation the error bars shall appear on the data points. If your data needs both
  23777. error dimensions, create two \ref QCPErrorBars with different \a type.
  23778. */
  23779. void QCPErrorBars::setErrorType(ErrorType type)
  23780. {
  23781. mErrorType = type;
  23782. }
  23783. /*!
  23784. Sets the width of the whiskers (the short bars at the end of the actual error bar backbones) to
  23785. \a pixels.
  23786. */
  23787. void QCPErrorBars::setWhiskerWidth(double pixels)
  23788. {
  23789. mWhiskerWidth = pixels;
  23790. }
  23791. /*!
  23792. Sets the gap diameter around the data points that will be left out when drawing the error bar
  23793. backbones. This gap prevents that error bars are drawn too close to or even through scatter
  23794. points.
  23795. */
  23796. void QCPErrorBars::setSymbolGap(double pixels)
  23797. {
  23798. mSymbolGap = pixels;
  23799. }
  23800. /*! \overload
  23801. Adds symmetrical error values as specified in \a error. The errors will be associated one-to-one
  23802. by the data point index to the associated data plottable (\ref setDataPlottable).
  23803. You can directly access and manipulate the error bar data via \ref data.
  23804. \see setData
  23805. */
  23806. void QCPErrorBars::addData(const QVector<double> &error)
  23807. {
  23808. addData(error, error);
  23809. }
  23810. /*! \overload
  23811. Adds asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
  23812. associated one-to-one by the data point index to the associated data plottable (\ref
  23813. setDataPlottable).
  23814. You can directly access and manipulate the error bar data via \ref data.
  23815. \see setData
  23816. */
  23817. void QCPErrorBars::addData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
  23818. {
  23819. if (errorMinus.size() != errorPlus.size())
  23820. qDebug() << Q_FUNC_INFO << "minus and plus error vectors have different sizes:" << errorMinus.size() << errorPlus.size();
  23821. const int n = qMin(errorMinus.size(), errorPlus.size());
  23822. mDataContainer->reserve(n);
  23823. for (int i=0; i<n; ++i)
  23824. mDataContainer->append(QCPErrorBarsData(errorMinus.at(i), errorPlus.at(i)));
  23825. }
  23826. /*! \overload
  23827. Adds a single symmetrical error bar as specified in \a error. The errors will be associated
  23828. one-to-one by the data point index to the associated data plottable (\ref setDataPlottable).
  23829. You can directly access and manipulate the error bar data via \ref data.
  23830. \see setData
  23831. */
  23832. void QCPErrorBars::addData(double error)
  23833. {
  23834. mDataContainer->append(QCPErrorBarsData(error));
  23835. }
  23836. /*! \overload
  23837. Adds a single asymmetrical error bar as specified in \a errorMinus and \a errorPlus. The errors
  23838. will be associated one-to-one by the data point index to the associated data plottable (\ref
  23839. setDataPlottable).
  23840. You can directly access and manipulate the error bar data via \ref data.
  23841. \see setData
  23842. */
  23843. void QCPErrorBars::addData(double errorMinus, double errorPlus)
  23844. {
  23845. mDataContainer->append(QCPErrorBarsData(errorMinus, errorPlus));
  23846. }
  23847. /* inherits documentation from base class */
  23848. int QCPErrorBars::dataCount() const
  23849. {
  23850. return mDataContainer->size();
  23851. }
  23852. /* inherits documentation from base class */
  23853. double QCPErrorBars::dataMainKey(int index) const
  23854. {
  23855. if (mDataPlottable)
  23856. return mDataPlottable->interface1D()->dataMainKey(index);
  23857. else
  23858. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23859. return 0;
  23860. }
  23861. /* inherits documentation from base class */
  23862. double QCPErrorBars::dataSortKey(int index) const
  23863. {
  23864. if (mDataPlottable)
  23865. return mDataPlottable->interface1D()->dataSortKey(index);
  23866. else
  23867. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23868. return 0;
  23869. }
  23870. /* inherits documentation from base class */
  23871. double QCPErrorBars::dataMainValue(int index) const
  23872. {
  23873. if (mDataPlottable)
  23874. return mDataPlottable->interface1D()->dataMainValue(index);
  23875. else
  23876. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23877. return 0;
  23878. }
  23879. /* inherits documentation from base class */
  23880. QCPRange QCPErrorBars::dataValueRange(int index) const
  23881. {
  23882. if (mDataPlottable)
  23883. {
  23884. const double value = mDataPlottable->interface1D()->dataMainValue(index);
  23885. if (index >= 0 && index < mDataContainer->size() && mErrorType == etValueError)
  23886. return {value-mDataContainer->at(index).errorMinus, value+mDataContainer->at(index).errorPlus};
  23887. else
  23888. return {value, value};
  23889. } else
  23890. {
  23891. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23892. return {};
  23893. }
  23894. }
  23895. /* inherits documentation from base class */
  23896. QPointF QCPErrorBars::dataPixelPosition(int index) const
  23897. {
  23898. if (mDataPlottable)
  23899. return mDataPlottable->interface1D()->dataPixelPosition(index);
  23900. else
  23901. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23902. return {};
  23903. }
  23904. /* inherits documentation from base class */
  23905. bool QCPErrorBars::sortKeyIsMainKey() const
  23906. {
  23907. if (mDataPlottable)
  23908. {
  23909. return mDataPlottable->interface1D()->sortKeyIsMainKey();
  23910. } else
  23911. {
  23912. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23913. return true;
  23914. }
  23915. }
  23916. /*!
  23917. \copydoc QCPPlottableInterface1D::selectTestRect
  23918. */
  23919. QCPDataSelection QCPErrorBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
  23920. {
  23921. QCPDataSelection result;
  23922. if (!mDataPlottable)
  23923. return result;
  23924. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23925. return result;
  23926. if (!mKeyAxis || !mValueAxis)
  23927. return result;
  23928. QCPErrorBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  23929. getVisibleDataBounds(visibleBegin, visibleEnd, QCPDataRange(0, dataCount()));
  23930. QVector<QLineF> backbones, whiskers;
  23931. for (QCPErrorBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  23932. {
  23933. backbones.clear();
  23934. whiskers.clear();
  23935. getErrorBarLines(it, backbones, whiskers);
  23936. foreach (const QLineF &backbone, backbones)
  23937. {
  23938. if (rectIntersectsLine(rect, backbone))
  23939. {
  23940. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  23941. break;
  23942. }
  23943. }
  23944. }
  23945. result.simplify();
  23946. return result;
  23947. }
  23948. /* inherits documentation from base class */
  23949. int QCPErrorBars::findBegin(double sortKey, bool expandedRange) const
  23950. {
  23951. if (mDataPlottable)
  23952. {
  23953. if (mDataContainer->isEmpty())
  23954. return 0;
  23955. int beginIndex = mDataPlottable->interface1D()->findBegin(sortKey, expandedRange);
  23956. if (beginIndex >= mDataContainer->size())
  23957. beginIndex = mDataContainer->size()-1;
  23958. return beginIndex;
  23959. } else
  23960. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23961. return 0;
  23962. }
  23963. /* inherits documentation from base class */
  23964. int QCPErrorBars::findEnd(double sortKey, bool expandedRange) const
  23965. {
  23966. if (mDataPlottable)
  23967. {
  23968. if (mDataContainer->isEmpty())
  23969. return 0;
  23970. int endIndex = mDataPlottable->interface1D()->findEnd(sortKey, expandedRange);
  23971. if (endIndex > mDataContainer->size())
  23972. endIndex = mDataContainer->size();
  23973. return endIndex;
  23974. } else
  23975. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23976. return 0;
  23977. }
  23978. /*!
  23979. Implements a selectTest specific to this plottable's point geometry.
  23980. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  23981. point to \a pos.
  23982. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  23983. */
  23984. double QCPErrorBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  23985. {
  23986. if (!mDataPlottable) return -1;
  23987. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23988. return -1;
  23989. if (!mKeyAxis || !mValueAxis)
  23990. return -1;
  23991. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  23992. {
  23993. QCPErrorBarsDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  23994. double result = pointDistance(pos, closestDataPoint);
  23995. if (details)
  23996. {
  23997. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  23998. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  23999. }
  24000. return result;
  24001. } else
  24002. return -1;
  24003. }
  24004. /* inherits documentation from base class */
  24005. void QCPErrorBars::draw(QCPPainter *painter)
  24006. {
  24007. if (!mDataPlottable) return;
  24008. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  24009. if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
  24010. // if the sort key isn't the main key, we must check the visibility for each data point/error bar individually
  24011. // (getVisibleDataBounds applies range restriction, but otherwise can only return full data range):
  24012. bool checkPointVisibility = !mDataPlottable->interface1D()->sortKeyIsMainKey();
  24013. // check data validity if flag set:
  24014. #ifdef QCUSTOMPLOT_CHECK_DATA
  24015. QCPErrorBarsDataContainer::const_iterator it;
  24016. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  24017. {
  24018. if (QCP::isInvalidData(it->errorMinus, it->errorPlus))
  24019. qDebug() << Q_FUNC_INFO << "Data point at index" << it-mDataContainer->constBegin() << "invalid." << "Plottable name:" << name();
  24020. }
  24021. #endif
  24022. applyDefaultAntialiasingHint(painter);
  24023. painter->setBrush(Qt::NoBrush);
  24024. // loop over and draw segments of unselected/selected data:
  24025. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  24026. getDataSegments(selectedSegments, unselectedSegments);
  24027. allSegments << unselectedSegments << selectedSegments;
  24028. QVector<QLineF> backbones, whiskers;
  24029. for (int i=0; i<allSegments.size(); ++i)
  24030. {
  24031. QCPErrorBarsDataContainer::const_iterator begin, end;
  24032. getVisibleDataBounds(begin, end, allSegments.at(i));
  24033. if (begin == end)
  24034. continue;
  24035. bool isSelectedSegment = i >= unselectedSegments.size();
  24036. if (isSelectedSegment && mSelectionDecorator)
  24037. mSelectionDecorator->applyPen(painter);
  24038. else
  24039. painter->setPen(mPen);
  24040. if (painter->pen().capStyle() == Qt::SquareCap)
  24041. {
  24042. QPen capFixPen(painter->pen());
  24043. capFixPen.setCapStyle(Qt::FlatCap);
  24044. painter->setPen(capFixPen);
  24045. }
  24046. backbones.clear();
  24047. whiskers.clear();
  24048. for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  24049. {
  24050. if (!checkPointVisibility || errorBarVisible(int(it-mDataContainer->constBegin())))
  24051. getErrorBarLines(it, backbones, whiskers);
  24052. }
  24053. painter->drawLines(backbones);
  24054. painter->drawLines(whiskers);
  24055. }
  24056. // draw other selection decoration that isn't just line/scatter pens and brushes:
  24057. if (mSelectionDecorator)
  24058. mSelectionDecorator->drawDecoration(painter, selection());
  24059. }
  24060. /* inherits documentation from base class */
  24061. void QCPErrorBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  24062. {
  24063. applyDefaultAntialiasingHint(painter);
  24064. painter->setPen(mPen);
  24065. if (mErrorType == etValueError && mValueAxis && mValueAxis->orientation() == Qt::Vertical)
  24066. {
  24067. painter->drawLine(QLineF(rect.center().x(), rect.top()+2, rect.center().x(), rect.bottom()-1));
  24068. painter->drawLine(QLineF(rect.center().x()-4, rect.top()+2, rect.center().x()+4, rect.top()+2));
  24069. painter->drawLine(QLineF(rect.center().x()-4, rect.bottom()-1, rect.center().x()+4, rect.bottom()-1));
  24070. } else
  24071. {
  24072. painter->drawLine(QLineF(rect.left()+2, rect.center().y(), rect.right()-2, rect.center().y()));
  24073. painter->drawLine(QLineF(rect.left()+2, rect.center().y()-4, rect.left()+2, rect.center().y()+4));
  24074. painter->drawLine(QLineF(rect.right()-2, rect.center().y()-4, rect.right()-2, rect.center().y()+4));
  24075. }
  24076. }
  24077. /* inherits documentation from base class */
  24078. QCPRange QCPErrorBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  24079. {
  24080. if (!mDataPlottable)
  24081. {
  24082. foundRange = false;
  24083. return {};
  24084. }
  24085. QCPRange range;
  24086. bool haveLower = false;
  24087. bool haveUpper = false;
  24088. QCPErrorBarsDataContainer::const_iterator it;
  24089. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  24090. {
  24091. if (mErrorType == etValueError)
  24092. {
  24093. // error bar doesn't extend in key dimension (except whisker but we ignore that here), so only use data point center
  24094. const double current = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
  24095. if (qIsNaN(current)) continue;
  24096. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24097. {
  24098. if (current < range.lower || !haveLower)
  24099. {
  24100. range.lower = current;
  24101. haveLower = true;
  24102. }
  24103. if (current > range.upper || !haveUpper)
  24104. {
  24105. range.upper = current;
  24106. haveUpper = true;
  24107. }
  24108. }
  24109. } else // mErrorType == etKeyError
  24110. {
  24111. const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
  24112. if (qIsNaN(dataKey)) continue;
  24113. // plus error:
  24114. double current = dataKey + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
  24115. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24116. {
  24117. if (current > range.upper || !haveUpper)
  24118. {
  24119. range.upper = current;
  24120. haveUpper = true;
  24121. }
  24122. }
  24123. // minus error:
  24124. current = dataKey - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
  24125. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24126. {
  24127. if (current < range.lower || !haveLower)
  24128. {
  24129. range.lower = current;
  24130. haveLower = true;
  24131. }
  24132. }
  24133. }
  24134. }
  24135. if (haveUpper && !haveLower)
  24136. {
  24137. range.lower = range.upper;
  24138. haveLower = true;
  24139. } else if (haveLower && !haveUpper)
  24140. {
  24141. range.upper = range.lower;
  24142. haveUpper = true;
  24143. }
  24144. foundRange = haveLower && haveUpper;
  24145. return range;
  24146. }
  24147. /* inherits documentation from base class */
  24148. QCPRange QCPErrorBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  24149. {
  24150. if (!mDataPlottable)
  24151. {
  24152. foundRange = false;
  24153. return {};
  24154. }
  24155. QCPRange range;
  24156. const bool restrictKeyRange = inKeyRange != QCPRange();
  24157. bool haveLower = false;
  24158. bool haveUpper = false;
  24159. QCPErrorBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  24160. QCPErrorBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  24161. if (mDataPlottable->interface1D()->sortKeyIsMainKey() && restrictKeyRange)
  24162. {
  24163. itBegin = mDataContainer->constBegin()+findBegin(inKeyRange.lower, false);
  24164. itEnd = mDataContainer->constBegin()+findEnd(inKeyRange.upper, false);
  24165. }
  24166. for (QCPErrorBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
  24167. {
  24168. if (restrictKeyRange)
  24169. {
  24170. const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
  24171. if (dataKey < inKeyRange.lower || dataKey > inKeyRange.upper)
  24172. continue;
  24173. }
  24174. if (mErrorType == etValueError)
  24175. {
  24176. const double dataValue = mDataPlottable->interface1D()->dataMainValue(int(it-mDataContainer->constBegin()));
  24177. if (qIsNaN(dataValue)) continue;
  24178. // plus error:
  24179. double current = dataValue + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
  24180. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24181. {
  24182. if (current > range.upper || !haveUpper)
  24183. {
  24184. range.upper = current;
  24185. haveUpper = true;
  24186. }
  24187. }
  24188. // minus error:
  24189. current = dataValue - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
  24190. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24191. {
  24192. if (current < range.lower || !haveLower)
  24193. {
  24194. range.lower = current;
  24195. haveLower = true;
  24196. }
  24197. }
  24198. } else // mErrorType == etKeyError
  24199. {
  24200. // error bar doesn't extend in value dimension (except whisker but we ignore that here), so only use data point center
  24201. const double current = mDataPlottable->interface1D()->dataMainValue(int(it-mDataContainer->constBegin()));
  24202. if (qIsNaN(current)) continue;
  24203. if (inSignDomain == QCP::sdBoth || (inSignDomain == QCP::sdNegative && current < 0) || (inSignDomain == QCP::sdPositive && current > 0))
  24204. {
  24205. if (current < range.lower || !haveLower)
  24206. {
  24207. range.lower = current;
  24208. haveLower = true;
  24209. }
  24210. if (current > range.upper || !haveUpper)
  24211. {
  24212. range.upper = current;
  24213. haveUpper = true;
  24214. }
  24215. }
  24216. }
  24217. }
  24218. if (haveUpper && !haveLower)
  24219. {
  24220. range.lower = range.upper;
  24221. haveLower = true;
  24222. } else if (haveLower && !haveUpper)
  24223. {
  24224. range.upper = range.lower;
  24225. haveUpper = true;
  24226. }
  24227. foundRange = haveLower && haveUpper;
  24228. return range;
  24229. }
  24230. /*! \internal
  24231. Calculates the lines that make up the error bar belonging to the data point \a it.
  24232. The resulting lines are added to \a backbones and \a whiskers. The vectors are not cleared, so
  24233. calling this method with different \a it but the same \a backbones and \a whiskers allows to
  24234. accumulate lines for multiple data points.
  24235. This method assumes that \a it is a valid iterator within the bounds of this \ref QCPErrorBars
  24236. instance and within the bounds of the associated data plottable.
  24237. */
  24238. void QCPErrorBars::getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it, QVector<QLineF> &backbones, QVector<QLineF> &whiskers) const
  24239. {
  24240. if (!mDataPlottable) return;
  24241. int index = int(it-mDataContainer->constBegin());
  24242. QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
  24243. if (qIsNaN(centerPixel.x()) || qIsNaN(centerPixel.y()))
  24244. return;
  24245. QCPAxis *errorAxis = mErrorType == etValueError ? mValueAxis.data() : mKeyAxis.data();
  24246. QCPAxis *orthoAxis = mErrorType == etValueError ? mKeyAxis.data() : mValueAxis.data();
  24247. const double centerErrorAxisPixel = errorAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  24248. const double centerOrthoAxisPixel = orthoAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  24249. const double centerErrorAxisCoord = errorAxis->pixelToCoord(centerErrorAxisPixel); // depending on plottable, this might be different from just mDataPlottable->interface1D()->dataMainKey/Value
  24250. const double symbolGap = mSymbolGap*0.5*errorAxis->pixelOrientation();
  24251. // plus error:
  24252. double errorStart, errorEnd;
  24253. if (!qIsNaN(it->errorPlus))
  24254. {
  24255. errorStart = centerErrorAxisPixel+symbolGap;
  24256. errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord+it->errorPlus);
  24257. if (errorAxis->orientation() == Qt::Vertical)
  24258. {
  24259. if ((errorStart > errorEnd) != errorAxis->rangeReversed())
  24260. backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
  24261. whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
  24262. } else
  24263. {
  24264. if ((errorStart < errorEnd) != errorAxis->rangeReversed())
  24265. backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
  24266. whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
  24267. }
  24268. }
  24269. // minus error:
  24270. if (!qIsNaN(it->errorMinus))
  24271. {
  24272. errorStart = centerErrorAxisPixel-symbolGap;
  24273. errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord-it->errorMinus);
  24274. if (errorAxis->orientation() == Qt::Vertical)
  24275. {
  24276. if ((errorStart < errorEnd) != errorAxis->rangeReversed())
  24277. backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
  24278. whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
  24279. } else
  24280. {
  24281. if ((errorStart > errorEnd) != errorAxis->rangeReversed())
  24282. backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
  24283. whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
  24284. }
  24285. }
  24286. }
  24287. /*! \internal
  24288. This method outputs the currently visible data range via \a begin and \a end. The returned range
  24289. will also never exceed \a rangeRestriction.
  24290. Since error bars with type \ref etKeyError may extend to arbitrarily positive and negative key
  24291. coordinates relative to their data point key, this method checks all outer error bars whether
  24292. they truly don't reach into the visible portion of the axis rect, by calling \ref
  24293. errorBarVisible. On the other hand error bars with type \ref etValueError that are associated
  24294. with data plottables whose sort key is equal to the main key (see \ref qcpdatacontainer-datatype
  24295. "QCPDataContainer DataType") can be handled very efficiently by finding the visible range of
  24296. error bars through binary search (\ref QCPPlottableInterface1D::findBegin and \ref
  24297. QCPPlottableInterface1D::findEnd).
  24298. If the plottable's sort key is not equal to the main key, this method returns the full data
  24299. range, only restricted by \a rangeRestriction. Drawing optimization then has to be done on a
  24300. point-by-point basis in the \ref draw method.
  24301. */
  24302. void QCPErrorBars::getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterator &begin, QCPErrorBarsDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
  24303. {
  24304. QCPAxis *keyAxis = mKeyAxis.data();
  24305. QCPAxis *valueAxis = mValueAxis.data();
  24306. if (!keyAxis || !valueAxis)
  24307. {
  24308. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  24309. end = mDataContainer->constEnd();
  24310. begin = end;
  24311. return;
  24312. }
  24313. if (!mDataPlottable || rangeRestriction.isEmpty())
  24314. {
  24315. end = mDataContainer->constEnd();
  24316. begin = end;
  24317. return;
  24318. }
  24319. if (!mDataPlottable->interface1D()->sortKeyIsMainKey())
  24320. {
  24321. // if the sort key isn't the main key, it's not possible to find a contiguous range of visible
  24322. // data points, so this method then only applies the range restriction and otherwise returns
  24323. // the full data range. Visibility checks must be done on a per-datapoin-basis during drawing
  24324. QCPDataRange dataRange(0, mDataContainer->size());
  24325. dataRange = dataRange.bounded(rangeRestriction);
  24326. begin = mDataContainer->constBegin()+dataRange.begin();
  24327. end = mDataContainer->constBegin()+dataRange.end();
  24328. return;
  24329. }
  24330. // get visible data range via interface from data plottable, and then restrict to available error data points:
  24331. const int n = qMin(mDataContainer->size(), mDataPlottable->interface1D()->dataCount());
  24332. int beginIndex = mDataPlottable->interface1D()->findBegin(keyAxis->range().lower);
  24333. int endIndex = mDataPlottable->interface1D()->findEnd(keyAxis->range().upper);
  24334. int i = beginIndex;
  24335. while (i > 0 && i < n && i > rangeRestriction.begin())
  24336. {
  24337. if (errorBarVisible(i))
  24338. beginIndex = i;
  24339. --i;
  24340. }
  24341. i = endIndex;
  24342. while (i >= 0 && i < n && i < rangeRestriction.end())
  24343. {
  24344. if (errorBarVisible(i))
  24345. endIndex = i+1;
  24346. ++i;
  24347. }
  24348. QCPDataRange dataRange(beginIndex, endIndex);
  24349. dataRange = dataRange.bounded(rangeRestriction.bounded(QCPDataRange(0, mDataContainer->size())));
  24350. begin = mDataContainer->constBegin()+dataRange.begin();
  24351. end = mDataContainer->constBegin()+dataRange.end();
  24352. }
  24353. /*! \internal
  24354. Calculates the minimum distance in pixels the error bars' representation has from the given \a
  24355. pixelPoint. This is used to determine whether the error bar was clicked or not, e.g. in \ref
  24356. selectTest. The closest data point to \a pixelPoint is returned in \a closestData.
  24357. */
  24358. double QCPErrorBars::pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const
  24359. {
  24360. closestData = mDataContainer->constEnd();
  24361. if (!mDataPlottable || mDataContainer->isEmpty())
  24362. return -1.0;
  24363. if (!mKeyAxis || !mValueAxis)
  24364. {
  24365. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  24366. return -1.0;
  24367. }
  24368. QCPErrorBarsDataContainer::const_iterator begin, end;
  24369. getVisibleDataBounds(begin, end, QCPDataRange(0, dataCount()));
  24370. // calculate minimum distances to error backbones (whiskers are ignored for speed) and find closestData iterator:
  24371. double minDistSqr = (std::numeric_limits<double>::max)();
  24372. QVector<QLineF> backbones, whiskers;
  24373. for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  24374. {
  24375. getErrorBarLines(it, backbones, whiskers);
  24376. foreach (const QLineF &backbone, backbones)
  24377. {
  24378. const double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(backbone);
  24379. if (currentDistSqr < minDistSqr)
  24380. {
  24381. minDistSqr = currentDistSqr;
  24382. closestData = it;
  24383. }
  24384. }
  24385. }
  24386. return qSqrt(minDistSqr);
  24387. }
  24388. /*! \internal
  24389. \note This method is identical to \ref QCPAbstractPlottable1D::getDataSegments but needs to be
  24390. reproduced here since the \ref QCPErrorBars plottable, as a special case that doesn't have its
  24391. own key/value data coordinates, doesn't derive from \ref QCPAbstractPlottable1D. See the
  24392. documentation there for details.
  24393. */
  24394. void QCPErrorBars::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
  24395. {
  24396. selectedSegments.clear();
  24397. unselectedSegments.clear();
  24398. if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
  24399. {
  24400. if (selected())
  24401. selectedSegments << QCPDataRange(0, dataCount());
  24402. else
  24403. unselectedSegments << QCPDataRange(0, dataCount());
  24404. } else
  24405. {
  24406. QCPDataSelection sel(selection());
  24407. sel.simplify();
  24408. selectedSegments = sel.dataRanges();
  24409. unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
  24410. }
  24411. }
  24412. /*! \internal
  24413. Returns whether the error bar at the specified \a index is visible within the current key axis
  24414. range.
  24415. This method assumes for performance reasons without checking that the key axis, the value axis,
  24416. and the data plottable (\ref setDataPlottable) are not \c nullptr and that \a index is within
  24417. valid bounds of this \ref QCPErrorBars instance and the bounds of the data plottable.
  24418. */
  24419. bool QCPErrorBars::errorBarVisible(int index) const
  24420. {
  24421. QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
  24422. const double centerKeyPixel = mKeyAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  24423. if (qIsNaN(centerKeyPixel))
  24424. return false;
  24425. double keyMin, keyMax;
  24426. if (mErrorType == etKeyError)
  24427. {
  24428. const double centerKey = mKeyAxis->pixelToCoord(centerKeyPixel);
  24429. const double errorPlus = mDataContainer->at(index).errorPlus;
  24430. const double errorMinus = mDataContainer->at(index).errorMinus;
  24431. keyMax = centerKey+(qIsNaN(errorPlus) ? 0 : errorPlus);
  24432. keyMin = centerKey-(qIsNaN(errorMinus) ? 0 : errorMinus);
  24433. } else // mErrorType == etValueError
  24434. {
  24435. keyMax = mKeyAxis->pixelToCoord(centerKeyPixel+mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
  24436. keyMin = mKeyAxis->pixelToCoord(centerKeyPixel-mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
  24437. }
  24438. return ((keyMax > mKeyAxis->range().lower) && (keyMin < mKeyAxis->range().upper));
  24439. }
  24440. /*! \internal
  24441. Returns whether \a line intersects (or is contained in) \a pixelRect.
  24442. \a line is assumed to be either perfectly horizontal or perfectly vertical, as is the case for
  24443. error bar lines.
  24444. */
  24445. bool QCPErrorBars::rectIntersectsLine(const QRectF &pixelRect, const QLineF &line) const
  24446. {
  24447. if (pixelRect.left() > line.x1() && pixelRect.left() > line.x2())
  24448. return false;
  24449. else if (pixelRect.right() < line.x1() && pixelRect.right() < line.x2())
  24450. return false;
  24451. else if (pixelRect.top() > line.y1() && pixelRect.top() > line.y2())
  24452. return false;
  24453. else if (pixelRect.bottom() < line.y1() && pixelRect.bottom() < line.y2())
  24454. return false;
  24455. else
  24456. return true;
  24457. }
  24458. /* end of 'src/plottables/plottable-errorbar.cpp' */
  24459. /* including file 'src/items/item-straightline.cpp' */
  24460. /* modified 2021-03-29T02:30:44, size 7596 */
  24461. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24462. //////////////////// QCPItemStraightLine
  24463. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24464. /*! \class QCPItemStraightLine
  24465. \brief A straight line that spans infinitely in both directions
  24466. \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions."
  24467. It has two positions, \a point1 and \a point2, which define the straight line.
  24468. */
  24469. /*!
  24470. Creates a straight line item and sets default values.
  24471. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24472. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24473. */
  24474. QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) :
  24475. QCPAbstractItem(parentPlot),
  24476. point1(createPosition(QLatin1String("point1"))),
  24477. point2(createPosition(QLatin1String("point2")))
  24478. {
  24479. point1->setCoords(0, 0);
  24480. point2->setCoords(1, 1);
  24481. setPen(QPen(Qt::black));
  24482. setSelectedPen(QPen(Qt::blue,2));
  24483. }
  24484. QCPItemStraightLine::~QCPItemStraightLine()
  24485. {
  24486. }
  24487. /*!
  24488. Sets the pen that will be used to draw the line
  24489. \see setSelectedPen
  24490. */
  24491. void QCPItemStraightLine::setPen(const QPen &pen)
  24492. {
  24493. mPen = pen;
  24494. }
  24495. /*!
  24496. Sets the pen that will be used to draw the line when selected
  24497. \see setPen, setSelected
  24498. */
  24499. void QCPItemStraightLine::setSelectedPen(const QPen &pen)
  24500. {
  24501. mSelectedPen = pen;
  24502. }
  24503. /* inherits documentation from base class */
  24504. double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24505. {
  24506. Q_UNUSED(details)
  24507. if (onlySelectable && !mSelectable)
  24508. return -1;
  24509. return QCPVector2D(pos).distanceToStraightLine(point1->pixelPosition(), point2->pixelPosition()-point1->pixelPosition());
  24510. }
  24511. /* inherits documentation from base class */
  24512. void QCPItemStraightLine::draw(QCPPainter *painter)
  24513. {
  24514. QCPVector2D start(point1->pixelPosition());
  24515. QCPVector2D end(point2->pixelPosition());
  24516. // get visible segment of straight line inside clipRect:
  24517. int clipPad = qCeil(mainPen().widthF());
  24518. QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  24519. // paint visible segment, if existent:
  24520. if (!line.isNull())
  24521. {
  24522. painter->setPen(mainPen());
  24523. painter->drawLine(line);
  24524. }
  24525. }
  24526. /*! \internal
  24527. Returns the section of the straight line defined by \a base and direction vector \a
  24528. vec, that is visible in the specified \a rect.
  24529. This is a helper function for \ref draw.
  24530. */
  24531. QLineF QCPItemStraightLine::getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const
  24532. {
  24533. double bx, by;
  24534. double gamma;
  24535. QLineF result;
  24536. if (vec.x() == 0 && vec.y() == 0)
  24537. return result;
  24538. if (qFuzzyIsNull(vec.x())) // line is vertical
  24539. {
  24540. // check top of rect:
  24541. bx = rect.left();
  24542. by = rect.top();
  24543. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  24544. if (gamma >= 0 && gamma <= rect.width())
  24545. result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical
  24546. } else if (qFuzzyIsNull(vec.y())) // line is horizontal
  24547. {
  24548. // check left of rect:
  24549. bx = rect.left();
  24550. by = rect.top();
  24551. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  24552. if (gamma >= 0 && gamma <= rect.height())
  24553. result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal
  24554. } else // line is skewed
  24555. {
  24556. QList<QCPVector2D> pointVectors;
  24557. // check top of rect:
  24558. bx = rect.left();
  24559. by = rect.top();
  24560. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  24561. if (gamma >= 0 && gamma <= rect.width())
  24562. pointVectors.append(QCPVector2D(bx+gamma, by));
  24563. // check bottom of rect:
  24564. bx = rect.left();
  24565. by = rect.bottom();
  24566. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  24567. if (gamma >= 0 && gamma <= rect.width())
  24568. pointVectors.append(QCPVector2D(bx+gamma, by));
  24569. // check left of rect:
  24570. bx = rect.left();
  24571. by = rect.top();
  24572. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  24573. if (gamma >= 0 && gamma <= rect.height())
  24574. pointVectors.append(QCPVector2D(bx, by+gamma));
  24575. // check right of rect:
  24576. bx = rect.right();
  24577. by = rect.top();
  24578. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  24579. if (gamma >= 0 && gamma <= rect.height())
  24580. pointVectors.append(QCPVector2D(bx, by+gamma));
  24581. // evaluate points:
  24582. if (pointVectors.size() == 2)
  24583. {
  24584. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  24585. } else if (pointVectors.size() > 2)
  24586. {
  24587. // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
  24588. double distSqrMax = 0;
  24589. QCPVector2D pv1, pv2;
  24590. for (int i=0; i<pointVectors.size()-1; ++i)
  24591. {
  24592. for (int k=i+1; k<pointVectors.size(); ++k)
  24593. {
  24594. double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
  24595. if (distSqr > distSqrMax)
  24596. {
  24597. pv1 = pointVectors.at(i);
  24598. pv2 = pointVectors.at(k);
  24599. distSqrMax = distSqr;
  24600. }
  24601. }
  24602. }
  24603. result.setPoints(pv1.toPointF(), pv2.toPointF());
  24604. }
  24605. }
  24606. return result;
  24607. }
  24608. /*! \internal
  24609. Returns the pen that should be used for drawing lines. Returns mPen when the
  24610. item is not selected and mSelectedPen when it is.
  24611. */
  24612. QPen QCPItemStraightLine::mainPen() const
  24613. {
  24614. return mSelected ? mSelectedPen : mPen;
  24615. }
  24616. /* end of 'src/items/item-straightline.cpp' */
  24617. /* including file 'src/items/item-line.cpp' */
  24618. /* modified 2021-03-29T02:30:44, size 8525 */
  24619. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24620. //////////////////// QCPItemLine
  24621. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24622. /*! \class QCPItemLine
  24623. \brief A line from one point to another
  24624. \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions."
  24625. It has two positions, \a start and \a end, which define the end points of the line.
  24626. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow.
  24627. */
  24628. /*!
  24629. Creates a line item and sets default values.
  24630. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24631. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24632. */
  24633. QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) :
  24634. QCPAbstractItem(parentPlot),
  24635. start(createPosition(QLatin1String("start"))),
  24636. end(createPosition(QLatin1String("end")))
  24637. {
  24638. start->setCoords(0, 0);
  24639. end->setCoords(1, 1);
  24640. setPen(QPen(Qt::black));
  24641. setSelectedPen(QPen(Qt::blue,2));
  24642. }
  24643. QCPItemLine::~QCPItemLine()
  24644. {
  24645. }
  24646. /*!
  24647. Sets the pen that will be used to draw the line
  24648. \see setSelectedPen
  24649. */
  24650. void QCPItemLine::setPen(const QPen &pen)
  24651. {
  24652. mPen = pen;
  24653. }
  24654. /*!
  24655. Sets the pen that will be used to draw the line when selected
  24656. \see setPen, setSelected
  24657. */
  24658. void QCPItemLine::setSelectedPen(const QPen &pen)
  24659. {
  24660. mSelectedPen = pen;
  24661. }
  24662. /*!
  24663. Sets the line ending style of the head. The head corresponds to the \a end position.
  24664. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24665. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  24666. \see setTail
  24667. */
  24668. void QCPItemLine::setHead(const QCPLineEnding &head)
  24669. {
  24670. mHead = head;
  24671. }
  24672. /*!
  24673. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  24674. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24675. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  24676. \see setHead
  24677. */
  24678. void QCPItemLine::setTail(const QCPLineEnding &tail)
  24679. {
  24680. mTail = tail;
  24681. }
  24682. /* inherits documentation from base class */
  24683. double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24684. {
  24685. Q_UNUSED(details)
  24686. if (onlySelectable && !mSelectable)
  24687. return -1;
  24688. return qSqrt(QCPVector2D(pos).distanceSquaredToLine(start->pixelPosition(), end->pixelPosition()));
  24689. }
  24690. /* inherits documentation from base class */
  24691. void QCPItemLine::draw(QCPPainter *painter)
  24692. {
  24693. QCPVector2D startVec(start->pixelPosition());
  24694. QCPVector2D endVec(end->pixelPosition());
  24695. if (qFuzzyIsNull((startVec-endVec).lengthSquared()))
  24696. return;
  24697. // get visible segment of straight line inside clipRect:
  24698. int clipPad = int(qMax(mHead.boundingDistance(), mTail.boundingDistance()));
  24699. clipPad = qMax(clipPad, qCeil(mainPen().widthF()));
  24700. QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  24701. // paint visible segment, if existent:
  24702. if (!line.isNull())
  24703. {
  24704. painter->setPen(mainPen());
  24705. painter->drawLine(line);
  24706. painter->setBrush(Qt::SolidPattern);
  24707. if (mTail.style() != QCPLineEnding::esNone)
  24708. mTail.draw(painter, startVec, startVec-endVec);
  24709. if (mHead.style() != QCPLineEnding::esNone)
  24710. mHead.draw(painter, endVec, endVec-startVec);
  24711. }
  24712. }
  24713. /*! \internal
  24714. Returns the section of the line defined by \a start and \a end, that is visible in the specified
  24715. \a rect.
  24716. This is a helper function for \ref draw.
  24717. */
  24718. QLineF QCPItemLine::getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const
  24719. {
  24720. bool containsStart = rect.contains(qRound(start.x()), qRound(start.y()));
  24721. bool containsEnd = rect.contains(qRound(end.x()), qRound(end.y()));
  24722. if (containsStart && containsEnd)
  24723. return {start.toPointF(), end.toPointF()};
  24724. QCPVector2D base = start;
  24725. QCPVector2D vec = end-start;
  24726. double bx, by;
  24727. double gamma, mu;
  24728. QLineF result;
  24729. QList<QCPVector2D> pointVectors;
  24730. if (!qFuzzyIsNull(vec.y())) // line is not horizontal
  24731. {
  24732. // check top of rect:
  24733. bx = rect.left();
  24734. by = rect.top();
  24735. mu = (by-base.y())/vec.y();
  24736. if (mu >= 0 && mu <= 1)
  24737. {
  24738. gamma = base.x()-bx + mu*vec.x();
  24739. if (gamma >= 0 && gamma <= rect.width())
  24740. pointVectors.append(QCPVector2D(bx+gamma, by));
  24741. }
  24742. // check bottom of rect:
  24743. bx = rect.left();
  24744. by = rect.bottom();
  24745. mu = (by-base.y())/vec.y();
  24746. if (mu >= 0 && mu <= 1)
  24747. {
  24748. gamma = base.x()-bx + mu*vec.x();
  24749. if (gamma >= 0 && gamma <= rect.width())
  24750. pointVectors.append(QCPVector2D(bx+gamma, by));
  24751. }
  24752. }
  24753. if (!qFuzzyIsNull(vec.x())) // line is not vertical
  24754. {
  24755. // check left of rect:
  24756. bx = rect.left();
  24757. by = rect.top();
  24758. mu = (bx-base.x())/vec.x();
  24759. if (mu >= 0 && mu <= 1)
  24760. {
  24761. gamma = base.y()-by + mu*vec.y();
  24762. if (gamma >= 0 && gamma <= rect.height())
  24763. pointVectors.append(QCPVector2D(bx, by+gamma));
  24764. }
  24765. // check right of rect:
  24766. bx = rect.right();
  24767. by = rect.top();
  24768. mu = (bx-base.x())/vec.x();
  24769. if (mu >= 0 && mu <= 1)
  24770. {
  24771. gamma = base.y()-by + mu*vec.y();
  24772. if (gamma >= 0 && gamma <= rect.height())
  24773. pointVectors.append(QCPVector2D(bx, by+gamma));
  24774. }
  24775. }
  24776. if (containsStart)
  24777. pointVectors.append(start);
  24778. if (containsEnd)
  24779. pointVectors.append(end);
  24780. // evaluate points:
  24781. if (pointVectors.size() == 2)
  24782. {
  24783. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  24784. } else if (pointVectors.size() > 2)
  24785. {
  24786. // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
  24787. double distSqrMax = 0;
  24788. QCPVector2D pv1, pv2;
  24789. for (int i=0; i<pointVectors.size()-1; ++i)
  24790. {
  24791. for (int k=i+1; k<pointVectors.size(); ++k)
  24792. {
  24793. double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
  24794. if (distSqr > distSqrMax)
  24795. {
  24796. pv1 = pointVectors.at(i);
  24797. pv2 = pointVectors.at(k);
  24798. distSqrMax = distSqr;
  24799. }
  24800. }
  24801. }
  24802. result.setPoints(pv1.toPointF(), pv2.toPointF());
  24803. }
  24804. return result;
  24805. }
  24806. /*! \internal
  24807. Returns the pen that should be used for drawing lines. Returns mPen when the
  24808. item is not selected and mSelectedPen when it is.
  24809. */
  24810. QPen QCPItemLine::mainPen() const
  24811. {
  24812. return mSelected ? mSelectedPen : mPen;
  24813. }
  24814. /* end of 'src/items/item-line.cpp' */
  24815. /* including file 'src/items/item-curve.cpp' */
  24816. /* modified 2021-03-29T02:30:44, size 7273 */
  24817. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24818. //////////////////// QCPItemCurve
  24819. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24820. /*! \class QCPItemCurve
  24821. \brief A curved line from one point to another
  24822. \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions."
  24823. It has four positions, \a start and \a end, which define the end points of the line, and two
  24824. control points which define the direction the line exits from the start and the direction from
  24825. which it approaches the end: \a startDir and \a endDir.
  24826. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an
  24827. arrow.
  24828. Often it is desirable for the control points to stay at fixed relative positions to the start/end
  24829. point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start,
  24830. and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir.
  24831. */
  24832. /*!
  24833. Creates a curve item and sets default values.
  24834. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24835. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24836. */
  24837. QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) :
  24838. QCPAbstractItem(parentPlot),
  24839. start(createPosition(QLatin1String("start"))),
  24840. startDir(createPosition(QLatin1String("startDir"))),
  24841. endDir(createPosition(QLatin1String("endDir"))),
  24842. end(createPosition(QLatin1String("end")))
  24843. {
  24844. start->setCoords(0, 0);
  24845. startDir->setCoords(0.5, 0);
  24846. endDir->setCoords(0, 0.5);
  24847. end->setCoords(1, 1);
  24848. setPen(QPen(Qt::black));
  24849. setSelectedPen(QPen(Qt::blue,2));
  24850. }
  24851. QCPItemCurve::~QCPItemCurve()
  24852. {
  24853. }
  24854. /*!
  24855. Sets the pen that will be used to draw the line
  24856. \see setSelectedPen
  24857. */
  24858. void QCPItemCurve::setPen(const QPen &pen)
  24859. {
  24860. mPen = pen;
  24861. }
  24862. /*!
  24863. Sets the pen that will be used to draw the line when selected
  24864. \see setPen, setSelected
  24865. */
  24866. void QCPItemCurve::setSelectedPen(const QPen &pen)
  24867. {
  24868. mSelectedPen = pen;
  24869. }
  24870. /*!
  24871. Sets the line ending style of the head. The head corresponds to the \a end position.
  24872. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24873. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  24874. \see setTail
  24875. */
  24876. void QCPItemCurve::setHead(const QCPLineEnding &head)
  24877. {
  24878. mHead = head;
  24879. }
  24880. /*!
  24881. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  24882. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24883. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  24884. \see setHead
  24885. */
  24886. void QCPItemCurve::setTail(const QCPLineEnding &tail)
  24887. {
  24888. mTail = tail;
  24889. }
  24890. /* inherits documentation from base class */
  24891. double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24892. {
  24893. Q_UNUSED(details)
  24894. if (onlySelectable && !mSelectable)
  24895. return -1;
  24896. QPointF startVec(start->pixelPosition());
  24897. QPointF startDirVec(startDir->pixelPosition());
  24898. QPointF endDirVec(endDir->pixelPosition());
  24899. QPointF endVec(end->pixelPosition());
  24900. QPainterPath cubicPath(startVec);
  24901. cubicPath.cubicTo(startDirVec, endDirVec, endVec);
  24902. QList<QPolygonF> polygons = cubicPath.toSubpathPolygons();
  24903. if (polygons.isEmpty())
  24904. return -1;
  24905. const QPolygonF polygon = polygons.first();
  24906. QCPVector2D p(pos);
  24907. double minDistSqr = (std::numeric_limits<double>::max)();
  24908. for (int i=1; i<polygon.size(); ++i)
  24909. {
  24910. double distSqr = p.distanceSquaredToLine(polygon.at(i-1), polygon.at(i));
  24911. if (distSqr < minDistSqr)
  24912. minDistSqr = distSqr;
  24913. }
  24914. return qSqrt(minDistSqr);
  24915. }
  24916. /* inherits documentation from base class */
  24917. void QCPItemCurve::draw(QCPPainter *painter)
  24918. {
  24919. QCPVector2D startVec(start->pixelPosition());
  24920. QCPVector2D startDirVec(startDir->pixelPosition());
  24921. QCPVector2D endDirVec(endDir->pixelPosition());
  24922. QCPVector2D endVec(end->pixelPosition());
  24923. if ((endVec-startVec).length() > 1e10) // too large curves cause crash
  24924. return;
  24925. QPainterPath cubicPath(startVec.toPointF());
  24926. cubicPath.cubicTo(startDirVec.toPointF(), endDirVec.toPointF(), endVec.toPointF());
  24927. // paint visible segment, if existent:
  24928. const int clipEnlarge = qCeil(mainPen().widthF());
  24929. QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
  24930. QRect cubicRect = cubicPath.controlPointRect().toRect();
  24931. if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position
  24932. cubicRect.adjust(0, 0, 1, 1);
  24933. if (clip.intersects(cubicRect))
  24934. {
  24935. painter->setPen(mainPen());
  24936. painter->drawPath(cubicPath);
  24937. painter->setBrush(Qt::SolidPattern);
  24938. if (mTail.style() != QCPLineEnding::esNone)
  24939. mTail.draw(painter, startVec, M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI);
  24940. if (mHead.style() != QCPLineEnding::esNone)
  24941. mHead.draw(painter, endVec, -cubicPath.angleAtPercent(1)/180.0*M_PI);
  24942. }
  24943. }
  24944. /*! \internal
  24945. Returns the pen that should be used for drawing lines. Returns mPen when the
  24946. item is not selected and mSelectedPen when it is.
  24947. */
  24948. QPen QCPItemCurve::mainPen() const
  24949. {
  24950. return mSelected ? mSelectedPen : mPen;
  24951. }
  24952. /* end of 'src/items/item-curve.cpp' */
  24953. /* including file 'src/items/item-rect.cpp' */
  24954. /* modified 2021-03-29T02:30:44, size 6472 */
  24955. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24956. //////////////////// QCPItemRect
  24957. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24958. /*! \class QCPItemRect
  24959. \brief A rectangle
  24960. \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions."
  24961. It has two positions, \a topLeft and \a bottomRight, which define the rectangle.
  24962. */
  24963. /*!
  24964. Creates a rectangle item and sets default values.
  24965. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24966. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24967. */
  24968. QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) :
  24969. QCPAbstractItem(parentPlot),
  24970. topLeft(createPosition(QLatin1String("topLeft"))),
  24971. bottomRight(createPosition(QLatin1String("bottomRight"))),
  24972. top(createAnchor(QLatin1String("top"), aiTop)),
  24973. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  24974. right(createAnchor(QLatin1String("right"), aiRight)),
  24975. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  24976. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  24977. left(createAnchor(QLatin1String("left"), aiLeft))
  24978. {
  24979. topLeft->setCoords(0, 1);
  24980. bottomRight->setCoords(1, 0);
  24981. setPen(QPen(Qt::black));
  24982. setSelectedPen(QPen(Qt::blue,2));
  24983. setBrush(Qt::NoBrush);
  24984. setSelectedBrush(Qt::NoBrush);
  24985. }
  24986. QCPItemRect::~QCPItemRect()
  24987. {
  24988. }
  24989. /*!
  24990. Sets the pen that will be used to draw the line of the rectangle
  24991. \see setSelectedPen, setBrush
  24992. */
  24993. void QCPItemRect::setPen(const QPen &pen)
  24994. {
  24995. mPen = pen;
  24996. }
  24997. /*!
  24998. Sets the pen that will be used to draw the line of the rectangle when selected
  24999. \see setPen, setSelected
  25000. */
  25001. void QCPItemRect::setSelectedPen(const QPen &pen)
  25002. {
  25003. mSelectedPen = pen;
  25004. }
  25005. /*!
  25006. Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to
  25007. Qt::NoBrush.
  25008. \see setSelectedBrush, setPen
  25009. */
  25010. void QCPItemRect::setBrush(const QBrush &brush)
  25011. {
  25012. mBrush = brush;
  25013. }
  25014. /*!
  25015. Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a
  25016. brush to Qt::NoBrush.
  25017. \see setBrush
  25018. */
  25019. void QCPItemRect::setSelectedBrush(const QBrush &brush)
  25020. {
  25021. mSelectedBrush = brush;
  25022. }
  25023. /* inherits documentation from base class */
  25024. double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25025. {
  25026. Q_UNUSED(details)
  25027. if (onlySelectable && !mSelectable)
  25028. return -1;
  25029. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()).normalized();
  25030. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  25031. return rectDistance(rect, pos, filledRect);
  25032. }
  25033. /* inherits documentation from base class */
  25034. void QCPItemRect::draw(QCPPainter *painter)
  25035. {
  25036. QPointF p1 = topLeft->pixelPosition();
  25037. QPointF p2 = bottomRight->pixelPosition();
  25038. if (p1.toPoint() == p2.toPoint())
  25039. return;
  25040. QRectF rect = QRectF(p1, p2).normalized();
  25041. double clipPad = mainPen().widthF();
  25042. QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  25043. if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect
  25044. {
  25045. painter->setPen(mainPen());
  25046. painter->setBrush(mainBrush());
  25047. painter->drawRect(rect);
  25048. }
  25049. }
  25050. /* inherits documentation from base class */
  25051. QPointF QCPItemRect::anchorPixelPosition(int anchorId) const
  25052. {
  25053. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
  25054. switch (anchorId)
  25055. {
  25056. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  25057. case aiTopRight: return rect.topRight();
  25058. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  25059. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  25060. case aiBottomLeft: return rect.bottomLeft();
  25061. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  25062. }
  25063. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25064. return {};
  25065. }
  25066. /*! \internal
  25067. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25068. and mSelectedPen when it is.
  25069. */
  25070. QPen QCPItemRect::mainPen() const
  25071. {
  25072. return mSelected ? mSelectedPen : mPen;
  25073. }
  25074. /*! \internal
  25075. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  25076. is not selected and mSelectedBrush when it is.
  25077. */
  25078. QBrush QCPItemRect::mainBrush() const
  25079. {
  25080. return mSelected ? mSelectedBrush : mBrush;
  25081. }
  25082. /* end of 'src/items/item-rect.cpp' */
  25083. /* including file 'src/items/item-text.cpp' */
  25084. /* modified 2021-03-29T02:30:44, size 13335 */
  25085. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25086. //////////////////// QCPItemText
  25087. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25088. /*! \class QCPItemText
  25089. \brief A text label
  25090. \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions."
  25091. Its position is defined by the member \a position and the setting of \ref setPositionAlignment.
  25092. The latter controls which part of the text rect shall be aligned with \a position.
  25093. The text alignment itself (i.e. left, center, right) can be controlled with \ref
  25094. setTextAlignment.
  25095. The text may be rotated around the \a position point with \ref setRotation.
  25096. */
  25097. /*!
  25098. Creates a text item and sets default values.
  25099. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25100. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25101. */
  25102. QCPItemText::QCPItemText(QCustomPlot *parentPlot) :
  25103. QCPAbstractItem(parentPlot),
  25104. position(createPosition(QLatin1String("position"))),
  25105. topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)),
  25106. top(createAnchor(QLatin1String("top"), aiTop)),
  25107. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  25108. right(createAnchor(QLatin1String("right"), aiRight)),
  25109. bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)),
  25110. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  25111. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  25112. left(createAnchor(QLatin1String("left"), aiLeft)),
  25113. mText(QLatin1String("text")),
  25114. mPositionAlignment(Qt::AlignCenter),
  25115. mTextAlignment(Qt::AlignTop|Qt::AlignHCenter),
  25116. mRotation(0)
  25117. {
  25118. position->setCoords(0, 0);
  25119. setPen(Qt::NoPen);
  25120. setSelectedPen(Qt::NoPen);
  25121. setBrush(Qt::NoBrush);
  25122. setSelectedBrush(Qt::NoBrush);
  25123. setColor(Qt::black);
  25124. setSelectedColor(Qt::blue);
  25125. }
  25126. QCPItemText::~QCPItemText()
  25127. {
  25128. }
  25129. /*!
  25130. Sets the color of the text.
  25131. */
  25132. void QCPItemText::setColor(const QColor &color)
  25133. {
  25134. mColor = color;
  25135. }
  25136. /*!
  25137. Sets the color of the text that will be used when the item is selected.
  25138. */
  25139. void QCPItemText::setSelectedColor(const QColor &color)
  25140. {
  25141. mSelectedColor = color;
  25142. }
  25143. /*!
  25144. Sets the pen that will be used do draw a rectangular border around the text. To disable the
  25145. border, set \a pen to Qt::NoPen.
  25146. \see setSelectedPen, setBrush, setPadding
  25147. */
  25148. void QCPItemText::setPen(const QPen &pen)
  25149. {
  25150. mPen = pen;
  25151. }
  25152. /*!
  25153. Sets the pen that will be used do draw a rectangular border around the text, when the item is
  25154. selected. To disable the border, set \a pen to Qt::NoPen.
  25155. \see setPen
  25156. */
  25157. void QCPItemText::setSelectedPen(const QPen &pen)
  25158. {
  25159. mSelectedPen = pen;
  25160. }
  25161. /*!
  25162. Sets the brush that will be used do fill the background of the text. To disable the
  25163. background, set \a brush to Qt::NoBrush.
  25164. \see setSelectedBrush, setPen, setPadding
  25165. */
  25166. void QCPItemText::setBrush(const QBrush &brush)
  25167. {
  25168. mBrush = brush;
  25169. }
  25170. /*!
  25171. Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the
  25172. background, set \a brush to Qt::NoBrush.
  25173. \see setBrush
  25174. */
  25175. void QCPItemText::setSelectedBrush(const QBrush &brush)
  25176. {
  25177. mSelectedBrush = brush;
  25178. }
  25179. /*!
  25180. Sets the font of the text.
  25181. \see setSelectedFont, setColor
  25182. */
  25183. void QCPItemText::setFont(const QFont &font)
  25184. {
  25185. mFont = font;
  25186. }
  25187. /*!
  25188. Sets the font of the text that will be used when the item is selected.
  25189. \see setFont
  25190. */
  25191. void QCPItemText::setSelectedFont(const QFont &font)
  25192. {
  25193. mSelectedFont = font;
  25194. }
  25195. /*!
  25196. Sets the text that will be displayed. Multi-line texts are supported by inserting a line break
  25197. character, e.g. '\n'.
  25198. \see setFont, setColor, setTextAlignment
  25199. */
  25200. void QCPItemText::setText(const QString &text)
  25201. {
  25202. mText = text;
  25203. }
  25204. /*!
  25205. Sets which point of the text rect shall be aligned with \a position.
  25206. Examples:
  25207. \li If \a alignment is <tt>Qt::AlignHCenter | Qt::AlignTop</tt>, the text will be positioned such
  25208. that the top of the text rect will be horizontally centered on \a position.
  25209. \li If \a alignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt>, \a position will indicate the
  25210. bottom left corner of the text rect.
  25211. If you want to control the alignment of (multi-lined) text within the text rect, use \ref
  25212. setTextAlignment.
  25213. */
  25214. void QCPItemText::setPositionAlignment(Qt::Alignment alignment)
  25215. {
  25216. mPositionAlignment = alignment;
  25217. }
  25218. /*!
  25219. Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight).
  25220. */
  25221. void QCPItemText::setTextAlignment(Qt::Alignment alignment)
  25222. {
  25223. mTextAlignment = alignment;
  25224. }
  25225. /*!
  25226. Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated
  25227. around \a position.
  25228. */
  25229. void QCPItemText::setRotation(double degrees)
  25230. {
  25231. mRotation = degrees;
  25232. }
  25233. /*!
  25234. Sets the distance between the border of the text rectangle and the text. The appearance (and
  25235. visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush.
  25236. */
  25237. void QCPItemText::setPadding(const QMargins &padding)
  25238. {
  25239. mPadding = padding;
  25240. }
  25241. /* inherits documentation from base class */
  25242. double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25243. {
  25244. Q_UNUSED(details)
  25245. if (onlySelectable && !mSelectable)
  25246. return -1;
  25247. // The rect may be rotated, so we transform the actual clicked pos to the rotated
  25248. // coordinate system, so we can use the normal rectDistance function for non-rotated rects:
  25249. QPointF positionPixels(position->pixelPosition());
  25250. QTransform inputTransform;
  25251. inputTransform.translate(positionPixels.x(), positionPixels.y());
  25252. inputTransform.rotate(-mRotation);
  25253. inputTransform.translate(-positionPixels.x(), -positionPixels.y());
  25254. QPointF rotatedPos = inputTransform.map(pos);
  25255. QFontMetrics fontMetrics(mFont);
  25256. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  25257. QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  25258. QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment);
  25259. textBoxRect.moveTopLeft(textPos.toPoint());
  25260. return rectDistance(textBoxRect, rotatedPos, true);
  25261. }
  25262. /* inherits documentation from base class */
  25263. void QCPItemText::draw(QCPPainter *painter)
  25264. {
  25265. QPointF pos(position->pixelPosition());
  25266. QTransform transform = painter->transform();
  25267. transform.translate(pos.x(), pos.y());
  25268. if (!qFuzzyIsNull(mRotation))
  25269. transform.rotate(mRotation);
  25270. painter->setFont(mainFont());
  25271. QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  25272. QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  25273. QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
  25274. textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top()));
  25275. textBoxRect.moveTopLeft(textPos.toPoint());
  25276. int clipPad = qCeil(mainPen().widthF());
  25277. QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  25278. if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect())))
  25279. {
  25280. painter->setTransform(transform);
  25281. if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) ||
  25282. (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0))
  25283. {
  25284. painter->setPen(mainPen());
  25285. painter->setBrush(mainBrush());
  25286. painter->drawRect(textBoxRect);
  25287. }
  25288. painter->setBrush(Qt::NoBrush);
  25289. painter->setPen(QPen(mainColor()));
  25290. painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText);
  25291. }
  25292. }
  25293. /* inherits documentation from base class */
  25294. QPointF QCPItemText::anchorPixelPosition(int anchorId) const
  25295. {
  25296. // get actual rect points (pretty much copied from draw function):
  25297. QPointF pos(position->pixelPosition());
  25298. QTransform transform;
  25299. transform.translate(pos.x(), pos.y());
  25300. if (!qFuzzyIsNull(mRotation))
  25301. transform.rotate(mRotation);
  25302. QFontMetrics fontMetrics(mainFont());
  25303. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  25304. QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  25305. QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
  25306. textBoxRect.moveTopLeft(textPos.toPoint());
  25307. QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect));
  25308. switch (anchorId)
  25309. {
  25310. case aiTopLeft: return rectPoly.at(0);
  25311. case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5;
  25312. case aiTopRight: return rectPoly.at(1);
  25313. case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5;
  25314. case aiBottomRight: return rectPoly.at(2);
  25315. case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5;
  25316. case aiBottomLeft: return rectPoly.at(3);
  25317. case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5;
  25318. }
  25319. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25320. return {};
  25321. }
  25322. /*! \internal
  25323. Returns the point that must be given to the QPainter::drawText function (which expects the top
  25324. left point of the text rect), according to the position \a pos, the text bounding box \a rect and
  25325. the requested \a positionAlignment.
  25326. For example, if \a positionAlignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt> the returned point
  25327. will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally
  25328. drawn at that point, the lower left corner of the resulting text rect is at \a pos.
  25329. */
  25330. QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const
  25331. {
  25332. if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop))
  25333. return pos;
  25334. QPointF result = pos; // start at top left
  25335. if (positionAlignment.testFlag(Qt::AlignHCenter))
  25336. result.rx() -= rect.width()/2.0;
  25337. else if (positionAlignment.testFlag(Qt::AlignRight))
  25338. result.rx() -= rect.width();
  25339. if (positionAlignment.testFlag(Qt::AlignVCenter))
  25340. result.ry() -= rect.height()/2.0;
  25341. else if (positionAlignment.testFlag(Qt::AlignBottom))
  25342. result.ry() -= rect.height();
  25343. return result;
  25344. }
  25345. /*! \internal
  25346. Returns the font that should be used for drawing text. Returns mFont when the item is not selected
  25347. and mSelectedFont when it is.
  25348. */
  25349. QFont QCPItemText::mainFont() const
  25350. {
  25351. return mSelected ? mSelectedFont : mFont;
  25352. }
  25353. /*! \internal
  25354. Returns the color that should be used for drawing text. Returns mColor when the item is not
  25355. selected and mSelectedColor when it is.
  25356. */
  25357. QColor QCPItemText::mainColor() const
  25358. {
  25359. return mSelected ? mSelectedColor : mColor;
  25360. }
  25361. /*! \internal
  25362. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25363. and mSelectedPen when it is.
  25364. */
  25365. QPen QCPItemText::mainPen() const
  25366. {
  25367. return mSelected ? mSelectedPen : mPen;
  25368. }
  25369. /*! \internal
  25370. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  25371. is not selected and mSelectedBrush when it is.
  25372. */
  25373. QBrush QCPItemText::mainBrush() const
  25374. {
  25375. return mSelected ? mSelectedBrush : mBrush;
  25376. }
  25377. /* end of 'src/items/item-text.cpp' */
  25378. /* including file 'src/items/item-ellipse.cpp' */
  25379. /* modified 2021-03-29T02:30:44, size 7881 */
  25380. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25381. //////////////////// QCPItemEllipse
  25382. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25383. /*! \class QCPItemEllipse
  25384. \brief An ellipse
  25385. \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions."
  25386. It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in.
  25387. */
  25388. /*!
  25389. Creates an ellipse item and sets default values.
  25390. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25391. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25392. */
  25393. QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) :
  25394. QCPAbstractItem(parentPlot),
  25395. topLeft(createPosition(QLatin1String("topLeft"))),
  25396. bottomRight(createPosition(QLatin1String("bottomRight"))),
  25397. topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)),
  25398. top(createAnchor(QLatin1String("top"), aiTop)),
  25399. topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)),
  25400. right(createAnchor(QLatin1String("right"), aiRight)),
  25401. bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)),
  25402. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  25403. bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)),
  25404. left(createAnchor(QLatin1String("left"), aiLeft)),
  25405. center(createAnchor(QLatin1String("center"), aiCenter))
  25406. {
  25407. topLeft->setCoords(0, 1);
  25408. bottomRight->setCoords(1, 0);
  25409. setPen(QPen(Qt::black));
  25410. setSelectedPen(QPen(Qt::blue, 2));
  25411. setBrush(Qt::NoBrush);
  25412. setSelectedBrush(Qt::NoBrush);
  25413. }
  25414. QCPItemEllipse::~QCPItemEllipse()
  25415. {
  25416. }
  25417. /*!
  25418. Sets the pen that will be used to draw the line of the ellipse
  25419. \see setSelectedPen, setBrush
  25420. */
  25421. void QCPItemEllipse::setPen(const QPen &pen)
  25422. {
  25423. mPen = pen;
  25424. }
  25425. /*!
  25426. Sets the pen that will be used to draw the line of the ellipse when selected
  25427. \see setPen, setSelected
  25428. */
  25429. void QCPItemEllipse::setSelectedPen(const QPen &pen)
  25430. {
  25431. mSelectedPen = pen;
  25432. }
  25433. /*!
  25434. Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to
  25435. Qt::NoBrush.
  25436. \see setSelectedBrush, setPen
  25437. */
  25438. void QCPItemEllipse::setBrush(const QBrush &brush)
  25439. {
  25440. mBrush = brush;
  25441. }
  25442. /*!
  25443. Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a
  25444. brush to Qt::NoBrush.
  25445. \see setBrush
  25446. */
  25447. void QCPItemEllipse::setSelectedBrush(const QBrush &brush)
  25448. {
  25449. mSelectedBrush = brush;
  25450. }
  25451. /* inherits documentation from base class */
  25452. double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25453. {
  25454. Q_UNUSED(details)
  25455. if (onlySelectable && !mSelectable)
  25456. return -1;
  25457. QPointF p1 = topLeft->pixelPosition();
  25458. QPointF p2 = bottomRight->pixelPosition();
  25459. QPointF center((p1+p2)/2.0);
  25460. double a = qAbs(p1.x()-p2.x())/2.0;
  25461. double b = qAbs(p1.y()-p2.y())/2.0;
  25462. double x = pos.x()-center.x();
  25463. double y = pos.y()-center.y();
  25464. // distance to border:
  25465. double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b));
  25466. double result = qAbs(c-1)*qSqrt(x*x+y*y);
  25467. // filled ellipse, allow click inside to count as hit:
  25468. if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
  25469. {
  25470. if (x*x/(a*a) + y*y/(b*b) <= 1)
  25471. result = mParentPlot->selectionTolerance()*0.99;
  25472. }
  25473. return result;
  25474. }
  25475. /* inherits documentation from base class */
  25476. void QCPItemEllipse::draw(QCPPainter *painter)
  25477. {
  25478. QPointF p1 = topLeft->pixelPosition();
  25479. QPointF p2 = bottomRight->pixelPosition();
  25480. if (p1.toPoint() == p2.toPoint())
  25481. return;
  25482. QRectF ellipseRect = QRectF(p1, p2).normalized();
  25483. const int clipEnlarge = qCeil(mainPen().widthF());
  25484. QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
  25485. if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect
  25486. {
  25487. painter->setPen(mainPen());
  25488. painter->setBrush(mainBrush());
  25489. #ifdef __EXCEPTIONS
  25490. try // drawEllipse sometimes throws exceptions if ellipse is too big
  25491. {
  25492. #endif
  25493. painter->drawEllipse(ellipseRect);
  25494. #ifdef __EXCEPTIONS
  25495. } catch (...)
  25496. {
  25497. qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible";
  25498. setVisible(false);
  25499. }
  25500. #endif
  25501. }
  25502. }
  25503. /* inherits documentation from base class */
  25504. QPointF QCPItemEllipse::anchorPixelPosition(int anchorId) const
  25505. {
  25506. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
  25507. switch (anchorId)
  25508. {
  25509. case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2);
  25510. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  25511. case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2);
  25512. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  25513. case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2);
  25514. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  25515. case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2);
  25516. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  25517. case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5;
  25518. }
  25519. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25520. return {};
  25521. }
  25522. /*! \internal
  25523. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25524. and mSelectedPen when it is.
  25525. */
  25526. QPen QCPItemEllipse::mainPen() const
  25527. {
  25528. return mSelected ? mSelectedPen : mPen;
  25529. }
  25530. /*! \internal
  25531. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  25532. is not selected and mSelectedBrush when it is.
  25533. */
  25534. QBrush QCPItemEllipse::mainBrush() const
  25535. {
  25536. return mSelected ? mSelectedBrush : mBrush;
  25537. }
  25538. /* end of 'src/items/item-ellipse.cpp' */
  25539. /* including file 'src/items/item-pixmap.cpp' */
  25540. /* modified 2021-03-29T02:30:44, size 10622 */
  25541. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25542. //////////////////// QCPItemPixmap
  25543. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25544. /*! \class QCPItemPixmap
  25545. \brief An arbitrary pixmap
  25546. \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions."
  25547. It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will
  25548. be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to
  25549. fit the rectangle or be drawn aligned to the topLeft position.
  25550. If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown
  25551. on the right side of the example image), the pixmap will be flipped in the respective
  25552. orientations.
  25553. */
  25554. /*!
  25555. Creates a rectangle item and sets default values.
  25556. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25557. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25558. */
  25559. QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) :
  25560. QCPAbstractItem(parentPlot),
  25561. topLeft(createPosition(QLatin1String("topLeft"))),
  25562. bottomRight(createPosition(QLatin1String("bottomRight"))),
  25563. top(createAnchor(QLatin1String("top"), aiTop)),
  25564. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  25565. right(createAnchor(QLatin1String("right"), aiRight)),
  25566. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  25567. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  25568. left(createAnchor(QLatin1String("left"), aiLeft)),
  25569. mScaled(false),
  25570. mScaledPixmapInvalidated(true),
  25571. mAspectRatioMode(Qt::KeepAspectRatio),
  25572. mTransformationMode(Qt::SmoothTransformation)
  25573. {
  25574. topLeft->setCoords(0, 1);
  25575. bottomRight->setCoords(1, 0);
  25576. setPen(Qt::NoPen);
  25577. setSelectedPen(QPen(Qt::blue));
  25578. }
  25579. QCPItemPixmap::~QCPItemPixmap()
  25580. {
  25581. }
  25582. /*!
  25583. Sets the pixmap that will be displayed.
  25584. */
  25585. void QCPItemPixmap::setPixmap(const QPixmap &pixmap)
  25586. {
  25587. mPixmap = pixmap;
  25588. mScaledPixmapInvalidated = true;
  25589. if (mPixmap.isNull())
  25590. qDebug() << Q_FUNC_INFO << "pixmap is null";
  25591. }
  25592. /*!
  25593. Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a
  25594. bottomRight positions.
  25595. */
  25596. void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode)
  25597. {
  25598. mScaled = scaled;
  25599. mAspectRatioMode = aspectRatioMode;
  25600. mTransformationMode = transformationMode;
  25601. mScaledPixmapInvalidated = true;
  25602. }
  25603. /*!
  25604. Sets the pen that will be used to draw a border around the pixmap.
  25605. \see setSelectedPen, setBrush
  25606. */
  25607. void QCPItemPixmap::setPen(const QPen &pen)
  25608. {
  25609. mPen = pen;
  25610. }
  25611. /*!
  25612. Sets the pen that will be used to draw a border around the pixmap when selected
  25613. \see setPen, setSelected
  25614. */
  25615. void QCPItemPixmap::setSelectedPen(const QPen &pen)
  25616. {
  25617. mSelectedPen = pen;
  25618. }
  25619. /* inherits documentation from base class */
  25620. double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25621. {
  25622. Q_UNUSED(details)
  25623. if (onlySelectable && !mSelectable)
  25624. return -1;
  25625. return rectDistance(getFinalRect(), pos, true);
  25626. }
  25627. /* inherits documentation from base class */
  25628. void QCPItemPixmap::draw(QCPPainter *painter)
  25629. {
  25630. bool flipHorz = false;
  25631. bool flipVert = false;
  25632. QRect rect = getFinalRect(&flipHorz, &flipVert);
  25633. int clipPad = mainPen().style() == Qt::NoPen ? 0 : qCeil(mainPen().widthF());
  25634. QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  25635. if (boundingRect.intersects(clipRect()))
  25636. {
  25637. updateScaledPixmap(rect, flipHorz, flipVert);
  25638. painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap);
  25639. QPen pen = mainPen();
  25640. if (pen.style() != Qt::NoPen)
  25641. {
  25642. painter->setPen(pen);
  25643. painter->setBrush(Qt::NoBrush);
  25644. painter->drawRect(rect);
  25645. }
  25646. }
  25647. }
  25648. /* inherits documentation from base class */
  25649. QPointF QCPItemPixmap::anchorPixelPosition(int anchorId) const
  25650. {
  25651. bool flipHorz = false;
  25652. bool flipVert = false;
  25653. QRect rect = getFinalRect(&flipHorz, &flipVert);
  25654. // we actually want denormal rects (negative width/height) here, so restore
  25655. // the flipped state:
  25656. if (flipHorz)
  25657. rect.adjust(rect.width(), 0, -rect.width(), 0);
  25658. if (flipVert)
  25659. rect.adjust(0, rect.height(), 0, -rect.height());
  25660. switch (anchorId)
  25661. {
  25662. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  25663. case aiTopRight: return rect.topRight();
  25664. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  25665. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  25666. case aiBottomLeft: return rect.bottomLeft();
  25667. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  25668. }
  25669. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25670. return {};
  25671. }
  25672. /*! \internal
  25673. Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The
  25674. parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped
  25675. horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a
  25676. bottomRight.)
  25677. This function only creates the scaled pixmap when the buffered pixmap has a different size than
  25678. the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does
  25679. not cause expensive rescaling every time.
  25680. If scaling is disabled, sets mScaledPixmap to a null QPixmap.
  25681. */
  25682. void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert)
  25683. {
  25684. if (mPixmap.isNull())
  25685. return;
  25686. if (mScaled)
  25687. {
  25688. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25689. double devicePixelRatio = mPixmap.devicePixelRatio();
  25690. #else
  25691. double devicePixelRatio = 1.0;
  25692. #endif
  25693. if (finalRect.isNull())
  25694. finalRect = getFinalRect(&flipHorz, &flipVert);
  25695. if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()/devicePixelRatio)
  25696. {
  25697. mScaledPixmap = mPixmap.scaled(finalRect.size()*devicePixelRatio, mAspectRatioMode, mTransformationMode);
  25698. if (flipHorz || flipVert)
  25699. mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert));
  25700. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25701. mScaledPixmap.setDevicePixelRatio(devicePixelRatio);
  25702. #endif
  25703. }
  25704. } else if (!mScaledPixmap.isNull())
  25705. mScaledPixmap = QPixmap();
  25706. mScaledPixmapInvalidated = false;
  25707. }
  25708. /*! \internal
  25709. Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions
  25710. and scaling settings.
  25711. The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn
  25712. flipped horizontally or vertically in the returned rect. (The returned rect itself is always
  25713. normalized, i.e. the top left corner of the rect is actually further to the top/left than the
  25714. bottom right corner). This is the case when the item position \a topLeft is further to the
  25715. bottom/right than \a bottomRight.
  25716. If scaling is disabled, returns a rect with size of the original pixmap and the top left corner
  25717. aligned with the item position \a topLeft. The position \a bottomRight is ignored.
  25718. */
  25719. QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const
  25720. {
  25721. QRect result;
  25722. bool flipHorz = false;
  25723. bool flipVert = false;
  25724. QPoint p1 = topLeft->pixelPosition().toPoint();
  25725. QPoint p2 = bottomRight->pixelPosition().toPoint();
  25726. if (p1 == p2)
  25727. return {p1, QSize(0, 0)};
  25728. if (mScaled)
  25729. {
  25730. QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y());
  25731. QPoint topLeft = p1;
  25732. if (newSize.width() < 0)
  25733. {
  25734. flipHorz = true;
  25735. newSize.rwidth() *= -1;
  25736. topLeft.setX(p2.x());
  25737. }
  25738. if (newSize.height() < 0)
  25739. {
  25740. flipVert = true;
  25741. newSize.rheight() *= -1;
  25742. topLeft.setY(p2.y());
  25743. }
  25744. QSize scaledSize = mPixmap.size();
  25745. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25746. scaledSize /= mPixmap.devicePixelRatio();
  25747. scaledSize.scale(newSize*mPixmap.devicePixelRatio(), mAspectRatioMode);
  25748. #else
  25749. scaledSize.scale(newSize, mAspectRatioMode);
  25750. #endif
  25751. result = QRect(topLeft, scaledSize);
  25752. } else
  25753. {
  25754. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25755. result = QRect(p1, mPixmap.size()/mPixmap.devicePixelRatio());
  25756. #else
  25757. result = QRect(p1, mPixmap.size());
  25758. #endif
  25759. }
  25760. if (flippedHorz)
  25761. *flippedHorz = flipHorz;
  25762. if (flippedVert)
  25763. *flippedVert = flipVert;
  25764. return result;
  25765. }
  25766. /*! \internal
  25767. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25768. and mSelectedPen when it is.
  25769. */
  25770. QPen QCPItemPixmap::mainPen() const
  25771. {
  25772. return mSelected ? mSelectedPen : mPen;
  25773. }
  25774. /* end of 'src/items/item-pixmap.cpp' */
  25775. /* including file 'src/items/item-tracer.cpp' */
  25776. /* modified 2021-03-29T02:30:44, size 14645 */
  25777. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25778. //////////////////// QCPItemTracer
  25779. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25780. /*! \class QCPItemTracer
  25781. \brief Item that sticks to QCPGraph data points
  25782. \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions."
  25783. The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt
  25784. the coordinate axes of the graph and update its \a position to be on the graph's data. This means
  25785. the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a
  25786. QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a
  25787. position will have no effect because they will be overriden in the next redraw (this is when the
  25788. coordinate update happens).
  25789. If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will
  25790. stay at the corresponding end of the graph.
  25791. With \ref setInterpolating you may specify whether the tracer may only stay exactly on data
  25792. points or whether it interpolates data points linearly, if given a key that lies between two data
  25793. points of the graph.
  25794. The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer
  25795. have no own visual appearance (set the style to \ref tsNone), and just connect other item
  25796. positions to the tracer \a position (used as an anchor) via \ref
  25797. QCPItemPosition::setParentAnchor.
  25798. \note The tracer position is only automatically updated upon redraws. So when the data of the
  25799. graph changes and immediately afterwards (without a redraw) the position coordinates of the
  25800. tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref
  25801. updatePosition must be called manually, prior to reading the tracer coordinates.
  25802. */
  25803. /*!
  25804. Creates a tracer item and sets default values.
  25805. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25806. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25807. */
  25808. QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) :
  25809. QCPAbstractItem(parentPlot),
  25810. position(createPosition(QLatin1String("position"))),
  25811. mSize(6),
  25812. mStyle(tsCrosshair),
  25813. mGraph(nullptr),
  25814. mGraphKey(0),
  25815. mInterpolating(false)
  25816. {
  25817. position->setCoords(0, 0);
  25818. setBrush(Qt::NoBrush);
  25819. setSelectedBrush(Qt::NoBrush);
  25820. setPen(QPen(Qt::black));
  25821. setSelectedPen(QPen(Qt::blue, 2));
  25822. }
  25823. QCPItemTracer::~QCPItemTracer()
  25824. {
  25825. }
  25826. /*!
  25827. Sets the pen that will be used to draw the line of the tracer
  25828. \see setSelectedPen, setBrush
  25829. */
  25830. void QCPItemTracer::setPen(const QPen &pen)
  25831. {
  25832. mPen = pen;
  25833. }
  25834. /*!
  25835. Sets the pen that will be used to draw the line of the tracer when selected
  25836. \see setPen, setSelected
  25837. */
  25838. void QCPItemTracer::setSelectedPen(const QPen &pen)
  25839. {
  25840. mSelectedPen = pen;
  25841. }
  25842. /*!
  25843. Sets the brush that will be used to draw any fills of the tracer
  25844. \see setSelectedBrush, setPen
  25845. */
  25846. void QCPItemTracer::setBrush(const QBrush &brush)
  25847. {
  25848. mBrush = brush;
  25849. }
  25850. /*!
  25851. Sets the brush that will be used to draw any fills of the tracer, when selected.
  25852. \see setBrush, setSelected
  25853. */
  25854. void QCPItemTracer::setSelectedBrush(const QBrush &brush)
  25855. {
  25856. mSelectedBrush = brush;
  25857. }
  25858. /*!
  25859. Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare
  25860. does, \ref tsCrosshair does not).
  25861. */
  25862. void QCPItemTracer::setSize(double size)
  25863. {
  25864. mSize = size;
  25865. }
  25866. /*!
  25867. Sets the style/visual appearance of the tracer.
  25868. If you only want to use the tracer \a position as an anchor for other items, set \a style to
  25869. \ref tsNone.
  25870. */
  25871. void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style)
  25872. {
  25873. mStyle = style;
  25874. }
  25875. /*!
  25876. Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type
  25877. QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph.
  25878. To free the tracer from any graph, set \a graph to \c nullptr. The tracer \a position can then be
  25879. placed freely like any other item position. This is the state the tracer will assume when its
  25880. graph gets deleted while still attached to it.
  25881. \see setGraphKey
  25882. */
  25883. void QCPItemTracer::setGraph(QCPGraph *graph)
  25884. {
  25885. if (graph)
  25886. {
  25887. if (graph->parentPlot() == mParentPlot)
  25888. {
  25889. position->setType(QCPItemPosition::ptPlotCoords);
  25890. position->setAxes(graph->keyAxis(), graph->valueAxis());
  25891. mGraph = graph;
  25892. updatePosition();
  25893. } else
  25894. qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item";
  25895. } else
  25896. {
  25897. mGraph = nullptr;
  25898. }
  25899. }
  25900. /*!
  25901. Sets the key of the graph's data point the tracer will be positioned at. This is the only free
  25902. coordinate of a tracer when attached to a graph.
  25903. Depending on \ref setInterpolating, the tracer will be either positioned on the data point
  25904. closest to \a key, or will stay exactly at \a key and interpolate the value linearly.
  25905. \see setGraph, setInterpolating
  25906. */
  25907. void QCPItemTracer::setGraphKey(double key)
  25908. {
  25909. mGraphKey = key;
  25910. }
  25911. /*!
  25912. Sets whether the value of the graph's data points shall be interpolated, when positioning the
  25913. tracer.
  25914. If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on
  25915. the data point of the graph which is closest to the key, but which is not necessarily exactly
  25916. there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and
  25917. the appropriate value will be interpolated from the graph's data points linearly.
  25918. \see setGraph, setGraphKey
  25919. */
  25920. void QCPItemTracer::setInterpolating(bool enabled)
  25921. {
  25922. mInterpolating = enabled;
  25923. }
  25924. /* inherits documentation from base class */
  25925. double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25926. {
  25927. Q_UNUSED(details)
  25928. if (onlySelectable && !mSelectable)
  25929. return -1;
  25930. QPointF center(position->pixelPosition());
  25931. double w = mSize/2.0;
  25932. QRect clip = clipRect();
  25933. switch (mStyle)
  25934. {
  25935. case tsNone: return -1;
  25936. case tsPlus:
  25937. {
  25938. if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25939. return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(center+QPointF(-w, 0), center+QPointF(w, 0)),
  25940. QCPVector2D(pos).distanceSquaredToLine(center+QPointF(0, -w), center+QPointF(0, w))));
  25941. break;
  25942. }
  25943. case tsCrosshair:
  25944. {
  25945. return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(clip.left(), center.y()), QCPVector2D(clip.right(), center.y())),
  25946. QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(center.x(), clip.top()), QCPVector2D(center.x(), clip.bottom()))));
  25947. }
  25948. case tsCircle:
  25949. {
  25950. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25951. {
  25952. // distance to border:
  25953. double centerDist = QCPVector2D(center-pos).length();
  25954. double circleLine = w;
  25955. double result = qAbs(centerDist-circleLine);
  25956. // filled ellipse, allow click inside to count as hit:
  25957. if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
  25958. {
  25959. if (centerDist <= circleLine)
  25960. result = mParentPlot->selectionTolerance()*0.99;
  25961. }
  25962. return result;
  25963. }
  25964. break;
  25965. }
  25966. case tsSquare:
  25967. {
  25968. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25969. {
  25970. QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w));
  25971. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  25972. return rectDistance(rect, pos, filledRect);
  25973. }
  25974. break;
  25975. }
  25976. }
  25977. return -1;
  25978. }
  25979. /* inherits documentation from base class */
  25980. void QCPItemTracer::draw(QCPPainter *painter)
  25981. {
  25982. updatePosition();
  25983. if (mStyle == tsNone)
  25984. return;
  25985. painter->setPen(mainPen());
  25986. painter->setBrush(mainBrush());
  25987. QPointF center(position->pixelPosition());
  25988. double w = mSize/2.0;
  25989. QRect clip = clipRect();
  25990. switch (mStyle)
  25991. {
  25992. case tsNone: return;
  25993. case tsPlus:
  25994. {
  25995. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25996. {
  25997. painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0)));
  25998. painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w)));
  25999. }
  26000. break;
  26001. }
  26002. case tsCrosshair:
  26003. {
  26004. if (center.y() > clip.top() && center.y() < clip.bottom())
  26005. painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y()));
  26006. if (center.x() > clip.left() && center.x() < clip.right())
  26007. painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom()));
  26008. break;
  26009. }
  26010. case tsCircle:
  26011. {
  26012. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  26013. painter->drawEllipse(center, w, w);
  26014. break;
  26015. }
  26016. case tsSquare:
  26017. {
  26018. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  26019. painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w)));
  26020. break;
  26021. }
  26022. }
  26023. }
  26024. /*!
  26025. If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a
  26026. position to reside on the graph data, depending on the configured key (\ref setGraphKey).
  26027. It is called automatically on every redraw and normally doesn't need to be called manually. One
  26028. exception is when you want to read the tracer coordinates via \a position and are not sure that
  26029. the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw.
  26030. In that situation, call this function before accessing \a position, to make sure you don't get
  26031. out-of-date coordinates.
  26032. If there is no graph set on this tracer, this function does nothing.
  26033. */
  26034. void QCPItemTracer::updatePosition()
  26035. {
  26036. if (mGraph)
  26037. {
  26038. if (mParentPlot->hasPlottable(mGraph))
  26039. {
  26040. if (mGraph->data()->size() > 1)
  26041. {
  26042. QCPGraphDataContainer::const_iterator first = mGraph->data()->constBegin();
  26043. QCPGraphDataContainer::const_iterator last = mGraph->data()->constEnd()-1;
  26044. if (mGraphKey <= first->key)
  26045. position->setCoords(first->key, first->value);
  26046. else if (mGraphKey >= last->key)
  26047. position->setCoords(last->key, last->value);
  26048. else
  26049. {
  26050. QCPGraphDataContainer::const_iterator it = mGraph->data()->findBegin(mGraphKey);
  26051. if (it != mGraph->data()->constEnd()) // mGraphKey is not exactly on last iterator, but somewhere between iterators
  26052. {
  26053. QCPGraphDataContainer::const_iterator prevIt = it;
  26054. ++it; // won't advance to constEnd because we handled that case (mGraphKey >= last->key) before
  26055. if (mInterpolating)
  26056. {
  26057. // interpolate between iterators around mGraphKey:
  26058. double slope = 0;
  26059. if (!qFuzzyCompare(double(it->key), double(prevIt->key)))
  26060. slope = (it->value-prevIt->value)/(it->key-prevIt->key);
  26061. position->setCoords(mGraphKey, (mGraphKey-prevIt->key)*slope+prevIt->value);
  26062. } else
  26063. {
  26064. // find iterator with key closest to mGraphKey:
  26065. if (mGraphKey < (prevIt->key+it->key)*0.5)
  26066. position->setCoords(prevIt->key, prevIt->value);
  26067. else
  26068. position->setCoords(it->key, it->value);
  26069. }
  26070. } else // mGraphKey is exactly on last iterator (should actually be caught when comparing first/last keys, but this is a failsafe for fp uncertainty)
  26071. position->setCoords(it->key, it->value);
  26072. }
  26073. } else if (mGraph->data()->size() == 1)
  26074. {
  26075. QCPGraphDataContainer::const_iterator it = mGraph->data()->constBegin();
  26076. position->setCoords(it->key, it->value);
  26077. } else
  26078. qDebug() << Q_FUNC_INFO << "graph has no data";
  26079. } else
  26080. qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)";
  26081. }
  26082. }
  26083. /*! \internal
  26084. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  26085. and mSelectedPen when it is.
  26086. */
  26087. QPen QCPItemTracer::mainPen() const
  26088. {
  26089. return mSelected ? mSelectedPen : mPen;
  26090. }
  26091. /*! \internal
  26092. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  26093. is not selected and mSelectedBrush when it is.
  26094. */
  26095. QBrush QCPItemTracer::mainBrush() const
  26096. {
  26097. return mSelected ? mSelectedBrush : mBrush;
  26098. }
  26099. /* end of 'src/items/item-tracer.cpp' */
  26100. /* including file 'src/items/item-bracket.cpp' */
  26101. /* modified 2021-03-29T02:30:44, size 10705 */
  26102. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26103. //////////////////// QCPItemBracket
  26104. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26105. /*! \class QCPItemBracket
  26106. \brief A bracket for referencing/highlighting certain parts in the plot.
  26107. \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions."
  26108. It has two positions, \a left and \a right, which define the span of the bracket. If \a left is
  26109. actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the
  26110. example image.
  26111. The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket
  26112. stretches away from the embraced span, can be controlled with \ref setLength.
  26113. \image html QCPItemBracket-length.png
  26114. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  26115. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  26116. It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine
  26117. or QCPItemCurve) or a text label (QCPItemText), to the bracket.
  26118. */
  26119. /*!
  26120. Creates a bracket item and sets default values.
  26121. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  26122. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  26123. */
  26124. QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) :
  26125. QCPAbstractItem(parentPlot),
  26126. left(createPosition(QLatin1String("left"))),
  26127. right(createPosition(QLatin1String("right"))),
  26128. center(createAnchor(QLatin1String("center"), aiCenter)),
  26129. mLength(8),
  26130. mStyle(bsCalligraphic)
  26131. {
  26132. left->setCoords(0, 0);
  26133. right->setCoords(1, 1);
  26134. setPen(QPen(Qt::black));
  26135. setSelectedPen(QPen(Qt::blue, 2));
  26136. }
  26137. QCPItemBracket::~QCPItemBracket()
  26138. {
  26139. }
  26140. /*!
  26141. Sets the pen that will be used to draw the bracket.
  26142. Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the
  26143. stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use
  26144. \ref setLength, which has a similar effect.
  26145. \see setSelectedPen
  26146. */
  26147. void QCPItemBracket::setPen(const QPen &pen)
  26148. {
  26149. mPen = pen;
  26150. }
  26151. /*!
  26152. Sets the pen that will be used to draw the bracket when selected
  26153. \see setPen, setSelected
  26154. */
  26155. void QCPItemBracket::setSelectedPen(const QPen &pen)
  26156. {
  26157. mSelectedPen = pen;
  26158. }
  26159. /*!
  26160. Sets the \a length in pixels how far the bracket extends in the direction towards the embraced
  26161. span of the bracket (i.e. perpendicular to the <i>left</i>-<i>right</i>-direction)
  26162. \image html QCPItemBracket-length.png
  26163. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  26164. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  26165. */
  26166. void QCPItemBracket::setLength(double length)
  26167. {
  26168. mLength = length;
  26169. }
  26170. /*!
  26171. Sets the style of the bracket, i.e. the shape/visual appearance.
  26172. \see setPen
  26173. */
  26174. void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style)
  26175. {
  26176. mStyle = style;
  26177. }
  26178. /* inherits documentation from base class */
  26179. double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  26180. {
  26181. Q_UNUSED(details)
  26182. if (onlySelectable && !mSelectable)
  26183. return -1;
  26184. QCPVector2D p(pos);
  26185. QCPVector2D leftVec(left->pixelPosition());
  26186. QCPVector2D rightVec(right->pixelPosition());
  26187. if (leftVec.toPoint() == rightVec.toPoint())
  26188. return -1;
  26189. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  26190. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  26191. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  26192. switch (mStyle)
  26193. {
  26194. case QCPItemBracket::bsSquare:
  26195. case QCPItemBracket::bsRound:
  26196. {
  26197. double a = p.distanceSquaredToLine(centerVec-widthVec, centerVec+widthVec);
  26198. double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec, centerVec-widthVec);
  26199. double c = p.distanceSquaredToLine(centerVec+widthVec+lengthVec, centerVec+widthVec);
  26200. return qSqrt(qMin(qMin(a, b), c));
  26201. }
  26202. case QCPItemBracket::bsCurly:
  26203. case QCPItemBracket::bsCalligraphic:
  26204. {
  26205. double a = p.distanceSquaredToLine(centerVec-widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
  26206. double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec*0.7, centerVec-widthVec*0.75+lengthVec*0.15);
  26207. double c = p.distanceSquaredToLine(centerVec+widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
  26208. double d = p.distanceSquaredToLine(centerVec+widthVec+lengthVec*0.7, centerVec+widthVec*0.75+lengthVec*0.15);
  26209. return qSqrt(qMin(qMin(a, b), qMin(c, d)));
  26210. }
  26211. }
  26212. return -1;
  26213. }
  26214. /* inherits documentation from base class */
  26215. void QCPItemBracket::draw(QCPPainter *painter)
  26216. {
  26217. QCPVector2D leftVec(left->pixelPosition());
  26218. QCPVector2D rightVec(right->pixelPosition());
  26219. if (leftVec.toPoint() == rightVec.toPoint())
  26220. return;
  26221. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  26222. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  26223. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  26224. QPolygon boundingPoly;
  26225. boundingPoly << leftVec.toPoint() << rightVec.toPoint()
  26226. << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint();
  26227. const int clipEnlarge = qCeil(mainPen().widthF());
  26228. QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
  26229. if (clip.intersects(boundingPoly.boundingRect()))
  26230. {
  26231. painter->setPen(mainPen());
  26232. switch (mStyle)
  26233. {
  26234. case bsSquare:
  26235. {
  26236. painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF());
  26237. painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
  26238. painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26239. break;
  26240. }
  26241. case bsRound:
  26242. {
  26243. painter->setBrush(Qt::NoBrush);
  26244. QPainterPath path;
  26245. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  26246. path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF());
  26247. path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26248. painter->drawPath(path);
  26249. break;
  26250. }
  26251. case bsCurly:
  26252. {
  26253. painter->setBrush(Qt::NoBrush);
  26254. QPainterPath path;
  26255. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  26256. path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+lengthVec).toPointF(), centerVec.toPointF());
  26257. path.cubicTo((centerVec-0.4*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26258. painter->drawPath(path);
  26259. break;
  26260. }
  26261. case bsCalligraphic:
  26262. {
  26263. painter->setPen(Qt::NoPen);
  26264. painter->setBrush(QBrush(mainPen().color()));
  26265. QPainterPath path;
  26266. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  26267. path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+0.8*lengthVec).toPointF(), centerVec.toPointF());
  26268. path.cubicTo((centerVec-0.4*widthVec+0.8*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26269. path.cubicTo((centerVec-widthVec-lengthVec*0.5).toPointF(), (centerVec-0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+lengthVec*0.2).toPointF());
  26270. path.cubicTo((centerVec+0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
  26271. painter->drawPath(path);
  26272. break;
  26273. }
  26274. }
  26275. }
  26276. }
  26277. /* inherits documentation from base class */
  26278. QPointF QCPItemBracket::anchorPixelPosition(int anchorId) const
  26279. {
  26280. QCPVector2D leftVec(left->pixelPosition());
  26281. QCPVector2D rightVec(right->pixelPosition());
  26282. if (leftVec.toPoint() == rightVec.toPoint())
  26283. return leftVec.toPointF();
  26284. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  26285. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  26286. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  26287. switch (anchorId)
  26288. {
  26289. case aiCenter:
  26290. return centerVec.toPointF();
  26291. }
  26292. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  26293. return {};
  26294. }
  26295. /*! \internal
  26296. Returns the pen that should be used for drawing lines. Returns mPen when the
  26297. item is not selected and mSelectedPen when it is.
  26298. */
  26299. QPen QCPItemBracket::mainPen() const
  26300. {
  26301. return mSelected ? mSelectedPen : mPen;
  26302. }
  26303. /* end of 'src/items/item-bracket.cpp' */
  26304. /* including file 'src/polar/radialaxis.cpp' */
  26305. /* modified 2021-03-29T02:30:44, size 49415 */
  26306. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26307. //////////////////// QCPPolarAxisRadial
  26308. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26309. /*! \class QCPPolarAxisRadial
  26310. \brief The radial axis inside a radial plot
  26311. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  26312. functionality to be incomplete, as well as changing public interfaces in the future.
  26313. Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
  26314. tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
  26315. the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
  26316. documentation of QCPAxisTicker.
  26317. */
  26318. /* start of documentation of inline functions */
  26319. /*! \fn QSharedPointer<QCPAxisTicker> QCPPolarAxisRadial::ticker() const
  26320. Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
  26321. responsible for generating the tick positions and tick labels of this axis. You can access the
  26322. \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
  26323. (\ref QCPAxisTicker::setTickCount).
  26324. You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
  26325. the documentation there. A new axis ticker can be set with \ref setTicker.
  26326. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  26327. ticker simply by passing the same shared pointer to multiple axes.
  26328. \see setTicker
  26329. */
  26330. /* end of documentation of inline functions */
  26331. /* start of documentation of signals */
  26332. /*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange)
  26333. This signal is emitted when the range of this axis has changed. You can connect it to the \ref
  26334. setRange slot of another axis to communicate the new range to the other axis, in order for it to
  26335. be synchronized.
  26336. You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
  26337. This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
  26338. range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
  26339. slot would limit the x axis to ranges between 0 and 10:
  26340. \code
  26341. customPlot->xAxis->setRange(newRange.bounded(0, 10))
  26342. \endcode
  26343. */
  26344. /*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
  26345. \overload
  26346. Additionally to the new range, this signal also provides the previous range held by the axis as
  26347. \a oldRange.
  26348. */
  26349. /*! \fn void QCPPolarAxisRadial::scaleTypeChanged(QCPPolarAxisRadial::ScaleType scaleType);
  26350. This signal is emitted when the scale type changes, by calls to \ref setScaleType
  26351. */
  26352. /*! \fn void QCPPolarAxisRadial::selectionChanged(QCPPolarAxisRadial::SelectableParts selection)
  26353. This signal is emitted when the selection state of this axis has changed, either by user interaction
  26354. or by a direct call to \ref setSelectedParts.
  26355. */
  26356. /*! \fn void QCPPolarAxisRadial::selectableChanged(const QCPPolarAxisRadial::SelectableParts &parts);
  26357. This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
  26358. */
  26359. /* end of documentation of signals */
  26360. /*!
  26361. Constructs an Axis instance of Type \a type for the axis rect \a parent.
  26362. Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
  26363. them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
  26364. create them manually and then inject them also via \ref QCPAxisRect::addAxis.
  26365. */
  26366. QCPPolarAxisRadial::QCPPolarAxisRadial(QCPPolarAxisAngular *parent) :
  26367. QCPLayerable(parent->parentPlot(), QString(), parent),
  26368. mRangeDrag(true),
  26369. mRangeZoom(true),
  26370. mRangeZoomFactor(0.85),
  26371. // axis base:
  26372. mAngularAxis(parent),
  26373. mAngle(45),
  26374. mAngleReference(arAngularAxis),
  26375. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  26376. mSelectedParts(spNone),
  26377. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  26378. mSelectedBasePen(QPen(Qt::blue, 2)),
  26379. // axis label:
  26380. mLabelPadding(0),
  26381. mLabel(),
  26382. mLabelFont(mParentPlot->font()),
  26383. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  26384. mLabelColor(Qt::black),
  26385. mSelectedLabelColor(Qt::blue),
  26386. // tick labels:
  26387. // mTickLabelPadding(0), in label painter
  26388. mTickLabels(true),
  26389. // mTickLabelRotation(0), in label painter
  26390. mTickLabelFont(mParentPlot->font()),
  26391. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  26392. mTickLabelColor(Qt::black),
  26393. mSelectedTickLabelColor(Qt::blue),
  26394. mNumberPrecision(6),
  26395. mNumberFormatChar('g'),
  26396. mNumberBeautifulPowers(true),
  26397. mNumberMultiplyCross(false),
  26398. // ticks and subticks:
  26399. mTicks(true),
  26400. mSubTicks(true),
  26401. mTickLengthIn(5),
  26402. mTickLengthOut(0),
  26403. mSubTickLengthIn(2),
  26404. mSubTickLengthOut(0),
  26405. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  26406. mSelectedTickPen(QPen(Qt::blue, 2)),
  26407. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  26408. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  26409. // scale and range:
  26410. mRange(0, 5),
  26411. mRangeReversed(false),
  26412. mScaleType(stLinear),
  26413. // internal members:
  26414. mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect
  26415. mTicker(new QCPAxisTicker),
  26416. mLabelPainter(mParentPlot)
  26417. {
  26418. setParent(parent);
  26419. setAntialiased(true);
  26420. setTickLabelPadding(5);
  26421. setTickLabelRotation(0);
  26422. setTickLabelMode(lmUpright);
  26423. mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artTangent);
  26424. mLabelPainter.setAbbreviateDecimalPowers(false);
  26425. }
  26426. QCPPolarAxisRadial::~QCPPolarAxisRadial()
  26427. {
  26428. }
  26429. QCPPolarAxisRadial::LabelMode QCPPolarAxisRadial::tickLabelMode() const
  26430. {
  26431. switch (mLabelPainter.anchorMode())
  26432. {
  26433. case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright;
  26434. case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated;
  26435. default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break;
  26436. }
  26437. return lmUpright;
  26438. }
  26439. /* No documentation as it is a property getter */
  26440. QString QCPPolarAxisRadial::numberFormat() const
  26441. {
  26442. QString result;
  26443. result.append(mNumberFormatChar);
  26444. if (mNumberBeautifulPowers)
  26445. {
  26446. result.append(QLatin1Char('b'));
  26447. if (mNumberMultiplyCross)
  26448. result.append(QLatin1Char('c'));
  26449. }
  26450. return result;
  26451. }
  26452. /* No documentation as it is a property getter */
  26453. int QCPPolarAxisRadial::tickLengthIn() const
  26454. {
  26455. return mTickLengthIn;
  26456. }
  26457. /* No documentation as it is a property getter */
  26458. int QCPPolarAxisRadial::tickLengthOut() const
  26459. {
  26460. return mTickLengthOut;
  26461. }
  26462. /* No documentation as it is a property getter */
  26463. int QCPPolarAxisRadial::subTickLengthIn() const
  26464. {
  26465. return mSubTickLengthIn;
  26466. }
  26467. /* No documentation as it is a property getter */
  26468. int QCPPolarAxisRadial::subTickLengthOut() const
  26469. {
  26470. return mSubTickLengthOut;
  26471. }
  26472. /* No documentation as it is a property getter */
  26473. int QCPPolarAxisRadial::labelPadding() const
  26474. {
  26475. return mLabelPadding;
  26476. }
  26477. void QCPPolarAxisRadial::setRangeDrag(bool enabled)
  26478. {
  26479. mRangeDrag = enabled;
  26480. }
  26481. void QCPPolarAxisRadial::setRangeZoom(bool enabled)
  26482. {
  26483. mRangeZoom = enabled;
  26484. }
  26485. void QCPPolarAxisRadial::setRangeZoomFactor(double factor)
  26486. {
  26487. mRangeZoomFactor = factor;
  26488. }
  26489. /*!
  26490. Sets whether the axis uses a linear scale or a logarithmic scale.
  26491. Note that this method controls the coordinate transformation. For logarithmic scales, you will
  26492. likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
  26493. the axis ticker to an instance of \ref QCPAxisTickerLog :
  26494. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation
  26495. See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
  26496. creation.
  26497. \ref setNumberPrecision
  26498. */
  26499. void QCPPolarAxisRadial::setScaleType(QCPPolarAxisRadial::ScaleType type)
  26500. {
  26501. if (mScaleType != type)
  26502. {
  26503. mScaleType = type;
  26504. if (mScaleType == stLogarithmic)
  26505. setRange(mRange.sanitizedForLogScale());
  26506. //mCachedMarginValid = false;
  26507. Q_EMIT scaleTypeChanged(mScaleType);
  26508. }
  26509. }
  26510. /*!
  26511. Sets the range of the axis.
  26512. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  26513. is always synchronized with the other axis range, when it changes.
  26514. To invert the direction of an axis, use \ref setRangeReversed.
  26515. */
  26516. void QCPPolarAxisRadial::setRange(const QCPRange &range)
  26517. {
  26518. if (range.lower == mRange.lower && range.upper == mRange.upper)
  26519. return;
  26520. if (!QCPRange::validRange(range)) return;
  26521. QCPRange oldRange = mRange;
  26522. if (mScaleType == stLogarithmic)
  26523. {
  26524. mRange = range.sanitizedForLogScale();
  26525. } else
  26526. {
  26527. mRange = range.sanitizedForLinScale();
  26528. }
  26529. Q_EMIT rangeChanged(mRange);
  26530. Q_EMIT rangeChanged(mRange, oldRange);
  26531. }
  26532. /*!
  26533. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  26534. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  26535. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  26536. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  26537. directly.
  26538. \see SelectablePart, setSelectedParts
  26539. */
  26540. void QCPPolarAxisRadial::setSelectableParts(const SelectableParts &selectable)
  26541. {
  26542. if (mSelectableParts != selectable)
  26543. {
  26544. mSelectableParts = selectable;
  26545. Q_EMIT selectableChanged(mSelectableParts);
  26546. }
  26547. }
  26548. /*!
  26549. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  26550. is selected, it uses a different pen/font.
  26551. The entire selection mechanism for axes is handled automatically when \ref
  26552. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  26553. wish to change the selection state manually.
  26554. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  26555. Q_EMITs the \ref selectionChanged signal when \a selected is different from the previous selection state.
  26556. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  26557. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  26558. */
  26559. void QCPPolarAxisRadial::setSelectedParts(const SelectableParts &selected)
  26560. {
  26561. if (mSelectedParts != selected)
  26562. {
  26563. mSelectedParts = selected;
  26564. Q_EMIT selectionChanged(mSelectedParts);
  26565. }
  26566. }
  26567. /*!
  26568. \overload
  26569. Sets the lower and upper bound of the axis range.
  26570. To invert the direction of an axis, use \ref setRangeReversed.
  26571. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  26572. */
  26573. void QCPPolarAxisRadial::setRange(double lower, double upper)
  26574. {
  26575. if (lower == mRange.lower && upper == mRange.upper)
  26576. return;
  26577. if (!QCPRange::validRange(lower, upper)) return;
  26578. QCPRange oldRange = mRange;
  26579. mRange.lower = lower;
  26580. mRange.upper = upper;
  26581. if (mScaleType == stLogarithmic)
  26582. {
  26583. mRange = mRange.sanitizedForLogScale();
  26584. } else
  26585. {
  26586. mRange = mRange.sanitizedForLinScale();
  26587. }
  26588. Q_EMIT rangeChanged(mRange);
  26589. Q_EMIT rangeChanged(mRange, oldRange);
  26590. }
  26591. /*!
  26592. \overload
  26593. Sets the range of the axis.
  26594. The \a position coordinate indicates together with the \a alignment parameter, where the new
  26595. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  26596. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  26597. or center of the range to be aligned with \a position. Any other values of \a alignment will
  26598. default to Qt::AlignCenter.
  26599. */
  26600. void QCPPolarAxisRadial::setRange(double position, double size, Qt::AlignmentFlag alignment)
  26601. {
  26602. if (alignment == Qt::AlignLeft)
  26603. setRange(position, position+size);
  26604. else if (alignment == Qt::AlignRight)
  26605. setRange(position-size, position);
  26606. else // alignment == Qt::AlignCenter
  26607. setRange(position-size/2.0, position+size/2.0);
  26608. }
  26609. /*!
  26610. Sets the lower bound of the axis range. The upper bound is not changed.
  26611. \see setRange
  26612. */
  26613. void QCPPolarAxisRadial::setRangeLower(double lower)
  26614. {
  26615. if (mRange.lower == lower)
  26616. return;
  26617. QCPRange oldRange = mRange;
  26618. mRange.lower = lower;
  26619. if (mScaleType == stLogarithmic)
  26620. {
  26621. mRange = mRange.sanitizedForLogScale();
  26622. } else
  26623. {
  26624. mRange = mRange.sanitizedForLinScale();
  26625. }
  26626. Q_EMIT rangeChanged(mRange);
  26627. Q_EMIT rangeChanged(mRange, oldRange);
  26628. }
  26629. /*!
  26630. Sets the upper bound of the axis range. The lower bound is not changed.
  26631. \see setRange
  26632. */
  26633. void QCPPolarAxisRadial::setRangeUpper(double upper)
  26634. {
  26635. if (mRange.upper == upper)
  26636. return;
  26637. QCPRange oldRange = mRange;
  26638. mRange.upper = upper;
  26639. if (mScaleType == stLogarithmic)
  26640. {
  26641. mRange = mRange.sanitizedForLogScale();
  26642. } else
  26643. {
  26644. mRange = mRange.sanitizedForLinScale();
  26645. }
  26646. Q_EMIT rangeChanged(mRange);
  26647. Q_EMIT rangeChanged(mRange, oldRange);
  26648. }
  26649. /*!
  26650. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  26651. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  26652. direction of increasing values is inverted.
  26653. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  26654. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  26655. upper part.
  26656. */
  26657. void QCPPolarAxisRadial::setRangeReversed(bool reversed)
  26658. {
  26659. mRangeReversed = reversed;
  26660. }
  26661. void QCPPolarAxisRadial::setAngle(double degrees)
  26662. {
  26663. mAngle = degrees;
  26664. }
  26665. void QCPPolarAxisRadial::setAngleReference(AngleReference reference)
  26666. {
  26667. mAngleReference = reference;
  26668. }
  26669. /*!
  26670. The axis ticker is responsible for generating the tick positions and tick labels. See the
  26671. documentation of QCPAxisTicker for details on how to work with axis tickers.
  26672. You can change the tick positioning/labeling behaviour of this axis by setting a different
  26673. QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
  26674. ticker, access it via \ref ticker.
  26675. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  26676. ticker simply by passing the same shared pointer to multiple axes.
  26677. \see ticker
  26678. */
  26679. void QCPPolarAxisRadial::setTicker(QSharedPointer<QCPAxisTicker> ticker)
  26680. {
  26681. if (ticker)
  26682. mTicker = ticker;
  26683. else
  26684. qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
  26685. // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
  26686. }
  26687. /*!
  26688. Sets whether tick marks are displayed.
  26689. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  26690. that, see \ref setTickLabels.
  26691. \see setSubTicks
  26692. */
  26693. void QCPPolarAxisRadial::setTicks(bool show)
  26694. {
  26695. if (mTicks != show)
  26696. {
  26697. mTicks = show;
  26698. //mCachedMarginValid = false;
  26699. }
  26700. }
  26701. /*!
  26702. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  26703. */
  26704. void QCPPolarAxisRadial::setTickLabels(bool show)
  26705. {
  26706. if (mTickLabels != show)
  26707. {
  26708. mTickLabels = show;
  26709. //mCachedMarginValid = false;
  26710. if (!mTickLabels)
  26711. mTickVectorLabels.clear();
  26712. }
  26713. }
  26714. /*!
  26715. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  26716. \see setLabelPadding, setPadding
  26717. */
  26718. void QCPPolarAxisRadial::setTickLabelPadding(int padding)
  26719. {
  26720. mLabelPainter.setPadding(padding);
  26721. }
  26722. /*!
  26723. Sets the font of the tick labels.
  26724. \see setTickLabels, setTickLabelColor
  26725. */
  26726. void QCPPolarAxisRadial::setTickLabelFont(const QFont &font)
  26727. {
  26728. if (font != mTickLabelFont)
  26729. {
  26730. mTickLabelFont = font;
  26731. //mCachedMarginValid = false;
  26732. }
  26733. }
  26734. /*!
  26735. Sets the color of the tick labels.
  26736. \see setTickLabels, setTickLabelFont
  26737. */
  26738. void QCPPolarAxisRadial::setTickLabelColor(const QColor &color)
  26739. {
  26740. mTickLabelColor = color;
  26741. }
  26742. /*!
  26743. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  26744. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  26745. from -90 to 90 degrees.
  26746. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  26747. other angles, the label is drawn with an offset such that it seems to point toward or away from
  26748. the tick mark.
  26749. */
  26750. void QCPPolarAxisRadial::setTickLabelRotation(double degrees)
  26751. {
  26752. mLabelPainter.setRotation(degrees);
  26753. }
  26754. void QCPPolarAxisRadial::setTickLabelMode(LabelMode mode)
  26755. {
  26756. switch (mode)
  26757. {
  26758. case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break;
  26759. case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break;
  26760. }
  26761. }
  26762. /*!
  26763. Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
  26764. of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
  26765. that, see the "Argument Formats" section in the detailed description of the QString class.
  26766. \a formatCode is a string of one, two or three characters. The first character is identical to
  26767. the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
  26768. format, 'g'/'G' scientific or fixed, whichever is shorter.
  26769. The second and third characters are optional and specific to QCustomPlot:\n
  26770. If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
  26771. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
  26772. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  26773. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  26774. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  26775. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  26776. cross and 183 (0xB7) for the dot.
  26777. Examples for \a formatCode:
  26778. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  26779. normal scientific format is used
  26780. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  26781. beautifully typeset decimal powers and a dot as multiplication sign
  26782. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  26783. multiplication sign
  26784. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  26785. powers. Format code will be reduced to 'f'.
  26786. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  26787. code will not be changed.
  26788. */
  26789. void QCPPolarAxisRadial::setNumberFormat(const QString &formatCode)
  26790. {
  26791. if (formatCode.isEmpty())
  26792. {
  26793. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  26794. return;
  26795. }
  26796. //mCachedMarginValid = false;
  26797. // interpret first char as number format char:
  26798. QString allowedFormatChars(QLatin1String("eEfgG"));
  26799. if (allowedFormatChars.contains(formatCode.at(0)))
  26800. {
  26801. mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
  26802. } else
  26803. {
  26804. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  26805. return;
  26806. }
  26807. if (formatCode.length() < 2)
  26808. {
  26809. mNumberBeautifulPowers = false;
  26810. mNumberMultiplyCross = false;
  26811. } else
  26812. {
  26813. // interpret second char as indicator for beautiful decimal powers:
  26814. if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
  26815. mNumberBeautifulPowers = true;
  26816. else
  26817. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  26818. if (formatCode.length() < 3)
  26819. {
  26820. mNumberMultiplyCross = false;
  26821. } else
  26822. {
  26823. // interpret third char as indicator for dot or cross multiplication symbol:
  26824. if (formatCode.at(2) == QLatin1Char('c'))
  26825. mNumberMultiplyCross = true;
  26826. else if (formatCode.at(2) == QLatin1Char('d'))
  26827. mNumberMultiplyCross = false;
  26828. else
  26829. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  26830. }
  26831. }
  26832. mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers);
  26833. mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot);
  26834. }
  26835. /*!
  26836. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  26837. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  26838. \ref setNumberFormat
  26839. */
  26840. void QCPPolarAxisRadial::setNumberPrecision(int precision)
  26841. {
  26842. if (mNumberPrecision != precision)
  26843. {
  26844. mNumberPrecision = precision;
  26845. //mCachedMarginValid = false;
  26846. }
  26847. }
  26848. /*!
  26849. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  26850. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  26851. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  26852. they won't collide with the ticks.
  26853. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  26854. */
  26855. void QCPPolarAxisRadial::setTickLength(int inside, int outside)
  26856. {
  26857. setTickLengthIn(inside);
  26858. setTickLengthOut(outside);
  26859. }
  26860. /*!
  26861. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  26862. inside the plot.
  26863. \see setTickLengthOut, setTickLength, setSubTickLength
  26864. */
  26865. void QCPPolarAxisRadial::setTickLengthIn(int inside)
  26866. {
  26867. if (mTickLengthIn != inside)
  26868. {
  26869. mTickLengthIn = inside;
  26870. }
  26871. }
  26872. /*!
  26873. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  26874. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  26875. increase their distance to the axis accordingly, so they won't collide with the ticks.
  26876. \see setTickLengthIn, setTickLength, setSubTickLength
  26877. */
  26878. void QCPPolarAxisRadial::setTickLengthOut(int outside)
  26879. {
  26880. if (mTickLengthOut != outside)
  26881. {
  26882. mTickLengthOut = outside;
  26883. //mCachedMarginValid = false; // only outside tick length can change margin
  26884. }
  26885. }
  26886. /*!
  26887. Sets whether sub tick marks are displayed.
  26888. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
  26889. \see setTicks
  26890. */
  26891. void QCPPolarAxisRadial::setSubTicks(bool show)
  26892. {
  26893. if (mSubTicks != show)
  26894. {
  26895. mSubTicks = show;
  26896. //mCachedMarginValid = false;
  26897. }
  26898. }
  26899. /*!
  26900. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  26901. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  26902. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  26903. so they won't collide with the ticks.
  26904. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  26905. */
  26906. void QCPPolarAxisRadial::setSubTickLength(int inside, int outside)
  26907. {
  26908. setSubTickLengthIn(inside);
  26909. setSubTickLengthOut(outside);
  26910. }
  26911. /*!
  26912. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  26913. the plot.
  26914. \see setSubTickLengthOut, setSubTickLength, setTickLength
  26915. */
  26916. void QCPPolarAxisRadial::setSubTickLengthIn(int inside)
  26917. {
  26918. if (mSubTickLengthIn != inside)
  26919. {
  26920. mSubTickLengthIn = inside;
  26921. }
  26922. }
  26923. /*!
  26924. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  26925. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  26926. distance to the axis accordingly, so they won't collide with the ticks.
  26927. \see setSubTickLengthIn, setSubTickLength, setTickLength
  26928. */
  26929. void QCPPolarAxisRadial::setSubTickLengthOut(int outside)
  26930. {
  26931. if (mSubTickLengthOut != outside)
  26932. {
  26933. mSubTickLengthOut = outside;
  26934. //mCachedMarginValid = false; // only outside tick length can change margin
  26935. }
  26936. }
  26937. /*!
  26938. Sets the pen, the axis base line is drawn with.
  26939. \see setTickPen, setSubTickPen
  26940. */
  26941. void QCPPolarAxisRadial::setBasePen(const QPen &pen)
  26942. {
  26943. mBasePen = pen;
  26944. }
  26945. /*!
  26946. Sets the pen, tick marks will be drawn with.
  26947. \see setTickLength, setBasePen
  26948. */
  26949. void QCPPolarAxisRadial::setTickPen(const QPen &pen)
  26950. {
  26951. mTickPen = pen;
  26952. }
  26953. /*!
  26954. Sets the pen, subtick marks will be drawn with.
  26955. \see setSubTickCount, setSubTickLength, setBasePen
  26956. */
  26957. void QCPPolarAxisRadial::setSubTickPen(const QPen &pen)
  26958. {
  26959. mSubTickPen = pen;
  26960. }
  26961. /*!
  26962. Sets the font of the axis label.
  26963. \see setLabelColor
  26964. */
  26965. void QCPPolarAxisRadial::setLabelFont(const QFont &font)
  26966. {
  26967. if (mLabelFont != font)
  26968. {
  26969. mLabelFont = font;
  26970. //mCachedMarginValid = false;
  26971. }
  26972. }
  26973. /*!
  26974. Sets the color of the axis label.
  26975. \see setLabelFont
  26976. */
  26977. void QCPPolarAxisRadial::setLabelColor(const QColor &color)
  26978. {
  26979. mLabelColor = color;
  26980. }
  26981. /*!
  26982. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  26983. its orientation. To disable axis labels, pass an empty string as \a str.
  26984. */
  26985. void QCPPolarAxisRadial::setLabel(const QString &str)
  26986. {
  26987. if (mLabel != str)
  26988. {
  26989. mLabel = str;
  26990. //mCachedMarginValid = false;
  26991. }
  26992. }
  26993. /*!
  26994. Sets the distance between the tick labels and the axis label.
  26995. \see setTickLabelPadding, setPadding
  26996. */
  26997. void QCPPolarAxisRadial::setLabelPadding(int padding)
  26998. {
  26999. if (mLabelPadding != padding)
  27000. {
  27001. mLabelPadding = padding;
  27002. //mCachedMarginValid = false;
  27003. }
  27004. }
  27005. /*!
  27006. Sets the font that is used for tick labels when they are selected.
  27007. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27008. */
  27009. void QCPPolarAxisRadial::setSelectedTickLabelFont(const QFont &font)
  27010. {
  27011. if (font != mSelectedTickLabelFont)
  27012. {
  27013. mSelectedTickLabelFont = font;
  27014. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  27015. }
  27016. }
  27017. /*!
  27018. Sets the font that is used for the axis label when it is selected.
  27019. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27020. */
  27021. void QCPPolarAxisRadial::setSelectedLabelFont(const QFont &font)
  27022. {
  27023. mSelectedLabelFont = font;
  27024. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  27025. }
  27026. /*!
  27027. Sets the color that is used for tick labels when they are selected.
  27028. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27029. */
  27030. void QCPPolarAxisRadial::setSelectedTickLabelColor(const QColor &color)
  27031. {
  27032. if (color != mSelectedTickLabelColor)
  27033. {
  27034. mSelectedTickLabelColor = color;
  27035. }
  27036. }
  27037. /*!
  27038. Sets the color that is used for the axis label when it is selected.
  27039. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27040. */
  27041. void QCPPolarAxisRadial::setSelectedLabelColor(const QColor &color)
  27042. {
  27043. mSelectedLabelColor = color;
  27044. }
  27045. /*!
  27046. Sets the pen that is used to draw the axis base line when selected.
  27047. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27048. */
  27049. void QCPPolarAxisRadial::setSelectedBasePen(const QPen &pen)
  27050. {
  27051. mSelectedBasePen = pen;
  27052. }
  27053. /*!
  27054. Sets the pen that is used to draw the (major) ticks when selected.
  27055. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27056. */
  27057. void QCPPolarAxisRadial::setSelectedTickPen(const QPen &pen)
  27058. {
  27059. mSelectedTickPen = pen;
  27060. }
  27061. /*!
  27062. Sets the pen that is used to draw the subticks when selected.
  27063. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27064. */
  27065. void QCPPolarAxisRadial::setSelectedSubTickPen(const QPen &pen)
  27066. {
  27067. mSelectedSubTickPen = pen;
  27068. }
  27069. /*!
  27070. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  27071. bounds of the range. The range is simply moved by \a diff.
  27072. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  27073. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  27074. */
  27075. void QCPPolarAxisRadial::moveRange(double diff)
  27076. {
  27077. QCPRange oldRange = mRange;
  27078. if (mScaleType == stLinear)
  27079. {
  27080. mRange.lower += diff;
  27081. mRange.upper += diff;
  27082. } else // mScaleType == stLogarithmic
  27083. {
  27084. mRange.lower *= diff;
  27085. mRange.upper *= diff;
  27086. }
  27087. Q_EMIT rangeChanged(mRange);
  27088. Q_EMIT rangeChanged(mRange, oldRange);
  27089. }
  27090. /*!
  27091. Scales the range of this axis by \a factor around the center of the current axis range. For
  27092. example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
  27093. range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
  27094. the center will have moved symmetrically closer).
  27095. If you wish to scale around a different coordinate than the current axis range center, use the
  27096. overload \ref scaleRange(double factor, double center).
  27097. */
  27098. void QCPPolarAxisRadial::scaleRange(double factor)
  27099. {
  27100. scaleRange(factor, range().center());
  27101. }
  27102. /*! \overload
  27103. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  27104. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  27105. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  27106. around 1.0 will have moved symmetrically closer to 1.0).
  27107. \see scaleRange(double factor)
  27108. */
  27109. void QCPPolarAxisRadial::scaleRange(double factor, double center)
  27110. {
  27111. QCPRange oldRange = mRange;
  27112. if (mScaleType == stLinear)
  27113. {
  27114. QCPRange newRange;
  27115. newRange.lower = (mRange.lower-center)*factor + center;
  27116. newRange.upper = (mRange.upper-center)*factor + center;
  27117. if (QCPRange::validRange(newRange))
  27118. mRange = newRange.sanitizedForLinScale();
  27119. } else // mScaleType == stLogarithmic
  27120. {
  27121. if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
  27122. {
  27123. QCPRange newRange;
  27124. newRange.lower = qPow(mRange.lower/center, factor)*center;
  27125. newRange.upper = qPow(mRange.upper/center, factor)*center;
  27126. if (QCPRange::validRange(newRange))
  27127. mRange = newRange.sanitizedForLogScale();
  27128. } else
  27129. qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
  27130. }
  27131. Q_EMIT rangeChanged(mRange);
  27132. Q_EMIT rangeChanged(mRange, oldRange);
  27133. }
  27134. /*!
  27135. Changes the axis range such that all plottables associated with this axis are fully visible in
  27136. that dimension.
  27137. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  27138. */
  27139. void QCPPolarAxisRadial::rescale(bool onlyVisiblePlottables)
  27140. {
  27141. Q_UNUSED(onlyVisiblePlottables)
  27142. /* TODO
  27143. QList<QCPAbstractPlottable*> p = plottables();
  27144. QCPRange newRange;
  27145. bool haveRange = false;
  27146. for (int i=0; i<p.size(); ++i)
  27147. {
  27148. if (!p.at(i)->realVisibility() && onlyVisiblePlottables)
  27149. continue;
  27150. QCPRange plottableRange;
  27151. bool currentFoundRange;
  27152. QCP::SignDomain signDomain = QCP::sdBoth;
  27153. if (mScaleType == stLogarithmic)
  27154. signDomain = (mRange.upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  27155. if (p.at(i)->keyAxis() == this)
  27156. plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain);
  27157. else
  27158. plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain);
  27159. if (currentFoundRange)
  27160. {
  27161. if (!haveRange)
  27162. newRange = plottableRange;
  27163. else
  27164. newRange.expand(plottableRange);
  27165. haveRange = true;
  27166. }
  27167. }
  27168. if (haveRange)
  27169. {
  27170. if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
  27171. {
  27172. double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
  27173. if (mScaleType == stLinear)
  27174. {
  27175. newRange.lower = center-mRange.size()/2.0;
  27176. newRange.upper = center+mRange.size()/2.0;
  27177. } else // mScaleType == stLogarithmic
  27178. {
  27179. newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
  27180. newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
  27181. }
  27182. }
  27183. setRange(newRange);
  27184. }
  27185. */
  27186. }
  27187. /*!
  27188. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  27189. */
  27190. void QCPPolarAxisRadial::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const
  27191. {
  27192. QCPVector2D posVector(pixelPos-mCenter);
  27193. radiusCoord = radiusToCoord(posVector.length());
  27194. angleCoord = mAngularAxis->angleRadToCoord(posVector.angle());
  27195. }
  27196. /*!
  27197. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  27198. */
  27199. QPointF QCPPolarAxisRadial::coordToPixel(double angleCoord, double radiusCoord) const
  27200. {
  27201. const double radiusPixel = coordToRadius(radiusCoord);
  27202. const double angleRad = mAngularAxis->coordToAngleRad(angleCoord);
  27203. return QPointF(mCenter.x()+qCos(angleRad)*radiusPixel, mCenter.y()+qSin(angleRad)*radiusPixel);
  27204. }
  27205. double QCPPolarAxisRadial::coordToRadius(double coord) const
  27206. {
  27207. if (mScaleType == stLinear)
  27208. {
  27209. if (!mRangeReversed)
  27210. return (coord-mRange.lower)/mRange.size()*mRadius;
  27211. else
  27212. return (mRange.upper-coord)/mRange.size()*mRadius;
  27213. } else // mScaleType == stLogarithmic
  27214. {
  27215. if (coord >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just return outside visible range
  27216. return !mRangeReversed ? mRadius+200 : mRadius-200;
  27217. else if (coord <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just return outside visible range
  27218. return !mRangeReversed ? mRadius-200 :mRadius+200;
  27219. else
  27220. {
  27221. if (!mRangeReversed)
  27222. return qLn(coord/mRange.lower)/qLn(mRange.upper/mRange.lower)*mRadius;
  27223. else
  27224. return qLn(mRange.upper/coord)/qLn(mRange.upper/mRange.lower)*mRadius;
  27225. }
  27226. }
  27227. }
  27228. double QCPPolarAxisRadial::radiusToCoord(double radius) const
  27229. {
  27230. if (mScaleType == stLinear)
  27231. {
  27232. if (!mRangeReversed)
  27233. return (radius)/mRadius*mRange.size()+mRange.lower;
  27234. else
  27235. return -(radius)/mRadius*mRange.size()+mRange.upper;
  27236. } else // mScaleType == stLogarithmic
  27237. {
  27238. if (!mRangeReversed)
  27239. return qPow(mRange.upper/mRange.lower, (radius)/mRadius)*mRange.lower;
  27240. else
  27241. return qPow(mRange.upper/mRange.lower, (-radius)/mRadius)*mRange.upper;
  27242. }
  27243. }
  27244. /*!
  27245. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  27246. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  27247. function does not change the current selection state of the axis.
  27248. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  27249. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  27250. */
  27251. QCPPolarAxisRadial::SelectablePart QCPPolarAxisRadial::getPartAt(const QPointF &pos) const
  27252. {
  27253. Q_UNUSED(pos) // TODO remove later
  27254. if (!mVisible)
  27255. return spNone;
  27256. /*
  27257. TODO:
  27258. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  27259. return spAxis;
  27260. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  27261. return spTickLabels;
  27262. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  27263. return spAxisLabel;
  27264. else */
  27265. return spNone;
  27266. }
  27267. /* inherits documentation from base class */
  27268. double QCPPolarAxisRadial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  27269. {
  27270. if (!mParentPlot) return -1;
  27271. SelectablePart part = getPartAt(pos);
  27272. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  27273. return -1;
  27274. if (details)
  27275. details->setValue(part);
  27276. return mParentPlot->selectionTolerance()*0.99;
  27277. }
  27278. /* inherits documentation from base class */
  27279. void QCPPolarAxisRadial::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  27280. {
  27281. Q_UNUSED(event)
  27282. SelectablePart part = details.value<SelectablePart>();
  27283. if (mSelectableParts.testFlag(part))
  27284. {
  27285. SelectableParts selBefore = mSelectedParts;
  27286. setSelectedParts(additive ? mSelectedParts^part : part);
  27287. if (selectionStateChanged)
  27288. *selectionStateChanged = mSelectedParts != selBefore;
  27289. }
  27290. }
  27291. /* inherits documentation from base class */
  27292. void QCPPolarAxisRadial::deselectEvent(bool *selectionStateChanged)
  27293. {
  27294. SelectableParts selBefore = mSelectedParts;
  27295. setSelectedParts(mSelectedParts & ~mSelectableParts);
  27296. if (selectionStateChanged)
  27297. *selectionStateChanged = mSelectedParts != selBefore;
  27298. }
  27299. /*! \internal
  27300. This mouse event reimplementation provides the functionality to let the user drag individual axes
  27301. exclusively, by startig the drag on top of the axis.
  27302. For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect
  27303. must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis
  27304. (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref
  27305. QCPAxisRect::setRangeDragAxes)
  27306. \seebaseclassmethod
  27307. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  27308. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  27309. */
  27310. void QCPPolarAxisRadial::mousePressEvent(QMouseEvent *event, const QVariant &details)
  27311. {
  27312. Q_UNUSED(details)
  27313. if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  27314. {
  27315. event->ignore();
  27316. return;
  27317. }
  27318. if (event->buttons() & Qt::LeftButton)
  27319. {
  27320. mDragging = true;
  27321. // initialize antialiasing backup in case we start dragging:
  27322. if (mParentPlot->noAntialiasingOnDrag())
  27323. {
  27324. mAADragBackup = mParentPlot->antialiasedElements();
  27325. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  27326. }
  27327. // Mouse range dragging interaction:
  27328. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  27329. mDragStartRange = mRange;
  27330. }
  27331. }
  27332. /*! \internal
  27333. This mouse event reimplementation provides the functionality to let the user drag individual axes
  27334. exclusively, by startig the drag on top of the axis.
  27335. \seebaseclassmethod
  27336. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  27337. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  27338. \see QCPAxis::mousePressEvent
  27339. */
  27340. void QCPPolarAxisRadial::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  27341. {
  27342. Q_UNUSED(event) // TODO remove later
  27343. Q_UNUSED(startPos) // TODO remove later
  27344. if (mDragging)
  27345. {
  27346. /* TODO
  27347. const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y();
  27348. const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y();
  27349. if (mScaleType == QCPPolarAxisRadial::stLinear)
  27350. {
  27351. const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel);
  27352. setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff);
  27353. } else if (mScaleType == QCPPolarAxisRadial::stLogarithmic)
  27354. {
  27355. const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel);
  27356. setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff);
  27357. }
  27358. */
  27359. if (mParentPlot->noAntialiasingOnDrag())
  27360. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  27361. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  27362. }
  27363. }
  27364. /*! \internal
  27365. This mouse event reimplementation provides the functionality to let the user drag individual axes
  27366. exclusively, by startig the drag on top of the axis.
  27367. \seebaseclassmethod
  27368. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  27369. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  27370. \see QCPAxis::mousePressEvent
  27371. */
  27372. void QCPPolarAxisRadial::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  27373. {
  27374. Q_UNUSED(event)
  27375. Q_UNUSED(startPos)
  27376. mDragging = false;
  27377. if (mParentPlot->noAntialiasingOnDrag())
  27378. {
  27379. mParentPlot->setAntialiasedElements(mAADragBackup);
  27380. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  27381. }
  27382. }
  27383. /*! \internal
  27384. This mouse event reimplementation provides the functionality to let the user zoom individual axes
  27385. exclusively, by performing the wheel event on top of the axis.
  27386. For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect
  27387. must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis
  27388. (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref
  27389. QCPAxisRect::setRangeZoomAxes)
  27390. \seebaseclassmethod
  27391. \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the
  27392. axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent.
  27393. */
  27394. void QCPPolarAxisRadial::wheelEvent(QWheelEvent *event)
  27395. {
  27396. // Mouse range zooming interaction:
  27397. if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  27398. {
  27399. event->ignore();
  27400. return;
  27401. }
  27402. // TODO:
  27403. //const double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually
  27404. //const double factor = qPow(mRangeZoomFactor, wheelSteps);
  27405. //scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y()));
  27406. mParentPlot->replot();
  27407. }
  27408. void QCPPolarAxisRadial::updateGeometry(const QPointF &center, double radius)
  27409. {
  27410. mCenter = center;
  27411. mRadius = radius;
  27412. if (mRadius < 1) mRadius = 1;
  27413. }
  27414. /*! \internal
  27415. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  27416. before drawing axis lines.
  27417. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  27418. This function takes into account the local setting of the antialiasing flag as well as the
  27419. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  27420. QCustomPlot::setNotAntialiasedElements.
  27421. \seebaseclassmethod
  27422. \see setAntialiased
  27423. */
  27424. void QCPPolarAxisRadial::applyDefaultAntialiasingHint(QCPPainter *painter) const
  27425. {
  27426. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  27427. }
  27428. /*! \internal
  27429. Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
  27430. \seebaseclassmethod
  27431. */
  27432. void QCPPolarAxisRadial::draw(QCPPainter *painter)
  27433. {
  27434. const double axisAngleRad = (mAngle+(mAngleReference==arAngularAxis ? mAngularAxis->angle() : 0))/180.0*M_PI;
  27435. const QPointF axisVector(qCos(axisAngleRad), qSin(axisAngleRad)); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF
  27436. const QPointF tickNormal = QCPVector2D(axisVector).perpendicular().toPointF(); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF
  27437. // draw baseline:
  27438. painter->setPen(getBasePen());
  27439. painter->drawLine(QLineF(mCenter, mCenter+axisVector*(mRadius-0.5)));
  27440. // draw subticks:
  27441. if (!mSubTickVector.isEmpty())
  27442. {
  27443. painter->setPen(getSubTickPen());
  27444. for (int i=0; i<mSubTickVector.size(); ++i)
  27445. {
  27446. const QPointF tickPosition = mCenter+axisVector*coordToRadius(mSubTickVector.at(i));
  27447. painter->drawLine(QLineF(tickPosition-tickNormal*mSubTickLengthIn, tickPosition+tickNormal*mSubTickLengthOut));
  27448. }
  27449. }
  27450. // draw ticks and labels:
  27451. if (!mTickVector.isEmpty())
  27452. {
  27453. mLabelPainter.setAnchorReference(mCenter-axisVector); // subtract (normalized) axisVector, just to prevent degenerate tangents for tick label at exact lower axis range
  27454. mLabelPainter.setFont(getTickLabelFont());
  27455. mLabelPainter.setColor(getTickLabelColor());
  27456. const QPen ticksPen = getTickPen();
  27457. painter->setPen(ticksPen);
  27458. for (int i=0; i<mTickVector.size(); ++i)
  27459. {
  27460. const double r = coordToRadius(mTickVector.at(i));
  27461. const QPointF tickPosition = mCenter+axisVector*r;
  27462. painter->drawLine(QLineF(tickPosition-tickNormal*mTickLengthIn, tickPosition+tickNormal*mTickLengthOut));
  27463. // possibly draw tick labels:
  27464. if (!mTickVectorLabels.isEmpty())
  27465. {
  27466. if ((!mRangeReversed && (i < mTickVectorLabels.count()-1 || mRadius-r > 10)) ||
  27467. (mRangeReversed && (i > 0 || mRadius-r > 10))) // skip last label if it's closer than 10 pixels to angular axis
  27468. mLabelPainter.drawTickLabel(painter, tickPosition+tickNormal*mSubTickLengthOut, mTickVectorLabels.at(i));
  27469. }
  27470. }
  27471. }
  27472. }
  27473. /*! \internal
  27474. Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
  27475. QCPAxisTicker::generate on the currently installed ticker.
  27476. If a change in the label text/count is detected, the cached axis margin is invalidated to make
  27477. sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
  27478. */
  27479. void QCPPolarAxisRadial::setupTickVectors()
  27480. {
  27481. if (!mParentPlot) return;
  27482. if ((!mTicks && !mTickLabels) || mRange.size() <= 0) return;
  27483. mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0);
  27484. }
  27485. /*! \internal
  27486. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  27487. is either mSelectedBasePen or mBasePen.
  27488. */
  27489. QPen QCPPolarAxisRadial::getBasePen() const
  27490. {
  27491. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  27492. }
  27493. /*! \internal
  27494. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  27495. is either mSelectedTickPen or mTickPen.
  27496. */
  27497. QPen QCPPolarAxisRadial::getTickPen() const
  27498. {
  27499. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  27500. }
  27501. /*! \internal
  27502. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  27503. is either mSelectedSubTickPen or mSubTickPen.
  27504. */
  27505. QPen QCPPolarAxisRadial::getSubTickPen() const
  27506. {
  27507. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  27508. }
  27509. /*! \internal
  27510. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  27511. is either mSelectedTickLabelFont or mTickLabelFont.
  27512. */
  27513. QFont QCPPolarAxisRadial::getTickLabelFont() const
  27514. {
  27515. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  27516. }
  27517. /*! \internal
  27518. Returns the font that is used to draw the axis label. Depending on the selection state, this
  27519. is either mSelectedLabelFont or mLabelFont.
  27520. */
  27521. QFont QCPPolarAxisRadial::getLabelFont() const
  27522. {
  27523. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  27524. }
  27525. /*! \internal
  27526. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  27527. is either mSelectedTickLabelColor or mTickLabelColor.
  27528. */
  27529. QColor QCPPolarAxisRadial::getTickLabelColor() const
  27530. {
  27531. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  27532. }
  27533. /*! \internal
  27534. Returns the color that is used to draw the axis label. Depending on the selection state, this
  27535. is either mSelectedLabelColor or mLabelColor.
  27536. */
  27537. QColor QCPPolarAxisRadial::getLabelColor() const
  27538. {
  27539. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  27540. }
  27541. /* inherits documentation from base class */
  27542. QCP::Interaction QCPPolarAxisRadial::selectionCategory() const
  27543. {
  27544. return QCP::iSelectAxes;
  27545. }
  27546. /* end of 'src/polar/radialaxis.cpp' */
  27547. /* including file 'src/polar/layoutelement-angularaxis.cpp' */
  27548. /* modified 2021-03-29T02:30:44, size 57266 */
  27549. ////////////////////////////////////////////////////////////////////////////////////////////////////
  27550. //////////////////// QCPPolarAxisAngular
  27551. ////////////////////////////////////////////////////////////////////////////////////////////////////
  27552. /*! \class QCPPolarAxisAngular
  27553. \brief The main container for polar plots, representing the angular axis as a circle
  27554. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  27555. functionality to be incomplete, as well as changing public interfaces in the future.
  27556. */
  27557. /* start documentation of inline functions */
  27558. /*! \fn QCPLayoutInset *QCPPolarAxisAngular::insetLayout() const
  27559. Returns the inset layout of this axis rect. It can be used to place other layout elements (or
  27560. even layouts with multiple other elements) inside/on top of an axis rect.
  27561. \see QCPLayoutInset
  27562. */
  27563. /*! \fn int QCPPolarAxisAngular::left() const
  27564. Returns the pixel position of the left border of this axis rect. Margins are not taken into
  27565. account here, so the returned value is with respect to the inner \ref rect.
  27566. */
  27567. /*! \fn int QCPPolarAxisAngular::right() const
  27568. Returns the pixel position of the right border of this axis rect. Margins are not taken into
  27569. account here, so the returned value is with respect to the inner \ref rect.
  27570. */
  27571. /*! \fn int QCPPolarAxisAngular::top() const
  27572. Returns the pixel position of the top border of this axis rect. Margins are not taken into
  27573. account here, so the returned value is with respect to the inner \ref rect.
  27574. */
  27575. /*! \fn int QCPPolarAxisAngular::bottom() const
  27576. Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
  27577. account here, so the returned value is with respect to the inner \ref rect.
  27578. */
  27579. /*! \fn int QCPPolarAxisAngular::width() const
  27580. Returns the pixel width of this axis rect. Margins are not taken into account here, so the
  27581. returned value is with respect to the inner \ref rect.
  27582. */
  27583. /*! \fn int QCPPolarAxisAngular::height() const
  27584. Returns the pixel height of this axis rect. Margins are not taken into account here, so the
  27585. returned value is with respect to the inner \ref rect.
  27586. */
  27587. /*! \fn QSize QCPPolarAxisAngular::size() const
  27588. Returns the pixel size of this axis rect. Margins are not taken into account here, so the
  27589. returned value is with respect to the inner \ref rect.
  27590. */
  27591. /*! \fn QPoint QCPPolarAxisAngular::topLeft() const
  27592. Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
  27593. so the returned value is with respect to the inner \ref rect.
  27594. */
  27595. /*! \fn QPoint QCPPolarAxisAngular::topRight() const
  27596. Returns the top right corner of this axis rect in pixels. Margins are not taken into account
  27597. here, so the returned value is with respect to the inner \ref rect.
  27598. */
  27599. /*! \fn QPoint QCPPolarAxisAngular::bottomLeft() const
  27600. Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
  27601. here, so the returned value is with respect to the inner \ref rect.
  27602. */
  27603. /*! \fn QPoint QCPPolarAxisAngular::bottomRight() const
  27604. Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
  27605. here, so the returned value is with respect to the inner \ref rect.
  27606. */
  27607. /*! \fn QPoint QCPPolarAxisAngular::center() const
  27608. Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
  27609. returned value is with respect to the inner \ref rect.
  27610. */
  27611. /* end documentation of inline functions */
  27612. /*!
  27613. Creates a QCPPolarAxis instance and sets default values. An axis is added for each of the four
  27614. sides, the top and right axes are set invisible initially.
  27615. */
  27616. QCPPolarAxisAngular::QCPPolarAxisAngular(QCustomPlot *parentPlot) :
  27617. QCPLayoutElement(parentPlot),
  27618. mBackgroundBrush(Qt::NoBrush),
  27619. mBackgroundScaled(true),
  27620. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  27621. mInsetLayout(new QCPLayoutInset),
  27622. mRangeDrag(false),
  27623. mRangeZoom(false),
  27624. mRangeZoomFactor(0.85),
  27625. // axis base:
  27626. mAngle(-90),
  27627. mAngleRad(mAngle/180.0*M_PI),
  27628. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  27629. mSelectedParts(spNone),
  27630. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  27631. mSelectedBasePen(QPen(Qt::blue, 2)),
  27632. // axis label:
  27633. mLabelPadding(0),
  27634. mLabel(),
  27635. mLabelFont(mParentPlot->font()),
  27636. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  27637. mLabelColor(Qt::black),
  27638. mSelectedLabelColor(Qt::blue),
  27639. // tick labels:
  27640. //mTickLabelPadding(0), in label painter
  27641. mTickLabels(true),
  27642. //mTickLabelRotation(0), in label painter
  27643. mTickLabelFont(mParentPlot->font()),
  27644. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  27645. mTickLabelColor(Qt::black),
  27646. mSelectedTickLabelColor(Qt::blue),
  27647. mNumberPrecision(6),
  27648. mNumberFormatChar('g'),
  27649. mNumberBeautifulPowers(true),
  27650. mNumberMultiplyCross(false),
  27651. // ticks and subticks:
  27652. mTicks(true),
  27653. mSubTicks(true),
  27654. mTickLengthIn(5),
  27655. mTickLengthOut(0),
  27656. mSubTickLengthIn(2),
  27657. mSubTickLengthOut(0),
  27658. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  27659. mSelectedTickPen(QPen(Qt::blue, 2)),
  27660. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  27661. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  27662. // scale and range:
  27663. mRange(0, 360),
  27664. mRangeReversed(false),
  27665. // internal members:
  27666. mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect
  27667. mGrid(new QCPPolarGrid(this)),
  27668. mTicker(new QCPAxisTickerFixed),
  27669. mDragging(false),
  27670. mLabelPainter(parentPlot)
  27671. {
  27672. // TODO:
  27673. //mInsetLayout->initializeParentPlot(mParentPlot);
  27674. //mInsetLayout->setParentLayerable(this);
  27675. //mInsetLayout->setParent(this);
  27676. if (QCPAxisTickerFixed *fixedTicker = mTicker.dynamicCast<QCPAxisTickerFixed>().data())
  27677. {
  27678. fixedTicker->setTickStep(30);
  27679. }
  27680. setAntialiased(true);
  27681. setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again
  27682. setTickLabelPadding(5);
  27683. setTickLabelRotation(0);
  27684. setTickLabelMode(lmUpright);
  27685. mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::artNormal);
  27686. mLabelPainter.setAbbreviateDecimalPowers(false);
  27687. mLabelPainter.setCacheSize(24); // so we can cache up to 15-degree intervals, polar angular axis uses a bit larger cache than normal axes
  27688. setMinimumSize(50, 50);
  27689. setMinimumMargins(QMargins(30, 30, 30, 30));
  27690. addRadialAxis();
  27691. mGrid->setRadialAxis(radialAxis());
  27692. }
  27693. QCPPolarAxisAngular::~QCPPolarAxisAngular()
  27694. {
  27695. delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
  27696. mGrid = 0;
  27697. delete mInsetLayout;
  27698. mInsetLayout = 0;
  27699. QList<QCPPolarAxisRadial*> radialAxesList = radialAxes();
  27700. for (int i=0; i<radialAxesList.size(); ++i)
  27701. removeRadialAxis(radialAxesList.at(i));
  27702. }
  27703. QCPPolarAxisAngular::LabelMode QCPPolarAxisAngular::tickLabelMode() const
  27704. {
  27705. switch (mLabelPainter.anchorMode())
  27706. {
  27707. case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright;
  27708. case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated;
  27709. default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break;
  27710. }
  27711. return lmUpright;
  27712. }
  27713. /* No documentation as it is a property getter */
  27714. QString QCPPolarAxisAngular::numberFormat() const
  27715. {
  27716. QString result;
  27717. result.append(mNumberFormatChar);
  27718. if (mNumberBeautifulPowers)
  27719. {
  27720. result.append(QLatin1Char('b'));
  27721. if (mLabelPainter.multiplicationSymbol() == QCPLabelPainterPrivate::SymbolCross)
  27722. result.append(QLatin1Char('c'));
  27723. }
  27724. return result;
  27725. }
  27726. /*!
  27727. Returns the number of axes on the axis rect side specified with \a type.
  27728. \see axis
  27729. */
  27730. int QCPPolarAxisAngular::radialAxisCount() const
  27731. {
  27732. return mRadialAxes.size();
  27733. }
  27734. /*!
  27735. Returns the axis with the given \a index on the axis rect side specified with \a type.
  27736. \see axisCount, axes
  27737. */
  27738. QCPPolarAxisRadial *QCPPolarAxisAngular::radialAxis(int index) const
  27739. {
  27740. if (index >= 0 && index < mRadialAxes.size())
  27741. {
  27742. return mRadialAxes.at(index);
  27743. } else
  27744. {
  27745. qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
  27746. return 0;
  27747. }
  27748. }
  27749. /*!
  27750. Returns all axes on the axis rect sides specified with \a types.
  27751. \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
  27752. multiple sides.
  27753. \see axis
  27754. */
  27755. QList<QCPPolarAxisRadial*> QCPPolarAxisAngular::radialAxes() const
  27756. {
  27757. return mRadialAxes;
  27758. }
  27759. /*!
  27760. Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
  27761. new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
  27762. remove an axis, use \ref removeAxis instead of deleting it manually.
  27763. You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was
  27764. previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
  27765. of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
  27766. with this axis rect as parent and with the same axis type as specified in \a type. If this is not
  27767. the case, a debug output is generated, the axis is not added, and the method returns 0.
  27768. This method can not be used to move \a axis between axis rects. The same \a axis instance must
  27769. not be added multiple times to the same or different axis rects.
  27770. If an axis rect side already contains one or more axes, the lower and upper endings of the new
  27771. axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
  27772. QCPLineEnding::esHalfBar.
  27773. \see addAxes, setupFullAxesBox
  27774. */
  27775. QCPPolarAxisRadial *QCPPolarAxisAngular::addRadialAxis(QCPPolarAxisRadial *axis)
  27776. {
  27777. QCPPolarAxisRadial *newAxis = axis;
  27778. if (!newAxis)
  27779. {
  27780. newAxis = new QCPPolarAxisRadial(this);
  27781. } else // user provided existing axis instance, do some sanity checks
  27782. {
  27783. if (newAxis->angularAxis() != this)
  27784. {
  27785. qDebug() << Q_FUNC_INFO << "passed radial axis doesn't have this angular axis as parent angular axis";
  27786. return 0;
  27787. }
  27788. if (radialAxes().contains(newAxis))
  27789. {
  27790. qDebug() << Q_FUNC_INFO << "passed axis is already owned by this angular axis";
  27791. return 0;
  27792. }
  27793. }
  27794. mRadialAxes.append(newAxis);
  27795. return newAxis;
  27796. }
  27797. /*!
  27798. Removes the specified \a axis from the axis rect and deletes it.
  27799. Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
  27800. \see addAxis
  27801. */
  27802. bool QCPPolarAxisAngular::removeRadialAxis(QCPPolarAxisRadial *radialAxis)
  27803. {
  27804. if (mRadialAxes.contains(radialAxis))
  27805. {
  27806. mRadialAxes.removeOne(radialAxis);
  27807. delete radialAxis;
  27808. return true;
  27809. } else
  27810. {
  27811. qDebug() << Q_FUNC_INFO << "Radial axis isn't associated with this angular axis:" << reinterpret_cast<quintptr>(radialAxis);
  27812. return false;
  27813. }
  27814. }
  27815. QRegion QCPPolarAxisAngular::exactClipRegion() const
  27816. {
  27817. return QRegion(mCenter.x()-mRadius, mCenter.y()-mRadius, qRound(2*mRadius), qRound(2*mRadius), QRegion::Ellipse);
  27818. }
  27819. /*!
  27820. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  27821. bounds of the range. The range is simply moved by \a diff.
  27822. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  27823. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  27824. */
  27825. void QCPPolarAxisAngular::moveRange(double diff)
  27826. {
  27827. QCPRange oldRange = mRange;
  27828. mRange.lower += diff;
  27829. mRange.upper += diff;
  27830. Q_EMIT rangeChanged(mRange);
  27831. Q_EMIT rangeChanged(mRange, oldRange);
  27832. }
  27833. /*!
  27834. Scales the range of this axis by \a factor around the center of the current axis range. For
  27835. example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
  27836. range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
  27837. the center will have moved symmetrically closer).
  27838. If you wish to scale around a different coordinate than the current axis range center, use the
  27839. overload \ref scaleRange(double factor, double center).
  27840. */
  27841. void QCPPolarAxisAngular::scaleRange(double factor)
  27842. {
  27843. scaleRange(factor, range().center());
  27844. }
  27845. /*! \overload
  27846. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  27847. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  27848. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  27849. around 1.0 will have moved symmetrically closer to 1.0).
  27850. \see scaleRange(double factor)
  27851. */
  27852. void QCPPolarAxisAngular::scaleRange(double factor, double center)
  27853. {
  27854. QCPRange oldRange = mRange;
  27855. QCPRange newRange;
  27856. newRange.lower = (mRange.lower-center)*factor + center;
  27857. newRange.upper = (mRange.upper-center)*factor + center;
  27858. if (QCPRange::validRange(newRange))
  27859. mRange = newRange.sanitizedForLinScale();
  27860. Q_EMIT rangeChanged(mRange);
  27861. Q_EMIT rangeChanged(mRange, oldRange);
  27862. }
  27863. /*!
  27864. Changes the axis range such that all plottables associated with this axis are fully visible in
  27865. that dimension.
  27866. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  27867. */
  27868. void QCPPolarAxisAngular::rescale(bool onlyVisiblePlottables)
  27869. {
  27870. QCPRange newRange;
  27871. bool haveRange = false;
  27872. for (int i=0; i<mGraphs.size(); ++i)
  27873. {
  27874. if (!mGraphs.at(i)->realVisibility() && onlyVisiblePlottables)
  27875. continue;
  27876. QCPRange range;
  27877. bool currentFoundRange;
  27878. if (mGraphs.at(i)->keyAxis() == this)
  27879. range = mGraphs.at(i)->getKeyRange(currentFoundRange, QCP::sdBoth);
  27880. else
  27881. range = mGraphs.at(i)->getValueRange(currentFoundRange, QCP::sdBoth);
  27882. if (currentFoundRange)
  27883. {
  27884. if (!haveRange)
  27885. newRange = range;
  27886. else
  27887. newRange.expand(range);
  27888. haveRange = true;
  27889. }
  27890. }
  27891. if (haveRange)
  27892. {
  27893. if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
  27894. {
  27895. double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
  27896. newRange.lower = center-mRange.size()/2.0;
  27897. newRange.upper = center+mRange.size()/2.0;
  27898. }
  27899. setRange(newRange);
  27900. }
  27901. }
  27902. /*!
  27903. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  27904. */
  27905. void QCPPolarAxisAngular::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const
  27906. {
  27907. if (!mRadialAxes.isEmpty())
  27908. mRadialAxes.first()->pixelToCoord(pixelPos, angleCoord, radiusCoord);
  27909. else
  27910. qDebug() << Q_FUNC_INFO << "no radial axis configured";
  27911. }
  27912. /*!
  27913. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  27914. */
  27915. QPointF QCPPolarAxisAngular::coordToPixel(double angleCoord, double radiusCoord) const
  27916. {
  27917. if (!mRadialAxes.isEmpty())
  27918. {
  27919. return mRadialAxes.first()->coordToPixel(angleCoord, radiusCoord);
  27920. } else
  27921. {
  27922. qDebug() << Q_FUNC_INFO << "no radial axis configured";
  27923. return QPointF();
  27924. }
  27925. }
  27926. /*!
  27927. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  27928. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  27929. function does not change the current selection state of the axis.
  27930. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  27931. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  27932. */
  27933. QCPPolarAxisAngular::SelectablePart QCPPolarAxisAngular::getPartAt(const QPointF &pos) const
  27934. {
  27935. Q_UNUSED(pos) // TODO remove later
  27936. if (!mVisible)
  27937. return spNone;
  27938. /*
  27939. TODO:
  27940. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  27941. return spAxis;
  27942. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  27943. return spTickLabels;
  27944. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  27945. return spAxisLabel;
  27946. else */
  27947. return spNone;
  27948. }
  27949. /* inherits documentation from base class */
  27950. double QCPPolarAxisAngular::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  27951. {
  27952. /*
  27953. if (!mParentPlot) return -1;
  27954. SelectablePart part = getPartAt(pos);
  27955. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  27956. return -1;
  27957. if (details)
  27958. details->setValue(part);
  27959. return mParentPlot->selectionTolerance()*0.99;
  27960. */
  27961. Q_UNUSED(details)
  27962. if (onlySelectable)
  27963. return -1;
  27964. if (QRectF(mOuterRect).contains(pos))
  27965. {
  27966. if (mParentPlot)
  27967. return mParentPlot->selectionTolerance()*0.99;
  27968. else
  27969. {
  27970. qDebug() << Q_FUNC_INFO << "parent plot not defined";
  27971. return -1;
  27972. }
  27973. } else
  27974. return -1;
  27975. }
  27976. /*!
  27977. This method is called automatically upon replot and doesn't need to be called by users of
  27978. QCPPolarAxisAngular.
  27979. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
  27980. and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
  27981. QCPInsetLayout::update function.
  27982. \seebaseclassmethod
  27983. */
  27984. void QCPPolarAxisAngular::update(UpdatePhase phase)
  27985. {
  27986. QCPLayoutElement::update(phase);
  27987. switch (phase)
  27988. {
  27989. case upPreparation:
  27990. {
  27991. setupTickVectors();
  27992. for (int i=0; i<mRadialAxes.size(); ++i)
  27993. mRadialAxes.at(i)->setupTickVectors();
  27994. break;
  27995. }
  27996. case upLayout:
  27997. {
  27998. mCenter = mRect.center();
  27999. mRadius = 0.5*qMin(qAbs(mRect.width()), qAbs(mRect.height()));
  28000. if (mRadius < 1) mRadius = 1; // prevent cases where radius might become 0 which causes trouble
  28001. for (int i=0; i<mRadialAxes.size(); ++i)
  28002. mRadialAxes.at(i)->updateGeometry(mCenter, mRadius);
  28003. mInsetLayout->setOuterRect(rect());
  28004. break;
  28005. }
  28006. default: break;
  28007. }
  28008. // pass update call on to inset layout (doesn't happen automatically, because QCPPolarAxis doesn't derive from QCPLayout):
  28009. mInsetLayout->update(phase);
  28010. }
  28011. /* inherits documentation from base class */
  28012. QList<QCPLayoutElement*> QCPPolarAxisAngular::elements(bool recursive) const
  28013. {
  28014. QList<QCPLayoutElement*> result;
  28015. if (mInsetLayout)
  28016. {
  28017. result << mInsetLayout;
  28018. if (recursive)
  28019. result << mInsetLayout->elements(recursive);
  28020. }
  28021. return result;
  28022. }
  28023. bool QCPPolarAxisAngular::removeGraph(QCPPolarGraph *graph)
  28024. {
  28025. if (!mGraphs.contains(graph))
  28026. {
  28027. qDebug() << Q_FUNC_INFO << "graph not in list:" << reinterpret_cast<quintptr>(graph);
  28028. return false;
  28029. }
  28030. // remove plottable from legend:
  28031. graph->removeFromLegend();
  28032. // remove plottable:
  28033. delete graph;
  28034. mGraphs.removeOne(graph);
  28035. return true;
  28036. }
  28037. /* inherits documentation from base class */
  28038. void QCPPolarAxisAngular::applyDefaultAntialiasingHint(QCPPainter *painter) const
  28039. {
  28040. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  28041. }
  28042. /* inherits documentation from base class */
  28043. void QCPPolarAxisAngular::draw(QCPPainter *painter)
  28044. {
  28045. drawBackground(painter, mCenter, mRadius);
  28046. // draw baseline circle:
  28047. painter->setPen(getBasePen());
  28048. painter->drawEllipse(mCenter, mRadius, mRadius);
  28049. // draw subticks:
  28050. if (!mSubTickVector.isEmpty())
  28051. {
  28052. painter->setPen(getSubTickPen());
  28053. for (int i=0; i<mSubTickVector.size(); ++i)
  28054. {
  28055. painter->drawLine(mCenter+mSubTickVectorCosSin.at(i)*(mRadius-mSubTickLengthIn),
  28056. mCenter+mSubTickVectorCosSin.at(i)*(mRadius+mSubTickLengthOut));
  28057. }
  28058. }
  28059. // draw ticks and labels:
  28060. if (!mTickVector.isEmpty())
  28061. {
  28062. mLabelPainter.setAnchorReference(mCenter);
  28063. mLabelPainter.setFont(getTickLabelFont());
  28064. mLabelPainter.setColor(getTickLabelColor());
  28065. const QPen ticksPen = getTickPen();
  28066. painter->setPen(ticksPen);
  28067. for (int i=0; i<mTickVector.size(); ++i)
  28068. {
  28069. const QPointF outerTick = mCenter+mTickVectorCosSin.at(i)*(mRadius+mTickLengthOut);
  28070. painter->drawLine(mCenter+mTickVectorCosSin.at(i)*(mRadius-mTickLengthIn), outerTick);
  28071. // draw tick labels:
  28072. if (!mTickVectorLabels.isEmpty())
  28073. {
  28074. if (i < mTickVectorLabels.count()-1 || (mTickVectorCosSin.at(i)-mTickVectorCosSin.first()).manhattanLength() > 5/180.0*M_PI) // skip last label if it's closer than approx 5 degrees to first
  28075. mLabelPainter.drawTickLabel(painter, outerTick, mTickVectorLabels.at(i));
  28076. }
  28077. }
  28078. }
  28079. }
  28080. /* inherits documentation from base class */
  28081. QCP::Interaction QCPPolarAxisAngular::selectionCategory() const
  28082. {
  28083. return QCP::iSelectAxes;
  28084. }
  28085. /*!
  28086. Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
  28087. axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
  28088. backgrounds are usually drawn below everything else.
  28089. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
  28090. enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
  28091. is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  28092. consider using the overloaded version of this function.
  28093. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
  28094. setBackground(const QBrush &brush).
  28095. \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
  28096. */
  28097. void QCPPolarAxisAngular::setBackground(const QPixmap &pm)
  28098. {
  28099. mBackgroundPixmap = pm;
  28100. mScaledBackgroundPixmap = QPixmap();
  28101. }
  28102. /*! \overload
  28103. Sets \a brush as the background brush. The axis rect background will be filled with this brush.
  28104. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
  28105. are usually drawn below everything else.
  28106. The brush will be drawn before (under) any background pixmap, which may be specified with \ref
  28107. setBackground(const QPixmap &pm).
  28108. To disable drawing of a background brush, set \a brush to Qt::NoBrush.
  28109. \see setBackground(const QPixmap &pm)
  28110. */
  28111. void QCPPolarAxisAngular::setBackground(const QBrush &brush)
  28112. {
  28113. mBackgroundBrush = brush;
  28114. }
  28115. /*! \overload
  28116. Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
  28117. shall be scaled in one call.
  28118. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  28119. */
  28120. void QCPPolarAxisAngular::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  28121. {
  28122. mBackgroundPixmap = pm;
  28123. mScaledBackgroundPixmap = QPixmap();
  28124. mBackgroundScaled = scaled;
  28125. mBackgroundScaledMode = mode;
  28126. }
  28127. /*!
  28128. Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
  28129. is set to true, you may control whether and how the aspect ratio of the original pixmap is
  28130. preserved with \ref setBackgroundScaledMode.
  28131. Note that the scaled version of the original pixmap is buffered, so there is no performance
  28132. penalty on replots. (Except when the axis rect dimensions are changed continuously.)
  28133. \see setBackground, setBackgroundScaledMode
  28134. */
  28135. void QCPPolarAxisAngular::setBackgroundScaled(bool scaled)
  28136. {
  28137. mBackgroundScaled = scaled;
  28138. }
  28139. /*!
  28140. If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
  28141. define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
  28142. \see setBackground, setBackgroundScaled
  28143. */
  28144. void QCPPolarAxisAngular::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  28145. {
  28146. mBackgroundScaledMode = mode;
  28147. }
  28148. void QCPPolarAxisAngular::setRangeDrag(bool enabled)
  28149. {
  28150. mRangeDrag = enabled;
  28151. }
  28152. void QCPPolarAxisAngular::setRangeZoom(bool enabled)
  28153. {
  28154. mRangeZoom = enabled;
  28155. }
  28156. void QCPPolarAxisAngular::setRangeZoomFactor(double factor)
  28157. {
  28158. mRangeZoomFactor = factor;
  28159. }
  28160. /*!
  28161. Sets the range of the axis.
  28162. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  28163. is always synchronized with the other axis range, when it changes.
  28164. To invert the direction of an axis, use \ref setRangeReversed.
  28165. */
  28166. void QCPPolarAxisAngular::setRange(const QCPRange &range)
  28167. {
  28168. if (range.lower == mRange.lower && range.upper == mRange.upper)
  28169. return;
  28170. if (!QCPRange::validRange(range)) return;
  28171. QCPRange oldRange = mRange;
  28172. mRange = range.sanitizedForLinScale();
  28173. Q_EMIT rangeChanged(mRange);
  28174. Q_EMIT rangeChanged(mRange, oldRange);
  28175. }
  28176. /*!
  28177. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  28178. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  28179. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  28180. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  28181. directly.
  28182. \see SelectablePart, setSelectedParts
  28183. */
  28184. void QCPPolarAxisAngular::setSelectableParts(const SelectableParts &selectable)
  28185. {
  28186. if (mSelectableParts != selectable)
  28187. {
  28188. mSelectableParts = selectable;
  28189. Q_EMIT selectableChanged(mSelectableParts);
  28190. }
  28191. }
  28192. /*!
  28193. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  28194. is selected, it uses a different pen/font.
  28195. The entire selection mechanism for axes is handled automatically when \ref
  28196. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  28197. wish to change the selection state manually.
  28198. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  28199. Q_EMITs the \ref selectionChanged signal when \a selected is different from the previous selection state.
  28200. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  28201. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  28202. */
  28203. void QCPPolarAxisAngular::setSelectedParts(const SelectableParts &selected)
  28204. {
  28205. if (mSelectedParts != selected)
  28206. {
  28207. mSelectedParts = selected;
  28208. Q_EMIT selectionChanged(mSelectedParts);
  28209. }
  28210. }
  28211. /*!
  28212. \overload
  28213. Sets the lower and upper bound of the axis range.
  28214. To invert the direction of an axis, use \ref setRangeReversed.
  28215. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  28216. */
  28217. void QCPPolarAxisAngular::setRange(double lower, double upper)
  28218. {
  28219. if (lower == mRange.lower && upper == mRange.upper)
  28220. return;
  28221. if (!QCPRange::validRange(lower, upper)) return;
  28222. QCPRange oldRange = mRange;
  28223. mRange.lower = lower;
  28224. mRange.upper = upper;
  28225. mRange = mRange.sanitizedForLinScale();
  28226. Q_EMIT rangeChanged(mRange);
  28227. Q_EMIT rangeChanged(mRange, oldRange);
  28228. }
  28229. /*!
  28230. \overload
  28231. Sets the range of the axis.
  28232. The \a position coordinate indicates together with the \a alignment parameter, where the new
  28233. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  28234. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  28235. or center of the range to be aligned with \a position. Any other values of \a alignment will
  28236. default to Qt::AlignCenter.
  28237. */
  28238. void QCPPolarAxisAngular::setRange(double position, double size, Qt::AlignmentFlag alignment)
  28239. {
  28240. if (alignment == Qt::AlignLeft)
  28241. setRange(position, position+size);
  28242. else if (alignment == Qt::AlignRight)
  28243. setRange(position-size, position);
  28244. else // alignment == Qt::AlignCenter
  28245. setRange(position-size/2.0, position+size/2.0);
  28246. }
  28247. /*!
  28248. Sets the lower bound of the axis range. The upper bound is not changed.
  28249. \see setRange
  28250. */
  28251. void QCPPolarAxisAngular::setRangeLower(double lower)
  28252. {
  28253. if (mRange.lower == lower)
  28254. return;
  28255. QCPRange oldRange = mRange;
  28256. mRange.lower = lower;
  28257. mRange = mRange.sanitizedForLinScale();
  28258. Q_EMIT rangeChanged(mRange);
  28259. Q_EMIT rangeChanged(mRange, oldRange);
  28260. }
  28261. /*!
  28262. Sets the upper bound of the axis range. The lower bound is not changed.
  28263. \see setRange
  28264. */
  28265. void QCPPolarAxisAngular::setRangeUpper(double upper)
  28266. {
  28267. if (mRange.upper == upper)
  28268. return;
  28269. QCPRange oldRange = mRange;
  28270. mRange.upper = upper;
  28271. mRange = mRange.sanitizedForLinScale();
  28272. Q_EMIT rangeChanged(mRange);
  28273. Q_EMIT rangeChanged(mRange, oldRange);
  28274. }
  28275. /*!
  28276. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  28277. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  28278. direction of increasing values is inverted.
  28279. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  28280. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  28281. upper part.
  28282. */
  28283. void QCPPolarAxisAngular::setRangeReversed(bool reversed)
  28284. {
  28285. mRangeReversed = reversed;
  28286. }
  28287. void QCPPolarAxisAngular::setAngle(double degrees)
  28288. {
  28289. mAngle = degrees;
  28290. mAngleRad = mAngle/180.0*M_PI;
  28291. }
  28292. /*!
  28293. The axis ticker is responsible for generating the tick positions and tick labels. See the
  28294. documentation of QCPAxisTicker for details on how to work with axis tickers.
  28295. You can change the tick positioning/labeling behaviour of this axis by setting a different
  28296. QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
  28297. ticker, access it via \ref ticker.
  28298. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  28299. ticker simply by passing the same shared pointer to multiple axes.
  28300. \see ticker
  28301. */
  28302. void QCPPolarAxisAngular::setTicker(QSharedPointer<QCPAxisTicker> ticker)
  28303. {
  28304. if (ticker)
  28305. mTicker = ticker;
  28306. else
  28307. qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
  28308. // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
  28309. }
  28310. /*!
  28311. Sets whether tick marks are displayed.
  28312. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  28313. that, see \ref setTickLabels.
  28314. \see setSubTicks
  28315. */
  28316. void QCPPolarAxisAngular::setTicks(bool show)
  28317. {
  28318. if (mTicks != show)
  28319. {
  28320. mTicks = show;
  28321. //mCachedMarginValid = false;
  28322. }
  28323. }
  28324. /*!
  28325. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  28326. */
  28327. void QCPPolarAxisAngular::setTickLabels(bool show)
  28328. {
  28329. if (mTickLabels != show)
  28330. {
  28331. mTickLabels = show;
  28332. //mCachedMarginValid = false;
  28333. if (!mTickLabels)
  28334. mTickVectorLabels.clear();
  28335. }
  28336. }
  28337. /*!
  28338. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  28339. \see setLabelPadding, setPadding
  28340. */
  28341. void QCPPolarAxisAngular::setTickLabelPadding(int padding)
  28342. {
  28343. mLabelPainter.setPadding(padding);
  28344. }
  28345. /*!
  28346. Sets the font of the tick labels.
  28347. \see setTickLabels, setTickLabelColor
  28348. */
  28349. void QCPPolarAxisAngular::setTickLabelFont(const QFont &font)
  28350. {
  28351. mTickLabelFont = font;
  28352. }
  28353. /*!
  28354. Sets the color of the tick labels.
  28355. \see setTickLabels, setTickLabelFont
  28356. */
  28357. void QCPPolarAxisAngular::setTickLabelColor(const QColor &color)
  28358. {
  28359. mTickLabelColor = color;
  28360. }
  28361. /*!
  28362. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  28363. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  28364. from -90 to 90 degrees.
  28365. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  28366. other angles, the label is drawn with an offset such that it seems to point toward or away from
  28367. the tick mark.
  28368. */
  28369. void QCPPolarAxisAngular::setTickLabelRotation(double degrees)
  28370. {
  28371. mLabelPainter.setRotation(degrees);
  28372. }
  28373. void QCPPolarAxisAngular::setTickLabelMode(LabelMode mode)
  28374. {
  28375. switch (mode)
  28376. {
  28377. case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break;
  28378. case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break;
  28379. }
  28380. }
  28381. /*!
  28382. Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
  28383. of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
  28384. that, see the "Argument Formats" section in the detailed description of the QString class.
  28385. \a formatCode is a string of one, two or three characters. The first character is identical to
  28386. the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
  28387. format, 'g'/'G' scientific or fixed, whichever is shorter.
  28388. The second and third characters are optional and specific to QCustomPlot:\n If the first char was
  28389. 'e' or 'g', numbers are/might be displayed in the scientific format, e.g. "5.5e9", which might be
  28390. visually unappealing in a plot. So when the second char of \a formatCode is set to 'b' (for
  28391. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  28392. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  28393. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  28394. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  28395. cross and 183 (0xB7) for the dot.
  28396. Examples for \a formatCode:
  28397. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  28398. normal scientific format is used
  28399. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  28400. beautifully typeset decimal powers and a dot as multiplication sign
  28401. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  28402. multiplication sign
  28403. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  28404. powers. Format code will be reduced to 'f'.
  28405. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  28406. code will not be changed.
  28407. */
  28408. void QCPPolarAxisAngular::setNumberFormat(const QString &formatCode)
  28409. {
  28410. if (formatCode.isEmpty())
  28411. {
  28412. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  28413. return;
  28414. }
  28415. //mCachedMarginValid = false;
  28416. // interpret first char as number format char:
  28417. QString allowedFormatChars(QLatin1String("eEfgG"));
  28418. if (allowedFormatChars.contains(formatCode.at(0)))
  28419. {
  28420. mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
  28421. } else
  28422. {
  28423. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  28424. return;
  28425. }
  28426. if (formatCode.length() < 2)
  28427. {
  28428. mNumberBeautifulPowers = false;
  28429. mNumberMultiplyCross = false;
  28430. } else
  28431. {
  28432. // interpret second char as indicator for beautiful decimal powers:
  28433. if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
  28434. mNumberBeautifulPowers = true;
  28435. else
  28436. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  28437. if (formatCode.length() < 3)
  28438. {
  28439. mNumberMultiplyCross = false;
  28440. } else
  28441. {
  28442. // interpret third char as indicator for dot or cross multiplication symbol:
  28443. if (formatCode.at(2) == QLatin1Char('c'))
  28444. mNumberMultiplyCross = true;
  28445. else if (formatCode.at(2) == QLatin1Char('d'))
  28446. mNumberMultiplyCross = false;
  28447. else
  28448. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  28449. }
  28450. }
  28451. mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers);
  28452. mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot);
  28453. }
  28454. /*!
  28455. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  28456. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  28457. \ref setNumberFormat
  28458. */
  28459. void QCPPolarAxisAngular::setNumberPrecision(int precision)
  28460. {
  28461. if (mNumberPrecision != precision)
  28462. {
  28463. mNumberPrecision = precision;
  28464. //mCachedMarginValid = false;
  28465. }
  28466. }
  28467. /*!
  28468. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  28469. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  28470. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  28471. they won't collide with the ticks.
  28472. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  28473. */
  28474. void QCPPolarAxisAngular::setTickLength(int inside, int outside)
  28475. {
  28476. setTickLengthIn(inside);
  28477. setTickLengthOut(outside);
  28478. }
  28479. /*!
  28480. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  28481. inside the plot.
  28482. \see setTickLengthOut, setTickLength, setSubTickLength
  28483. */
  28484. void QCPPolarAxisAngular::setTickLengthIn(int inside)
  28485. {
  28486. if (mTickLengthIn != inside)
  28487. {
  28488. mTickLengthIn = inside;
  28489. }
  28490. }
  28491. /*!
  28492. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  28493. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  28494. increase their distance to the axis accordingly, so they won't collide with the ticks.
  28495. \see setTickLengthIn, setTickLength, setSubTickLength
  28496. */
  28497. void QCPPolarAxisAngular::setTickLengthOut(int outside)
  28498. {
  28499. if (mTickLengthOut != outside)
  28500. {
  28501. mTickLengthOut = outside;
  28502. //mCachedMarginValid = false; // only outside tick length can change margin
  28503. }
  28504. }
  28505. /*!
  28506. Sets whether sub tick marks are displayed.
  28507. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
  28508. \see setTicks
  28509. */
  28510. void QCPPolarAxisAngular::setSubTicks(bool show)
  28511. {
  28512. if (mSubTicks != show)
  28513. {
  28514. mSubTicks = show;
  28515. //mCachedMarginValid = false;
  28516. }
  28517. }
  28518. /*!
  28519. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  28520. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  28521. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  28522. so they won't collide with the ticks.
  28523. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  28524. */
  28525. void QCPPolarAxisAngular::setSubTickLength(int inside, int outside)
  28526. {
  28527. setSubTickLengthIn(inside);
  28528. setSubTickLengthOut(outside);
  28529. }
  28530. /*!
  28531. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  28532. the plot.
  28533. \see setSubTickLengthOut, setSubTickLength, setTickLength
  28534. */
  28535. void QCPPolarAxisAngular::setSubTickLengthIn(int inside)
  28536. {
  28537. if (mSubTickLengthIn != inside)
  28538. {
  28539. mSubTickLengthIn = inside;
  28540. }
  28541. }
  28542. /*!
  28543. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  28544. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  28545. distance to the axis accordingly, so they won't collide with the ticks.
  28546. \see setSubTickLengthIn, setSubTickLength, setTickLength
  28547. */
  28548. void QCPPolarAxisAngular::setSubTickLengthOut(int outside)
  28549. {
  28550. if (mSubTickLengthOut != outside)
  28551. {
  28552. mSubTickLengthOut = outside;
  28553. //mCachedMarginValid = false; // only outside tick length can change margin
  28554. }
  28555. }
  28556. /*!
  28557. Sets the pen, the axis base line is drawn with.
  28558. \see setTickPen, setSubTickPen
  28559. */
  28560. void QCPPolarAxisAngular::setBasePen(const QPen &pen)
  28561. {
  28562. mBasePen = pen;
  28563. }
  28564. /*!
  28565. Sets the pen, tick marks will be drawn with.
  28566. \see setTickLength, setBasePen
  28567. */
  28568. void QCPPolarAxisAngular::setTickPen(const QPen &pen)
  28569. {
  28570. mTickPen = pen;
  28571. }
  28572. /*!
  28573. Sets the pen, subtick marks will be drawn with.
  28574. \see setSubTickCount, setSubTickLength, setBasePen
  28575. */
  28576. void QCPPolarAxisAngular::setSubTickPen(const QPen &pen)
  28577. {
  28578. mSubTickPen = pen;
  28579. }
  28580. /*!
  28581. Sets the font of the axis label.
  28582. \see setLabelColor
  28583. */
  28584. void QCPPolarAxisAngular::setLabelFont(const QFont &font)
  28585. {
  28586. if (mLabelFont != font)
  28587. {
  28588. mLabelFont = font;
  28589. //mCachedMarginValid = false;
  28590. }
  28591. }
  28592. /*!
  28593. Sets the color of the axis label.
  28594. \see setLabelFont
  28595. */
  28596. void QCPPolarAxisAngular::setLabelColor(const QColor &color)
  28597. {
  28598. mLabelColor = color;
  28599. }
  28600. /*!
  28601. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  28602. its orientation. To disable axis labels, pass an empty string as \a str.
  28603. */
  28604. void QCPPolarAxisAngular::setLabel(const QString &str)
  28605. {
  28606. if (mLabel != str)
  28607. {
  28608. mLabel = str;
  28609. //mCachedMarginValid = false;
  28610. }
  28611. }
  28612. /*!
  28613. Sets the distance between the tick labels and the axis label.
  28614. \see setTickLabelPadding, setPadding
  28615. */
  28616. void QCPPolarAxisAngular::setLabelPadding(int padding)
  28617. {
  28618. if (mLabelPadding != padding)
  28619. {
  28620. mLabelPadding = padding;
  28621. //mCachedMarginValid = false;
  28622. }
  28623. }
  28624. /*!
  28625. Sets the font that is used for tick labels when they are selected.
  28626. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28627. */
  28628. void QCPPolarAxisAngular::setSelectedTickLabelFont(const QFont &font)
  28629. {
  28630. if (font != mSelectedTickLabelFont)
  28631. {
  28632. mSelectedTickLabelFont = font;
  28633. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  28634. }
  28635. }
  28636. /*!
  28637. Sets the font that is used for the axis label when it is selected.
  28638. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28639. */
  28640. void QCPPolarAxisAngular::setSelectedLabelFont(const QFont &font)
  28641. {
  28642. mSelectedLabelFont = font;
  28643. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  28644. }
  28645. /*!
  28646. Sets the color that is used for tick labels when they are selected.
  28647. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28648. */
  28649. void QCPPolarAxisAngular::setSelectedTickLabelColor(const QColor &color)
  28650. {
  28651. if (color != mSelectedTickLabelColor)
  28652. {
  28653. mSelectedTickLabelColor = color;
  28654. }
  28655. }
  28656. /*!
  28657. Sets the color that is used for the axis label when it is selected.
  28658. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28659. */
  28660. void QCPPolarAxisAngular::setSelectedLabelColor(const QColor &color)
  28661. {
  28662. mSelectedLabelColor = color;
  28663. }
  28664. /*!
  28665. Sets the pen that is used to draw the axis base line when selected.
  28666. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28667. */
  28668. void QCPPolarAxisAngular::setSelectedBasePen(const QPen &pen)
  28669. {
  28670. mSelectedBasePen = pen;
  28671. }
  28672. /*!
  28673. Sets the pen that is used to draw the (major) ticks when selected.
  28674. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28675. */
  28676. void QCPPolarAxisAngular::setSelectedTickPen(const QPen &pen)
  28677. {
  28678. mSelectedTickPen = pen;
  28679. }
  28680. /*!
  28681. Sets the pen that is used to draw the subticks when selected.
  28682. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28683. */
  28684. void QCPPolarAxisAngular::setSelectedSubTickPen(const QPen &pen)
  28685. {
  28686. mSelectedSubTickPen = pen;
  28687. }
  28688. /*! \internal
  28689. Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
  28690. pixmap.
  28691. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
  28692. according filling inside the axis rect with the provided \a painter.
  28693. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
  28694. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  28695. the axis rect with the provided \a painter. The scaled version is buffered in
  28696. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  28697. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  28698. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  28699. set.
  28700. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  28701. */
  28702. void QCPPolarAxisAngular::drawBackground(QCPPainter *painter, const QPointF &center, double radius)
  28703. {
  28704. // draw background fill (don't use circular clip, looks bad):
  28705. if (mBackgroundBrush != Qt::NoBrush)
  28706. {
  28707. QPainterPath ellipsePath;
  28708. ellipsePath.addEllipse(center, radius, radius);
  28709. painter->fillPath(ellipsePath, mBackgroundBrush);
  28710. }
  28711. // draw background pixmap (on top of fill, if brush specified):
  28712. if (!mBackgroundPixmap.isNull())
  28713. {
  28714. QRegion clipCircle(center.x()-radius, center.y()-radius, qRound(2*radius), qRound(2*radius), QRegion::Ellipse);
  28715. QRegion originalClip = painter->clipRegion();
  28716. painter->setClipRegion(clipCircle);
  28717. if (mBackgroundScaled)
  28718. {
  28719. // check whether mScaledBackground needs to be updated:
  28720. QSize scaledSize(mBackgroundPixmap.size());
  28721. scaledSize.scale(mRect.size(), mBackgroundScaledMode);
  28722. if (mScaledBackgroundPixmap.size() != scaledSize)
  28723. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  28724. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
  28725. } else
  28726. {
  28727. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
  28728. }
  28729. painter->setClipRegion(originalClip);
  28730. }
  28731. }
  28732. /*! \internal
  28733. Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
  28734. QCPAxisTicker::generate on the currently installed ticker.
  28735. If a change in the label text/count is detected, the cached axis margin is invalidated to make
  28736. sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
  28737. */
  28738. void QCPPolarAxisAngular::setupTickVectors()
  28739. {
  28740. if (!mParentPlot) return;
  28741. if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
  28742. mSubTickVector.clear(); // since we might not pass it to mTicker->generate(), and we don't want old data in there
  28743. mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0);
  28744. // fill cos/sin buffers which will be used by draw() and QCPPolarGrid::draw(), so we don't have to calculate it twice:
  28745. mTickVectorCosSin.resize(mTickVector.size());
  28746. for (int i=0; i<mTickVector.size(); ++i)
  28747. {
  28748. const double theta = coordToAngleRad(mTickVector.at(i));
  28749. mTickVectorCosSin[i] = QPointF(qCos(theta), qSin(theta));
  28750. }
  28751. mSubTickVectorCosSin.resize(mSubTickVector.size());
  28752. for (int i=0; i<mSubTickVector.size(); ++i)
  28753. {
  28754. const double theta = coordToAngleRad(mSubTickVector.at(i));
  28755. mSubTickVectorCosSin[i] = QPointF(qCos(theta), qSin(theta));
  28756. }
  28757. }
  28758. /*! \internal
  28759. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  28760. is either mSelectedBasePen or mBasePen.
  28761. */
  28762. QPen QCPPolarAxisAngular::getBasePen() const
  28763. {
  28764. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  28765. }
  28766. /*! \internal
  28767. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  28768. is either mSelectedTickPen or mTickPen.
  28769. */
  28770. QPen QCPPolarAxisAngular::getTickPen() const
  28771. {
  28772. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  28773. }
  28774. /*! \internal
  28775. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  28776. is either mSelectedSubTickPen or mSubTickPen.
  28777. */
  28778. QPen QCPPolarAxisAngular::getSubTickPen() const
  28779. {
  28780. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  28781. }
  28782. /*! \internal
  28783. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  28784. is either mSelectedTickLabelFont or mTickLabelFont.
  28785. */
  28786. QFont QCPPolarAxisAngular::getTickLabelFont() const
  28787. {
  28788. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  28789. }
  28790. /*! \internal
  28791. Returns the font that is used to draw the axis label. Depending on the selection state, this
  28792. is either mSelectedLabelFont or mLabelFont.
  28793. */
  28794. QFont QCPPolarAxisAngular::getLabelFont() const
  28795. {
  28796. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  28797. }
  28798. /*! \internal
  28799. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  28800. is either mSelectedTickLabelColor or mTickLabelColor.
  28801. */
  28802. QColor QCPPolarAxisAngular::getTickLabelColor() const
  28803. {
  28804. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  28805. }
  28806. /*! \internal
  28807. Returns the color that is used to draw the axis label. Depending on the selection state, this
  28808. is either mSelectedLabelColor or mLabelColor.
  28809. */
  28810. QColor QCPPolarAxisAngular::getLabelColor() const
  28811. {
  28812. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  28813. }
  28814. /*! \internal
  28815. Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
  28816. pressed, the range dragging interaction is initialized (the actual range manipulation happens in
  28817. the \ref mouseMoveEvent).
  28818. The mDragging flag is set to true and some anchor points are set that are needed to determine the
  28819. distance the mouse was dragged in the mouse move/release events later.
  28820. \see mouseMoveEvent, mouseReleaseEvent
  28821. */
  28822. void QCPPolarAxisAngular::mousePressEvent(QMouseEvent *event, const QVariant &details)
  28823. {
  28824. Q_UNUSED(details)
  28825. if (event->buttons() & Qt::LeftButton)
  28826. {
  28827. mDragging = true;
  28828. // initialize antialiasing backup in case we start dragging:
  28829. if (mParentPlot->noAntialiasingOnDrag())
  28830. {
  28831. mAADragBackup = mParentPlot->antialiasedElements();
  28832. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  28833. }
  28834. // Mouse range dragging interaction:
  28835. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  28836. {
  28837. mDragAngularStart = range();
  28838. mDragRadialStart.clear();
  28839. for (int i=0; i<mRadialAxes.size(); ++i)
  28840. mDragRadialStart.append(mRadialAxes.at(i)->range());
  28841. }
  28842. }
  28843. }
  28844. /*! \internal
  28845. Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
  28846. preceding \ref mousePressEvent, the range is moved accordingly.
  28847. \see mousePressEvent, mouseReleaseEvent
  28848. */
  28849. void QCPPolarAxisAngular::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  28850. {
  28851. Q_UNUSED(startPos)
  28852. bool doReplot = false;
  28853. // Mouse range dragging interaction:
  28854. if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  28855. {
  28856. if (mRangeDrag)
  28857. {
  28858. doReplot = true;
  28859. double angleCoordStart, radiusCoordStart;
  28860. double angleCoord, radiusCoord;
  28861. pixelToCoord(startPos, angleCoordStart, radiusCoordStart);
  28862. pixelToCoord(event->pos(), angleCoord, radiusCoord);
  28863. double diff = angleCoordStart - angleCoord;
  28864. setRange(mDragAngularStart.lower+diff, mDragAngularStart.upper+diff);
  28865. }
  28866. for (int i=0; i<mRadialAxes.size(); ++i)
  28867. {
  28868. QCPPolarAxisRadial *ax = mRadialAxes.at(i);
  28869. if (!ax->rangeDrag())
  28870. continue;
  28871. doReplot = true;
  28872. double angleCoordStart, radiusCoordStart;
  28873. double angleCoord, radiusCoord;
  28874. ax->pixelToCoord(startPos, angleCoordStart, radiusCoordStart);
  28875. ax->pixelToCoord(event->pos(), angleCoord, radiusCoord);
  28876. if (ax->scaleType() == QCPPolarAxisRadial::stLinear)
  28877. {
  28878. double diff = radiusCoordStart - radiusCoord;
  28879. ax->setRange(mDragRadialStart.at(i).lower+diff, mDragRadialStart.at(i).upper+diff);
  28880. } else if (ax->scaleType() == QCPPolarAxisRadial::stLogarithmic)
  28881. {
  28882. if (radiusCoord != 0)
  28883. {
  28884. double diff = radiusCoordStart/radiusCoord;
  28885. ax->setRange(mDragRadialStart.at(i).lower*diff, mDragRadialStart.at(i).upper*diff);
  28886. }
  28887. }
  28888. }
  28889. if (doReplot) // if either vertical or horizontal drag was enabled, do a replot
  28890. {
  28891. if (mParentPlot->noAntialiasingOnDrag())
  28892. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  28893. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  28894. }
  28895. }
  28896. }
  28897. /* inherits documentation from base class */
  28898. void QCPPolarAxisAngular::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  28899. {
  28900. Q_UNUSED(event)
  28901. Q_UNUSED(startPos)
  28902. mDragging = false;
  28903. if (mParentPlot->noAntialiasingOnDrag())
  28904. {
  28905. mParentPlot->setAntialiasedElements(mAADragBackup);
  28906. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  28907. }
  28908. }
  28909. /*! \internal
  28910. Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
  28911. ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
  28912. the scaling operation is the current cursor position inside the axis rect. The scaling factor is
  28913. dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
  28914. zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
  28915. Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse
  28916. wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be
  28917. multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as
  28918. exponent of the range zoom factor. This takes care of the wheel direction automatically, by
  28919. inverting the factor, when the wheel step is negative (f^-1 = 1/f).
  28920. */
  28921. void QCPPolarAxisAngular::wheelEvent(QWheelEvent *event)
  28922. {
  28923. bool doReplot = false;
  28924. // Mouse range zooming interaction:
  28925. if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  28926. {
  28927. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  28928. const double delta = event->delta();
  28929. #else
  28930. const double delta = event->angleDelta().y();
  28931. #endif
  28932. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  28933. const QPointF pos = event->pos();
  28934. #else
  28935. const QPointF pos = event->position();
  28936. #endif
  28937. const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
  28938. if (mRangeZoom)
  28939. {
  28940. double angleCoord, radiusCoord;
  28941. pixelToCoord(pos, angleCoord, radiusCoord);
  28942. scaleRange(qPow(mRangeZoomFactor, wheelSteps), angleCoord);
  28943. }
  28944. for (int i=0; i<mRadialAxes.size(); ++i)
  28945. {
  28946. QCPPolarAxisRadial *ax = mRadialAxes.at(i);
  28947. if (!ax->rangeZoom())
  28948. continue;
  28949. doReplot = true;
  28950. double angleCoord, radiusCoord;
  28951. ax->pixelToCoord(pos, angleCoord, radiusCoord);
  28952. ax->scaleRange(qPow(ax->rangeZoomFactor(), wheelSteps), radiusCoord);
  28953. }
  28954. }
  28955. if (doReplot)
  28956. mParentPlot->replot();
  28957. }
  28958. bool QCPPolarAxisAngular::registerPolarGraph(QCPPolarGraph *graph)
  28959. {
  28960. if (mGraphs.contains(graph))
  28961. {
  28962. qDebug() << Q_FUNC_INFO << "plottable already added:" << reinterpret_cast<quintptr>(graph);
  28963. return false;
  28964. }
  28965. if (graph->keyAxis() != this)
  28966. {
  28967. qDebug() << Q_FUNC_INFO << "plottable not created with this as axis:" << reinterpret_cast<quintptr>(graph);
  28968. return false;
  28969. }
  28970. mGraphs.append(graph);
  28971. // possibly add plottable to legend:
  28972. if (mParentPlot->autoAddPlottableToLegend())
  28973. graph->addToLegend();
  28974. if (!graph->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
  28975. graph->setLayer(mParentPlot->currentLayer());
  28976. return true;
  28977. }
  28978. /* end of 'src/polar/layoutelement-angularaxis.cpp' */
  28979. /* including file 'src/polar/polargrid.cpp' */
  28980. /* modified 2021-03-29T02:30:44, size 7493 */
  28981. ////////////////////////////////////////////////////////////////////////////////////////////////////
  28982. //////////////////// QCPPolarGrid
  28983. ////////////////////////////////////////////////////////////////////////////////////////////////////
  28984. /*! \class QCPPolarGrid
  28985. \brief The grid in both angular and radial dimensions for polar plots
  28986. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  28987. functionality to be incomplete, as well as changing public interfaces in the future.
  28988. */
  28989. /*!
  28990. Creates a QCPPolarGrid instance and sets default values.
  28991. You shouldn't instantiate grids on their own, since every axis brings its own grid.
  28992. */
  28993. QCPPolarGrid::QCPPolarGrid(QCPPolarAxisAngular *parentAxis) :
  28994. QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
  28995. mType(gtNone),
  28996. mSubGridType(gtNone),
  28997. mAntialiasedSubGrid(true),
  28998. mAntialiasedZeroLine(true),
  28999. mParentAxis(parentAxis)
  29000. {
  29001. // warning: this is called in QCPPolarAxisAngular constructor, so parentAxis members should not be accessed/called
  29002. setParent(parentAxis);
  29003. setType(gtAll);
  29004. setSubGridType(gtNone);
  29005. setAngularPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  29006. setAngularSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  29007. setRadialPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  29008. setRadialSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  29009. setRadialZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
  29010. setAntialiased(true);
  29011. }
  29012. void QCPPolarGrid::setRadialAxis(QCPPolarAxisRadial *axis)
  29013. {
  29014. mRadialAxis = axis;
  29015. }
  29016. void QCPPolarGrid::setType(GridTypes type)
  29017. {
  29018. mType = type;
  29019. }
  29020. void QCPPolarGrid::setSubGridType(GridTypes type)
  29021. {
  29022. mSubGridType = type;
  29023. }
  29024. /*!
  29025. Sets whether sub grid lines are drawn antialiased.
  29026. */
  29027. void QCPPolarGrid::setAntialiasedSubGrid(bool enabled)
  29028. {
  29029. mAntialiasedSubGrid = enabled;
  29030. }
  29031. /*!
  29032. Sets whether zero lines are drawn antialiased.
  29033. */
  29034. void QCPPolarGrid::setAntialiasedZeroLine(bool enabled)
  29035. {
  29036. mAntialiasedZeroLine = enabled;
  29037. }
  29038. /*!
  29039. Sets the pen with which (major) grid lines are drawn.
  29040. */
  29041. void QCPPolarGrid::setAngularPen(const QPen &pen)
  29042. {
  29043. mAngularPen = pen;
  29044. }
  29045. /*!
  29046. Sets the pen with which sub grid lines are drawn.
  29047. */
  29048. void QCPPolarGrid::setAngularSubGridPen(const QPen &pen)
  29049. {
  29050. mAngularSubGridPen = pen;
  29051. }
  29052. void QCPPolarGrid::setRadialPen(const QPen &pen)
  29053. {
  29054. mRadialPen = pen;
  29055. }
  29056. void QCPPolarGrid::setRadialSubGridPen(const QPen &pen)
  29057. {
  29058. mRadialSubGridPen = pen;
  29059. }
  29060. void QCPPolarGrid::setRadialZeroLinePen(const QPen &pen)
  29061. {
  29062. mRadialZeroLinePen = pen;
  29063. }
  29064. /*! \internal
  29065. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  29066. before drawing the major grid lines.
  29067. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  29068. This function takes into account the local setting of the antialiasing flag as well as the
  29069. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  29070. QCustomPlot::setNotAntialiasedElements.
  29071. \see setAntialiased
  29072. */
  29073. void QCPPolarGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
  29074. {
  29075. applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
  29076. }
  29077. /*! \internal
  29078. Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
  29079. over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
  29080. */
  29081. void QCPPolarGrid::draw(QCPPainter *painter)
  29082. {
  29083. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  29084. const QPointF center = mParentAxis->mCenter;
  29085. const double radius = mParentAxis->mRadius;
  29086. painter->setBrush(Qt::NoBrush);
  29087. // draw main angular grid:
  29088. if (mType.testFlag(gtAngular))
  29089. drawAngularGrid(painter, center, radius, mParentAxis->mTickVectorCosSin, mAngularPen);
  29090. // draw main radial grid:
  29091. if (mType.testFlag(gtRadial) && mRadialAxis)
  29092. drawRadialGrid(painter, center, mRadialAxis->tickVector(), mRadialPen, mRadialZeroLinePen);
  29093. applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeGrid);
  29094. // draw sub angular grid:
  29095. if (mSubGridType.testFlag(gtAngular))
  29096. drawAngularGrid(painter, center, radius, mParentAxis->mSubTickVectorCosSin, mAngularSubGridPen);
  29097. // draw sub radial grid:
  29098. if (mSubGridType.testFlag(gtRadial) && mRadialAxis)
  29099. drawRadialGrid(painter, center, mRadialAxis->subTickVector(), mRadialSubGridPen);
  29100. }
  29101. void QCPPolarGrid::drawRadialGrid(QCPPainter *painter, const QPointF &center, const QVector<double> &coords, const QPen &pen, const QPen &zeroPen)
  29102. {
  29103. if (!mRadialAxis) return;
  29104. if (coords.isEmpty()) return;
  29105. const bool drawZeroLine = zeroPen != Qt::NoPen;
  29106. const double zeroLineEpsilon = qAbs(coords.last()-coords.first())*1e-6;
  29107. painter->setPen(pen);
  29108. for (int i=0; i<coords.size(); ++i)
  29109. {
  29110. const double r = mRadialAxis->coordToRadius(coords.at(i));
  29111. if (drawZeroLine && qAbs(coords.at(i)) < zeroLineEpsilon)
  29112. {
  29113. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  29114. painter->setPen(zeroPen);
  29115. painter->drawEllipse(center, r, r);
  29116. painter->setPen(pen);
  29117. applyDefaultAntialiasingHint(painter);
  29118. } else
  29119. {
  29120. painter->drawEllipse(center, r, r);
  29121. }
  29122. }
  29123. }
  29124. void QCPPolarGrid::drawAngularGrid(QCPPainter *painter, const QPointF &center, double radius, const QVector<QPointF> &ticksCosSin, const QPen &pen)
  29125. {
  29126. if (ticksCosSin.isEmpty()) return;
  29127. painter->setPen(pen);
  29128. for (int i=0; i<ticksCosSin.size(); ++i)
  29129. painter->drawLine(center, center+ticksCosSin.at(i)*radius);
  29130. }
  29131. /* end of 'src/polar/polargrid.cpp' */
  29132. /* including file 'src/polar/polargraph.cpp' */
  29133. /* modified 2021-03-29T02:30:44, size 44035 */
  29134. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29135. //////////////////// QCPPolarLegendItem
  29136. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29137. /*! \class QCPPolarLegendItem
  29138. \brief A legend item for polar plots
  29139. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  29140. functionality to be incomplete, as well as changing public interfaces in the future.
  29141. */
  29142. QCPPolarLegendItem::QCPPolarLegendItem(QCPLegend *parent, QCPPolarGraph *graph) :
  29143. QCPAbstractLegendItem(parent),
  29144. mPolarGraph(graph)
  29145. {
  29146. setAntialiased(false);
  29147. }
  29148. void QCPPolarLegendItem::draw(QCPPainter *painter)
  29149. {
  29150. if (!mPolarGraph) return;
  29151. painter->setFont(getFont());
  29152. painter->setPen(QPen(getTextColor()));
  29153. QSizeF iconSize = mParentLegend->iconSize();
  29154. QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name());
  29155. QRectF iconRect(mRect.topLeft(), iconSize);
  29156. int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
  29157. painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPolarGraph->name());
  29158. // draw icon:
  29159. painter->save();
  29160. painter->setClipRect(iconRect, Qt::IntersectClip);
  29161. mPolarGraph->drawLegendIcon(painter, iconRect);
  29162. painter->restore();
  29163. // draw icon border:
  29164. if (getIconBorderPen().style() != Qt::NoPen)
  29165. {
  29166. painter->setPen(getIconBorderPen());
  29167. painter->setBrush(Qt::NoBrush);
  29168. int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
  29169. painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
  29170. painter->drawRect(iconRect);
  29171. }
  29172. }
  29173. QSize QCPPolarLegendItem::minimumOuterSizeHint() const
  29174. {
  29175. if (!mPolarGraph) return QSize();
  29176. QSize result(0, 0);
  29177. QRect textRect;
  29178. QFontMetrics fontMetrics(getFont());
  29179. QSize iconSize = mParentLegend->iconSize();
  29180. textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name());
  29181. result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width());
  29182. result.setHeight(qMax(textRect.height(), iconSize.height()));
  29183. result.rwidth() += mMargins.left()+mMargins.right();
  29184. result.rheight() += mMargins.top()+mMargins.bottom();
  29185. return result;
  29186. }
  29187. QPen QCPPolarLegendItem::getIconBorderPen() const
  29188. {
  29189. return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
  29190. }
  29191. QColor QCPPolarLegendItem::getTextColor() const
  29192. {
  29193. return mSelected ? mSelectedTextColor : mTextColor;
  29194. }
  29195. QFont QCPPolarLegendItem::getFont() const
  29196. {
  29197. return mSelected ? mSelectedFont : mFont;
  29198. }
  29199. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29200. //////////////////// QCPPolarGraph
  29201. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29202. /*! \class QCPPolarGraph
  29203. \brief A radial graph used to display data in polar plots
  29204. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  29205. functionality to be incomplete, as well as changing public interfaces in the future.
  29206. */
  29207. /* start of documentation of inline functions */
  29208. // TODO
  29209. /* end of documentation of inline functions */
  29210. /*!
  29211. Constructs a graph which uses \a keyAxis as its angular and \a valueAxis as its radial axis. \a
  29212. keyAxis and \a valueAxis must reside in the same QCustomPlot, and the radial axis must be
  29213. associated with the angular axis. If either of these restrictions is violated, a corresponding
  29214. message is printed to the debug output (qDebug), the construction is not aborted, though.
  29215. The created QCPPolarGraph is automatically registered with the QCustomPlot instance inferred from
  29216. \a keyAxis. This QCustomPlot instance takes ownership of the QCPPolarGraph, so do not delete it
  29217. manually but use QCPPolarAxisAngular::removeGraph() instead.
  29218. To directly create a QCPPolarGraph inside a plot, you shoud use the QCPPolarAxisAngular::addGraph
  29219. method.
  29220. */
  29221. QCPPolarGraph::QCPPolarGraph(QCPPolarAxisAngular *keyAxis, QCPPolarAxisRadial *valueAxis) :
  29222. QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis),
  29223. mDataContainer(new QCPGraphDataContainer),
  29224. mName(),
  29225. mAntialiasedFill(true),
  29226. mAntialiasedScatters(true),
  29227. mPen(Qt::black),
  29228. mBrush(Qt::NoBrush),
  29229. mPeriodic(true),
  29230. mKeyAxis(keyAxis),
  29231. mValueAxis(valueAxis),
  29232. mSelectable(QCP::stWhole)
  29233. //mSelectionDecorator(0) // TODO
  29234. {
  29235. if (keyAxis->parentPlot() != valueAxis->parentPlot())
  29236. qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
  29237. mKeyAxis->registerPolarGraph(this);
  29238. //setSelectionDecorator(new QCPSelectionDecorator); // TODO
  29239. setPen(QPen(Qt::blue, 0));
  29240. setBrush(Qt::NoBrush);
  29241. setLineStyle(lsLine);
  29242. }
  29243. QCPPolarGraph::~QCPPolarGraph()
  29244. {
  29245. /* TODO
  29246. if (mSelectionDecorator)
  29247. {
  29248. delete mSelectionDecorator;
  29249. mSelectionDecorator = 0;
  29250. }
  29251. */
  29252. }
  29253. /*!
  29254. The name is the textual representation of this plottable as it is displayed in the legend
  29255. (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
  29256. */
  29257. void QCPPolarGraph::setName(const QString &name)
  29258. {
  29259. mName = name;
  29260. }
  29261. /*!
  29262. Sets whether fills of this plottable are drawn antialiased or not.
  29263. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  29264. QCustomPlot::setNotAntialiasedElements.
  29265. */
  29266. void QCPPolarGraph::setAntialiasedFill(bool enabled)
  29267. {
  29268. mAntialiasedFill = enabled;
  29269. }
  29270. /*!
  29271. Sets whether the scatter symbols of this plottable are drawn antialiased or not.
  29272. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  29273. QCustomPlot::setNotAntialiasedElements.
  29274. */
  29275. void QCPPolarGraph::setAntialiasedScatters(bool enabled)
  29276. {
  29277. mAntialiasedScatters = enabled;
  29278. }
  29279. /*!
  29280. The pen is used to draw basic lines that make up the plottable representation in the
  29281. plot.
  29282. For example, the \ref QCPGraph subclass draws its graph lines with this pen.
  29283. \see setBrush
  29284. */
  29285. void QCPPolarGraph::setPen(const QPen &pen)
  29286. {
  29287. mPen = pen;
  29288. }
  29289. /*!
  29290. The brush is used to draw basic fills of the plottable representation in the
  29291. plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
  29292. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
  29293. it's not set to Qt::NoBrush.
  29294. \see setPen
  29295. */
  29296. void QCPPolarGraph::setBrush(const QBrush &brush)
  29297. {
  29298. mBrush = brush;
  29299. }
  29300. void QCPPolarGraph::setPeriodic(bool enabled)
  29301. {
  29302. mPeriodic = enabled;
  29303. }
  29304. /*!
  29305. The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
  29306. to the plottable's value axis. This function performs no checks to make sure this is the case.
  29307. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
  29308. y-axis (QCustomPlot::yAxis) as value axis.
  29309. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  29310. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  29311. \see setValueAxis
  29312. */
  29313. void QCPPolarGraph::setKeyAxis(QCPPolarAxisAngular *axis)
  29314. {
  29315. mKeyAxis = axis;
  29316. }
  29317. /*!
  29318. The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
  29319. orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
  29320. case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
  29321. the y-axis (QCustomPlot::yAxis) as value axis.
  29322. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  29323. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  29324. \see setKeyAxis
  29325. */
  29326. void QCPPolarGraph::setValueAxis(QCPPolarAxisRadial *axis)
  29327. {
  29328. mValueAxis = axis;
  29329. }
  29330. /*!
  29331. Sets whether and to which granularity this plottable can be selected.
  29332. A selection can happen by clicking on the QCustomPlot surface (When \ref
  29333. QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
  29334. (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
  29335. calling \ref setSelection.
  29336. \see setSelection, QCP::SelectionType
  29337. */
  29338. void QCPPolarGraph::setSelectable(QCP::SelectionType selectable)
  29339. {
  29340. if (mSelectable != selectable)
  29341. {
  29342. mSelectable = selectable;
  29343. QCPDataSelection oldSelection = mSelection;
  29344. mSelection.enforceType(mSelectable);
  29345. Q_EMIT selectableChanged(mSelectable);
  29346. if (mSelection != oldSelection)
  29347. {
  29348. Q_EMIT selectionChanged(selected());
  29349. Q_EMIT selectionChanged(mSelection);
  29350. }
  29351. }
  29352. }
  29353. /*!
  29354. Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
  29355. (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
  29356. selectionDecorator).
  29357. The entire selection mechanism for plottables is handled automatically when \ref
  29358. QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
  29359. you wish to change the selection state programmatically.
  29360. Using \ref setSelectable you can further specify for each plottable whether and to which
  29361. granularity it is selectable. If \a selection is not compatible with the current \ref
  29362. QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
  29363. accordingly (see \ref QCPDataSelection::enforceType).
  29364. Q_EMITs the \ref selectionChanged signal when \a selected is different from the previous selection state.
  29365. \see setSelectable, selectTest
  29366. */
  29367. void QCPPolarGraph::setSelection(QCPDataSelection selection)
  29368. {
  29369. selection.enforceType(mSelectable);
  29370. if (mSelection != selection)
  29371. {
  29372. mSelection = selection;
  29373. Q_EMIT selectionChanged(selected());
  29374. Q_EMIT selectionChanged(mSelection);
  29375. }
  29376. }
  29377. /*! \overload
  29378. Replaces the current data container with the provided \a data container.
  29379. Since a QSharedPointer is used, multiple QCPPolarGraphs may share the same data container safely.
  29380. Modifying the data in the container will then affect all graphs that share the container. Sharing
  29381. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  29382. \snippet documentation/doc-code-snippets/mainwindow.cpp QCPPolarGraph-datasharing-1
  29383. If you do not wish to share containers, but create a copy from an existing container, rather use
  29384. the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
  29385. \snippet documentation/doc-code-snippets/mainwindow.cpp QCPPolarGraph-datasharing-2
  29386. \see addData
  29387. */
  29388. void QCPPolarGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
  29389. {
  29390. mDataContainer = data;
  29391. }
  29392. /*! \overload
  29393. Replaces the current data with the provided points in \a keys and \a values. The provided
  29394. vectors should have equal length. Else, the number of added points will be the size of the
  29395. smallest vector.
  29396. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  29397. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  29398. \see addData
  29399. */
  29400. void QCPPolarGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  29401. {
  29402. mDataContainer->clear();
  29403. addData(keys, values, alreadySorted);
  29404. }
  29405. /*!
  29406. Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
  29407. \ref lsNone and \ref setScatterStyle to the desired scatter style.
  29408. \see setScatterStyle
  29409. */
  29410. void QCPPolarGraph::setLineStyle(LineStyle ls)
  29411. {
  29412. mLineStyle = ls;
  29413. }
  29414. /*!
  29415. Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
  29416. are drawn (e.g. for line-only-plots with appropriate line style).
  29417. \see QCPScatterStyle, setLineStyle
  29418. */
  29419. void QCPPolarGraph::setScatterStyle(const QCPScatterStyle &style)
  29420. {
  29421. mScatterStyle = style;
  29422. }
  29423. void QCPPolarGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  29424. {
  29425. if (keys.size() != values.size())
  29426. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  29427. const int n = qMin(keys.size(), values.size());
  29428. QVector<QCPGraphData> tempData(n);
  29429. QVector<QCPGraphData>::iterator it = tempData.begin();
  29430. const QVector<QCPGraphData>::iterator itEnd = tempData.end();
  29431. int i = 0;
  29432. while (it != itEnd)
  29433. {
  29434. it->key = keys[i];
  29435. it->value = values[i];
  29436. ++it;
  29437. ++i;
  29438. }
  29439. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  29440. }
  29441. void QCPPolarGraph::addData(double key, double value)
  29442. {
  29443. mDataContainer->add(QCPGraphData(key, value));
  29444. }
  29445. /*!
  29446. Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
  29447. customize the visual representation of selected data ranges further than by using the default
  29448. QCPSelectionDecorator.
  29449. The plottable takes ownership of the \a decorator.
  29450. The currently set decorator can be accessed via \ref selectionDecorator.
  29451. */
  29452. /*
  29453. void QCPPolarGraph::setSelectionDecorator(QCPSelectionDecorator *decorator)
  29454. {
  29455. if (decorator)
  29456. {
  29457. if (decorator->registerWithPlottable(this))
  29458. {
  29459. if (mSelectionDecorator) // delete old decorator if necessary
  29460. delete mSelectionDecorator;
  29461. mSelectionDecorator = decorator;
  29462. }
  29463. } else if (mSelectionDecorator) // just clear decorator
  29464. {
  29465. delete mSelectionDecorator;
  29466. mSelectionDecorator = 0;
  29467. }
  29468. }
  29469. */
  29470. void QCPPolarGraph::coordsToPixels(double key, double value, double &x, double &y) const
  29471. {
  29472. if (mValueAxis)
  29473. {
  29474. const QPointF point = mValueAxis->coordToPixel(key, value);
  29475. x = point.x();
  29476. y = point.y();
  29477. } else
  29478. {
  29479. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29480. }
  29481. }
  29482. const QPointF QCPPolarGraph::coordsToPixels(double key, double value) const
  29483. {
  29484. if (mValueAxis)
  29485. {
  29486. return mValueAxis->coordToPixel(key, value);
  29487. } else
  29488. {
  29489. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29490. return QPointF();
  29491. }
  29492. }
  29493. void QCPPolarGraph::pixelsToCoords(double x, double y, double &key, double &value) const
  29494. {
  29495. if (mValueAxis)
  29496. {
  29497. mValueAxis->pixelToCoord(QPointF(x, y), key, value);
  29498. } else
  29499. {
  29500. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29501. }
  29502. }
  29503. void QCPPolarGraph::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
  29504. {
  29505. if (mValueAxis)
  29506. {
  29507. mValueAxis->pixelToCoord(pixelPos, key, value);
  29508. } else
  29509. {
  29510. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29511. }
  29512. }
  29513. void QCPPolarGraph::rescaleAxes(bool onlyEnlarge) const
  29514. {
  29515. rescaleKeyAxis(onlyEnlarge);
  29516. rescaleValueAxis(onlyEnlarge);
  29517. }
  29518. void QCPPolarGraph::rescaleKeyAxis(bool onlyEnlarge) const
  29519. {
  29520. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  29521. if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  29522. bool foundRange;
  29523. QCPRange newRange = getKeyRange(foundRange, QCP::sdBoth);
  29524. if (foundRange)
  29525. {
  29526. if (onlyEnlarge)
  29527. newRange.expand(keyAxis->range());
  29528. if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
  29529. {
  29530. double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
  29531. newRange.lower = center-keyAxis->range().size()/2.0;
  29532. newRange.upper = center+keyAxis->range().size()/2.0;
  29533. }
  29534. keyAxis->setRange(newRange);
  29535. }
  29536. }
  29537. void QCPPolarGraph::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
  29538. {
  29539. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  29540. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  29541. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  29542. QCP::SignDomain signDomain = QCP::sdBoth;
  29543. if (valueAxis->scaleType() == QCPPolarAxisRadial::stLogarithmic)
  29544. signDomain = (valueAxis->range().upper < 0 ? QCP::sdNegative : QCP::sdPositive);
  29545. bool foundRange;
  29546. QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
  29547. if (foundRange)
  29548. {
  29549. if (onlyEnlarge)
  29550. newRange.expand(valueAxis->range());
  29551. if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable
  29552. {
  29553. double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason
  29554. if (valueAxis->scaleType() == QCPPolarAxisRadial::stLinear)
  29555. {
  29556. newRange.lower = center-valueAxis->range().size()/2.0;
  29557. newRange.upper = center+valueAxis->range().size()/2.0;
  29558. } else // scaleType() == stLogarithmic
  29559. {
  29560. newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  29561. newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  29562. }
  29563. }
  29564. valueAxis->setRange(newRange);
  29565. }
  29566. }
  29567. bool QCPPolarGraph::addToLegend(QCPLegend *legend)
  29568. {
  29569. if (!legend)
  29570. {
  29571. qDebug() << Q_FUNC_INFO << "passed legend is null";
  29572. return false;
  29573. }
  29574. if (legend->parentPlot() != mParentPlot)
  29575. {
  29576. qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
  29577. return false;
  29578. }
  29579. //if (!legend->hasItemWithPlottable(this)) // TODO
  29580. //{
  29581. legend->addItem(new QCPPolarLegendItem(legend, this));
  29582. return true;
  29583. //} else
  29584. // return false;
  29585. }
  29586. bool QCPPolarGraph::addToLegend()
  29587. {
  29588. if (!mParentPlot || !mParentPlot->legend)
  29589. return false;
  29590. else
  29591. return addToLegend(mParentPlot->legend);
  29592. }
  29593. bool QCPPolarGraph::removeFromLegend(QCPLegend *legend) const
  29594. {
  29595. if (!legend)
  29596. {
  29597. qDebug() << Q_FUNC_INFO << "passed legend is null";
  29598. return false;
  29599. }
  29600. QCPPolarLegendItem *removableItem = 0;
  29601. for (int i=0; i<legend->itemCount(); ++i) // TODO: reduce this to code in QCPAbstractPlottable::removeFromLegend once unified
  29602. {
  29603. if (QCPPolarLegendItem *pli = qobject_cast<QCPPolarLegendItem*>(legend->item(i)))
  29604. {
  29605. if (pli->polarGraph() == this)
  29606. {
  29607. removableItem = pli;
  29608. break;
  29609. }
  29610. }
  29611. }
  29612. if (removableItem)
  29613. return legend->removeItem(removableItem);
  29614. else
  29615. return false;
  29616. }
  29617. bool QCPPolarGraph::removeFromLegend() const
  29618. {
  29619. if (!mParentPlot || !mParentPlot->legend)
  29620. return false;
  29621. else
  29622. return removeFromLegend(mParentPlot->legend);
  29623. }
  29624. double QCPPolarGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  29625. {
  29626. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  29627. return -1;
  29628. if (!mKeyAxis || !mValueAxis)
  29629. return -1;
  29630. if (mKeyAxis->rect().contains(pos.toPoint()))
  29631. {
  29632. QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  29633. double result = pointDistance(pos, closestDataPoint);
  29634. if (details)
  29635. {
  29636. int pointIndex = closestDataPoint-mDataContainer->constBegin();
  29637. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  29638. }
  29639. return result;
  29640. } else
  29641. return -1;
  29642. }
  29643. /* inherits documentation from base class */
  29644. QCPRange QCPPolarGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  29645. {
  29646. return mDataContainer->keyRange(foundRange, inSignDomain);
  29647. }
  29648. /* inherits documentation from base class */
  29649. QCPRange QCPPolarGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  29650. {
  29651. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  29652. }
  29653. /* inherits documentation from base class */
  29654. QRect QCPPolarGraph::clipRect() const
  29655. {
  29656. if (mKeyAxis)
  29657. return mKeyAxis.data()->rect();
  29658. else
  29659. return QRect();
  29660. }
  29661. void QCPPolarGraph::draw(QCPPainter *painter)
  29662. {
  29663. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  29664. if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
  29665. if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
  29666. painter->setClipRegion(mKeyAxis->exactClipRegion());
  29667. QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
  29668. // loop over and draw segments of unselected/selected data:
  29669. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  29670. getDataSegments(selectedSegments, unselectedSegments);
  29671. allSegments << unselectedSegments << selectedSegments;
  29672. for (int i=0; i<allSegments.size(); ++i)
  29673. {
  29674. bool isSelectedSegment = i >= unselectedSegments.size();
  29675. // get line pixel points appropriate to line style:
  29676. QCPDataRange lineDataRange = isSelectedSegment ? allSegments.at(i) : allSegments.at(i).adjusted(-1, 1); // unselected segments extend lines to bordering selected data point (safe to exceed total data bounds in first/last segment, getLines takes care)
  29677. getLines(&lines, lineDataRange);
  29678. // check data validity if flag set:
  29679. #ifdef QCUSTOMPLOT_CHECK_DATA
  29680. QCPGraphDataContainer::const_iterator it;
  29681. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  29682. {
  29683. if (QCP::isInvalidData(it->key, it->value))
  29684. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
  29685. }
  29686. #endif
  29687. // draw fill of graph:
  29688. //if (isSelectedSegment && mSelectionDecorator)
  29689. // mSelectionDecorator->applyBrush(painter);
  29690. //else
  29691. painter->setBrush(mBrush);
  29692. painter->setPen(Qt::NoPen);
  29693. drawFill(painter, &lines);
  29694. // draw line:
  29695. if (mLineStyle != lsNone)
  29696. {
  29697. //if (isSelectedSegment && mSelectionDecorator)
  29698. // mSelectionDecorator->applyPen(painter);
  29699. //else
  29700. painter->setPen(mPen);
  29701. painter->setBrush(Qt::NoBrush);
  29702. drawLinePlot(painter, lines);
  29703. }
  29704. // draw scatters:
  29705. QCPScatterStyle finalScatterStyle = mScatterStyle;
  29706. //if (isSelectedSegment && mSelectionDecorator)
  29707. // finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
  29708. if (!finalScatterStyle.isNone())
  29709. {
  29710. getScatters(&scatters, allSegments.at(i));
  29711. drawScatterPlot(painter, scatters, finalScatterStyle);
  29712. }
  29713. }
  29714. // draw other selection decoration that isn't just line/scatter pens and brushes:
  29715. //if (mSelectionDecorator)
  29716. // mSelectionDecorator->drawDecoration(painter, selection());
  29717. }
  29718. QCP::Interaction QCPPolarGraph::selectionCategory() const
  29719. {
  29720. return QCP::iSelectPlottables;
  29721. }
  29722. void QCPPolarGraph::applyDefaultAntialiasingHint(QCPPainter *painter) const
  29723. {
  29724. applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
  29725. }
  29726. /* inherits documentation from base class */
  29727. void QCPPolarGraph::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  29728. {
  29729. Q_UNUSED(event)
  29730. if (mSelectable != QCP::stNone)
  29731. {
  29732. QCPDataSelection newSelection = details.value<QCPDataSelection>();
  29733. QCPDataSelection selectionBefore = mSelection;
  29734. if (additive)
  29735. {
  29736. if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
  29737. {
  29738. if (selected())
  29739. setSelection(QCPDataSelection());
  29740. else
  29741. setSelection(newSelection);
  29742. } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
  29743. {
  29744. if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
  29745. setSelection(mSelection-newSelection);
  29746. else
  29747. setSelection(mSelection+newSelection);
  29748. }
  29749. } else
  29750. setSelection(newSelection);
  29751. if (selectionStateChanged)
  29752. *selectionStateChanged = mSelection != selectionBefore;
  29753. }
  29754. }
  29755. /* inherits documentation from base class */
  29756. void QCPPolarGraph::deselectEvent(bool *selectionStateChanged)
  29757. {
  29758. if (mSelectable != QCP::stNone)
  29759. {
  29760. QCPDataSelection selectionBefore = mSelection;
  29761. setSelection(QCPDataSelection());
  29762. if (selectionStateChanged)
  29763. *selectionStateChanged = mSelection != selectionBefore;
  29764. }
  29765. }
  29766. /*! \internal
  29767. Draws lines between the points in \a lines, given in pixel coordinates.
  29768. \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
  29769. */
  29770. void QCPPolarGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
  29771. {
  29772. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  29773. {
  29774. applyDefaultAntialiasingHint(painter);
  29775. drawPolyline(painter, lines);
  29776. }
  29777. }
  29778. /*! \internal
  29779. Draws the fill of the graph using the specified \a painter, with the currently set brush.
  29780. Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref
  29781. getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons.
  29782. In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas),
  29783. this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to
  29784. operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN
  29785. segments of the two involved graphs, before passing the overlapping pairs to \ref
  29786. getChannelFillPolygon.
  29787. Pass the points of this graph's line as \a lines, in pixel coordinates.
  29788. \see drawLinePlot, drawImpulsePlot, drawScatterPlot
  29789. */
  29790. void QCPPolarGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
  29791. {
  29792. applyFillAntialiasingHint(painter);
  29793. if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
  29794. painter->drawPolygon(QPolygonF(*lines));
  29795. }
  29796. /*! \internal
  29797. Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
  29798. scatters will be drawn with \a painter and have the appearance as specified in \a style.
  29799. \see drawLinePlot, drawImpulsePlot
  29800. */
  29801. void QCPPolarGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
  29802. {
  29803. applyScattersAntialiasingHint(painter);
  29804. style.applyTo(painter, mPen);
  29805. for (int i=0; i<scatters.size(); ++i)
  29806. style.drawShape(painter, scatters.at(i).x(), scatters.at(i).y());
  29807. }
  29808. void QCPPolarGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  29809. {
  29810. // draw fill:
  29811. if (mBrush.style() != Qt::NoBrush)
  29812. {
  29813. applyFillAntialiasingHint(painter);
  29814. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  29815. }
  29816. // draw line vertically centered:
  29817. if (mLineStyle != lsNone)
  29818. {
  29819. applyDefaultAntialiasingHint(painter);
  29820. painter->setPen(mPen);
  29821. painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens
  29822. }
  29823. // draw scatter symbol:
  29824. if (!mScatterStyle.isNone())
  29825. {
  29826. applyScattersAntialiasingHint(painter);
  29827. // scale scatter pixmap if it's too large to fit in legend icon rect:
  29828. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  29829. {
  29830. QCPScatterStyle scaledStyle(mScatterStyle);
  29831. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  29832. scaledStyle.applyTo(painter, mPen);
  29833. scaledStyle.drawShape(painter, QRectF(rect).center());
  29834. } else
  29835. {
  29836. mScatterStyle.applyTo(painter, mPen);
  29837. mScatterStyle.drawShape(painter, QRectF(rect).center());
  29838. }
  29839. }
  29840. }
  29841. void QCPPolarGraph::applyFillAntialiasingHint(QCPPainter *painter) const
  29842. {
  29843. applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
  29844. }
  29845. void QCPPolarGraph::applyScattersAntialiasingHint(QCPPainter *painter) const
  29846. {
  29847. applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
  29848. }
  29849. double QCPPolarGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
  29850. {
  29851. closestData = mDataContainer->constEnd();
  29852. if (mDataContainer->isEmpty())
  29853. return -1.0;
  29854. if (mLineStyle == lsNone && mScatterStyle.isNone())
  29855. return -1.0;
  29856. // calculate minimum distances to graph data points and find closestData iterator:
  29857. double minDistSqr = (std::numeric_limits<double>::max)();
  29858. // determine which key range comes into question, taking selection tolerance around pos into account:
  29859. double posKeyMin, posKeyMax, dummy;
  29860. pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
  29861. pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
  29862. if (posKeyMin > posKeyMax)
  29863. qSwap(posKeyMin, posKeyMax);
  29864. // iterate over found data points and then choose the one with the shortest distance to pos:
  29865. QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
  29866. QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
  29867. for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
  29868. {
  29869. const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
  29870. if (currentDistSqr < minDistSqr)
  29871. {
  29872. minDistSqr = currentDistSqr;
  29873. closestData = it;
  29874. }
  29875. }
  29876. // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
  29877. if (mLineStyle != lsNone)
  29878. {
  29879. // line displayed, calculate distance to line segments:
  29880. QVector<QPointF> lineData;
  29881. getLines(&lineData, QCPDataRange(0, dataCount()));
  29882. QCPVector2D p(pixelPoint);
  29883. for (int i=0; i<lineData.size()-1; ++i)
  29884. {
  29885. const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
  29886. if (currentDistSqr < minDistSqr)
  29887. minDistSqr = currentDistSqr;
  29888. }
  29889. }
  29890. return qSqrt(minDistSqr);
  29891. }
  29892. int QCPPolarGraph::dataCount() const
  29893. {
  29894. return mDataContainer->size();
  29895. }
  29896. void QCPPolarGraph::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
  29897. {
  29898. selectedSegments.clear();
  29899. unselectedSegments.clear();
  29900. if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
  29901. {
  29902. if (selected())
  29903. selectedSegments << QCPDataRange(0, dataCount());
  29904. else
  29905. unselectedSegments << QCPDataRange(0, dataCount());
  29906. } else
  29907. {
  29908. QCPDataSelection sel(selection());
  29909. sel.simplify();
  29910. selectedSegments = sel.dataRanges();
  29911. unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
  29912. }
  29913. }
  29914. void QCPPolarGraph::drawPolyline(QCPPainter *painter, const QVector<QPointF> &lineData) const
  29915. {
  29916. // if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
  29917. if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
  29918. painter->pen().style() == Qt::SolidLine &&
  29919. !painter->modes().testFlag(QCPPainter::pmVectorized) &&
  29920. !painter->modes().testFlag(QCPPainter::pmNoCaching))
  29921. {
  29922. int i = 0;
  29923. bool lastIsNan = false;
  29924. const int lineDataSize = lineData.size();
  29925. while (i < lineDataSize && (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()))) // make sure first point is not NaN
  29926. ++i;
  29927. ++i; // because drawing works in 1 point retrospect
  29928. while (i < lineDataSize)
  29929. {
  29930. if (!qIsNaN(lineData.at(i).y()) && !qIsNaN(lineData.at(i).x())) // NaNs create a gap in the line
  29931. {
  29932. if (!lastIsNan)
  29933. painter->drawLine(lineData.at(i-1), lineData.at(i));
  29934. else
  29935. lastIsNan = false;
  29936. } else
  29937. lastIsNan = true;
  29938. ++i;
  29939. }
  29940. } else
  29941. {
  29942. int segmentStart = 0;
  29943. int i = 0;
  29944. const int lineDataSize = lineData.size();
  29945. while (i < lineDataSize)
  29946. {
  29947. if (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()) || qIsInf(lineData.at(i).y())) // NaNs create a gap in the line. Also filter Infs which make drawPolyline block
  29948. {
  29949. painter->drawPolyline(lineData.constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point
  29950. segmentStart = i+1;
  29951. }
  29952. ++i;
  29953. }
  29954. // draw last segment:
  29955. painter->drawPolyline(lineData.constData()+segmentStart, lineDataSize-segmentStart);
  29956. }
  29957. }
  29958. void QCPPolarGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
  29959. {
  29960. if (rangeRestriction.isEmpty())
  29961. {
  29962. end = mDataContainer->constEnd();
  29963. begin = end;
  29964. } else
  29965. {
  29966. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  29967. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  29968. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  29969. // get visible data range:
  29970. if (mPeriodic)
  29971. {
  29972. begin = mDataContainer->constBegin();
  29973. end = mDataContainer->constEnd();
  29974. } else
  29975. {
  29976. begin = mDataContainer->findBegin(keyAxis->range().lower);
  29977. end = mDataContainer->findEnd(keyAxis->range().upper);
  29978. }
  29979. // limit lower/upperEnd to rangeRestriction:
  29980. mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
  29981. }
  29982. }
  29983. /*! \internal
  29984. This method retrieves an optimized set of data points via \ref getOptimizedLineData, an branches
  29985. out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
  29986. according to the line style of the graph.
  29987. \a lines will be filled with points in pixel coordinates, that can be drawn with the according
  29988. draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
  29989. aren't necessarily the original data points. For example, step line styles require additional
  29990. points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
  29991. lines vector will be empty.
  29992. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  29993. conversion. In this function, the specified range may exceed the total data bounds without harm:
  29994. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  29995. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  29996. getDataSegments.
  29997. \see getScatters
  29998. */
  29999. void QCPPolarGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
  30000. {
  30001. if (!lines) return;
  30002. QCPGraphDataContainer::const_iterator begin, end;
  30003. getVisibleDataBounds(begin, end, dataRange);
  30004. if (begin == end)
  30005. {
  30006. lines->clear();
  30007. return;
  30008. }
  30009. QVector<QCPGraphData> lineData;
  30010. if (mLineStyle != lsNone)
  30011. getOptimizedLineData(&lineData, begin, end);
  30012. switch (mLineStyle)
  30013. {
  30014. case lsNone: lines->clear(); break;
  30015. case lsLine: *lines = dataToLines(lineData); break;
  30016. }
  30017. }
  30018. void QCPPolarGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
  30019. {
  30020. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  30021. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  30022. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  30023. if (!scatters) return;
  30024. QCPGraphDataContainer::const_iterator begin, end;
  30025. getVisibleDataBounds(begin, end, dataRange);
  30026. if (begin == end)
  30027. {
  30028. scatters->clear();
  30029. return;
  30030. }
  30031. QVector<QCPGraphData> data;
  30032. getOptimizedScatterData(&data, begin, end);
  30033. scatters->resize(data.size());
  30034. for (int i=0; i<data.size(); ++i)
  30035. {
  30036. if (!qIsNaN(data.at(i).value))
  30037. (*scatters)[i] = valueAxis->coordToPixel(data.at(i).key, data.at(i).value);
  30038. }
  30039. }
  30040. void QCPPolarGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
  30041. {
  30042. lineData->clear();
  30043. // TODO: fix for log axes and thick line style
  30044. const QCPRange range = mValueAxis->range();
  30045. bool reversed = mValueAxis->rangeReversed();
  30046. const double clipMargin = range.size()*0.05; // extra distance from visible circle, so optimized outside lines can cover more angle before having to place a dummy point to prevent tangents
  30047. const double upperClipValue = range.upper + (reversed ? 0 : range.size()*0.05+clipMargin); // clip slightly outside of actual range to avoid line thicknesses to peek into visible circle
  30048. const double lowerClipValue = range.lower - (reversed ? range.size()*0.05+clipMargin : 0); // clip slightly outside of actual range to avoid line thicknesses to peek into visible circle
  30049. const double maxKeySkip = qAsin(qSqrt(clipMargin*(clipMargin+2*range.size()))/(range.size()+clipMargin))/M_PI*mKeyAxis->range().size(); // the maximum angle between two points on outer circle (r=clipValue+clipMargin) before connecting line becomes tangent to inner circle (r=clipValue)
  30050. double skipBegin = 0;
  30051. bool belowRange = false;
  30052. bool aboveRange = false;
  30053. QCPGraphDataContainer::const_iterator it = begin;
  30054. while (it != end)
  30055. {
  30056. if (it->value < lowerClipValue)
  30057. {
  30058. if (aboveRange) // jumped directly from above to below visible range, draw previous point so entry angle is correct
  30059. {
  30060. aboveRange = false;
  30061. if (!reversed) // TODO: with inner radius, we'll need else case here with projected border point
  30062. lineData->append(*(it-1));
  30063. }
  30064. if (!belowRange)
  30065. {
  30066. skipBegin = it->key;
  30067. lineData->append(QCPGraphData(it->key, lowerClipValue));
  30068. belowRange = true;
  30069. }
  30070. if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle)
  30071. {
  30072. skipBegin += maxKeySkip;
  30073. lineData->append(QCPGraphData(skipBegin, lowerClipValue));
  30074. }
  30075. } else if (it->value > upperClipValue)
  30076. {
  30077. if (belowRange) // jumped directly from below to above visible range, draw previous point so entry angle is correct (if lower means outer, so if reversed axis)
  30078. {
  30079. belowRange = false;
  30080. if (reversed)
  30081. lineData->append(*(it-1));
  30082. }
  30083. if (!aboveRange)
  30084. {
  30085. skipBegin = it->key;
  30086. lineData->append(QCPGraphData(it->key, upperClipValue));
  30087. aboveRange = true;
  30088. }
  30089. if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle)
  30090. {
  30091. skipBegin += maxKeySkip;
  30092. lineData->append(QCPGraphData(skipBegin, upperClipValue));
  30093. }
  30094. } else // value within bounds where we don't optimize away points
  30095. {
  30096. if (aboveRange)
  30097. {
  30098. aboveRange = false;
  30099. if (!reversed)
  30100. lineData->append(*(it-1)); // just entered from above, draw previous point so entry angle is correct (if above means outer, so if not reversed axis)
  30101. }
  30102. if (belowRange)
  30103. {
  30104. belowRange = false;
  30105. if (reversed)
  30106. lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis)
  30107. }
  30108. lineData->append(*it); // inside visible circle, add point normally
  30109. }
  30110. ++it;
  30111. }
  30112. // to make fill not erratic, add last point normally if it was outside visible circle:
  30113. if (aboveRange)
  30114. {
  30115. aboveRange = false;
  30116. if (!reversed)
  30117. lineData->append(*(it-1)); // just entered from above, draw previous point so entry angle is correct (if above means outer, so if not reversed axis)
  30118. }
  30119. if (belowRange)
  30120. {
  30121. belowRange = false;
  30122. if (reversed)
  30123. lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis)
  30124. }
  30125. }
  30126. void QCPPolarGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
  30127. {
  30128. scatterData->clear();
  30129. const QCPRange range = mValueAxis->range();
  30130. bool reversed = mValueAxis->rangeReversed();
  30131. const double clipMargin = range.size()*0.05;
  30132. const double upperClipValue = range.upper + (reversed ? 0 : clipMargin); // clip slightly outside of actual range to avoid scatter size to peek into visible circle
  30133. const double lowerClipValue = range.lower - (reversed ? clipMargin : 0); // clip slightly outside of actual range to avoid scatter size to peek into visible circle
  30134. QCPGraphDataContainer::const_iterator it = begin;
  30135. while (it != end)
  30136. {
  30137. if (it->value > lowerClipValue && it->value < upperClipValue)
  30138. scatterData->append(*it);
  30139. ++it;
  30140. }
  30141. }
  30142. /*! \internal
  30143. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  30144. coordinate points which are suitable for drawing the line style \ref lsLine.
  30145. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  30146. getLines if the line style is set accordingly.
  30147. \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  30148. */
  30149. QVector<QPointF> QCPPolarGraph::dataToLines(const QVector<QCPGraphData> &data) const
  30150. {
  30151. QVector<QPointF> result;
  30152. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  30153. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  30154. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  30155. // transform data points to pixels:
  30156. result.resize(data.size());
  30157. for (int i=0; i<data.size(); ++i)
  30158. result[i] = mValueAxis->coordToPixel(data.at(i).key, data.at(i).value);
  30159. return result;
  30160. }
  30161. /* end of 'src/polar/polargraph.cpp' */