QCustomPlot.cpp 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499
  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. 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. 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((double) mRect.left()+ (double)mRect.width())};
  2337. else
  2338. return {axis->pixelToCoord((double)mRect.top()+ (double)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. 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. 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. 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. 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. 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::MarginSide::msLeft, QList<QCPLayoutElement*>());
  2482. mChildren.insert(QCP::MarginSide::msRight, QList<QCPLayoutElement*>());
  2483. mChildren.insert(QCP::MarginSide::msTop, QList<QCPLayoutElement*>());
  2484. mChildren.insert(QCP::MarginSide::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(SizeConstraintRect::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::MarginSide::msAll)
  2623. {
  2624. }
  2625. QCPLayoutElement::~QCPLayoutElement()
  2626. {
  2627. setMarginGroup(QCP::MarginSide::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::MarginSide::msLeft)) sideVector.append(QCP::MarginSide::msLeft);
  2772. if (sides.testFlag(QCP::MarginSide::msRight)) sideVector.append(QCP::MarginSide::msRight);
  2773. if (sides.testFlag(QCP::MarginSide::msTop)) sideVector.append(QCP::MarginSide::msTop);
  2774. if (sides.testFlag(QCP::MarginSide::msBottom)) sideVector.append(QCP::MarginSide::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::MarginSide::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::MarginSide::msLeft << QCP::MarginSide::msRight << QCP::MarginSide::msTop << QCP::MarginSide::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::SizeConstraintRect::scrInnerRect)
  3293. minOuter.rwidth() += el->margins().left() + el->margins().right();
  3294. if (minOuter.height() > 0 && el->sizeConstraintRect() == QCPLayoutElement::SizeConstraintRect::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::SizeConstraintRect::scrInnerRect)
  3313. maxOuter.rwidth() += el->margins().left() + el->margins().right();
  3314. if (maxOuter.height() < QWIDGETSIZE_MAX && el->sizeConstraintRect() == QCPLayoutElement::SizeConstraintRect::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(FillOrder::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 == FillOrder::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 FillOrder::foRowsFirst: return column*rowCount() + row;
  3715. case FillOrder::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 FillOrder::foRowsFirst:
  3750. {
  3751. column = index / nRows;
  3752. row = index % nRows;
  3753. break;
  3754. }
  3755. case FillOrder::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 InsetPlacement::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) == InsetPlacement::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) == InsetPlacement::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(InsetPlacement::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(InsetPlacement::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(EndingStyle::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 EndingStyle::esNone:
  4363. return 0;
  4364. case EndingStyle::esFlatArrow:
  4365. case EndingStyle::esSpikeArrow:
  4366. case EndingStyle::esLineArrow:
  4367. case EndingStyle::esSkewedBar:
  4368. return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length
  4369. case EndingStyle::esDisc:
  4370. case EndingStyle::esSquare:
  4371. case EndingStyle::esDiamond:
  4372. case EndingStyle::esBar:
  4373. case EndingStyle::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 EndingStyle::esNone:
  4392. case EndingStyle::esLineArrow:
  4393. case EndingStyle::esSkewedBar:
  4394. case EndingStyle::esBar:
  4395. case EndingStyle::esHalfBar:
  4396. return 0;
  4397. case EndingStyle::esFlatArrow:
  4398. return mLength;
  4399. case EndingStyle::esDisc:
  4400. case EndingStyle::esSquare:
  4401. case EndingStyle::esDiamond:
  4402. return mWidth*0.5;
  4403. case EndingStyle::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 == QCPLineEnding::EndingStyle::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 EndingStyle::esNone: break;
  4428. case EndingStyle::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 EndingStyle::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 EndingStyle::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 EndingStyle::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 EndingStyle::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 EndingStyle::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 EndingStyle::esBar:
  4504. {
  4505. painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF());
  4506. break;
  4507. }
  4508. case EndingStyle::esHalfBar:
  4509. {
  4510. painter->drawLine((pos+widthVec).toPointF(), pos.toPointF());
  4511. break;
  4512. }
  4513. case EndingStyle::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(AnchorSide::asLeft),
  4555. mAnchorReferenceType(AnchorReferenceType::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::LabelSide::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::LabelSide::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::LabelSide::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 AnchorSide::asLeft: return tickPos+QPointF(mPadding, 0);
  4789. case AnchorSide::asRight: return tickPos+QPointF(-mPadding, 0);
  4790. case AnchorSide::asTop: return tickPos+QPointF(0, mPadding);
  4791. case AnchorSide::asBottom: return tickPos+QPointF(0, -mPadding);
  4792. case AnchorSide::asTopLeft: return tickPos+QPointF(mPadding*M_SQRT1_2, mPadding*M_SQRT1_2);
  4793. case AnchorSide::asTopRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, mPadding*M_SQRT1_2);
  4794. case AnchorSide::asBottomRight: return tickPos+QPointF(-mPadding*M_SQRT1_2, -mPadding*M_SQRT1_2);
  4795. case AnchorSide::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 == AnchorReferenceType::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, (double)-labelData.totalBounds.height() + (double)mLetterDescent + (double)mLetterCapHeight); // shifts origin to true top of capital (or number) characters
  4934. if (labelData.side == AnchorSide::asLeft || labelData.side == AnchorSide::asRight) // anchor is centered vertically
  4935. labelData.transform.translate(0, -mLetterCapHeight/2.0);
  4936. else if (labelData.side == AnchorSide::asTop || labelData.side == AnchorSide::asBottom) // anchor is centered horizontally
  4937. labelData.transform.translate(-labelData.totalBounds.width()/2.0, 0);
  4938. if (labelData.side == AnchorSide::asTopRight || labelData.side == AnchorSide::asRight || labelData.side == AnchorSide::asBottomRight) // anchor is at right
  4939. labelData.transform.translate(-labelData.totalBounds.width(), 0);
  4940. if (labelData.side == AnchorSide::asBottomLeft || labelData.side == AnchorSide::asBottom || labelData.side == AnchorSide::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 == AnchorReferenceType::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 AnchorSide::asTopLeft;
  5013. else if (anchorNormal.y() < -sideVert) return AnchorSide::asBottomLeft;
  5014. else return AnchorSide::asLeft;
  5015. } else if (anchorNormal.x() < -sideHorz)
  5016. {
  5017. if (anchorNormal.y() > sideVert) return AnchorSide::asTopRight;
  5018. else if (anchorNormal.y() < -sideVert) return AnchorSide::asBottomRight;
  5019. else return AnchorSide::asRight;
  5020. } else
  5021. {
  5022. if (anchorNormal.y() > 0) return AnchorSide::asTop;
  5023. else return AnchorSide::asBottom;
  5024. }
  5025. return AnchorSide::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 == AnchorSide::asTop) result = rotateClockwise ? AnchorSide::asLeft : AnchorSide::asRight;
  5036. else if (side == AnchorSide::asBottom) result = rotateClockwise ? AnchorSide::asRight : AnchorSide::asLeft;
  5037. else if (side == AnchorSide::asTopLeft) result = rotateClockwise ? AnchorSide::asLeft : AnchorSide::asTop;
  5038. else if (side == AnchorSide::asTopRight) result = rotateClockwise ? AnchorSide::asTop : AnchorSide::asRight;
  5039. else if (side == AnchorSide::asBottomLeft) result = rotateClockwise ? AnchorSide::asBottom : AnchorSide::asLeft;
  5040. else if (side == AnchorSide::asBottomRight) result = rotateClockwise ? AnchorSide::asRight : AnchorSide::asBottom;
  5041. } else // for full rotation by +/-90 degrees, other sides are more appropriate for centering on anchor:
  5042. {
  5043. if (side == AnchorSide::asLeft) result = rotateClockwise ? AnchorSide::asBottom : AnchorSide::asTop;
  5044. else if (side == AnchorSide::asRight) result = rotateClockwise ? AnchorSide::asTop : AnchorSide::asBottom;
  5045. else if (side == AnchorSide::asTop) result = rotateClockwise ? AnchorSide::asLeft : AnchorSide::asRight;
  5046. else if (side == AnchorSide::asBottom) result = rotateClockwise ? AnchorSide::asRight : AnchorSide::asLeft;
  5047. else if (side == AnchorSide::asTopLeft) result = rotateClockwise ? AnchorSide::asBottomLeft : AnchorSide::asTopRight;
  5048. else if (side == AnchorSide::asTopRight) result = rotateClockwise ? AnchorSide::asTopLeft : AnchorSide::asBottomRight;
  5049. else if (side == AnchorSide::asBottomLeft) result = rotateClockwise ? AnchorSide::asBottomRight : AnchorSide::asTopLeft;
  5050. else if (side == AnchorSide::asBottomRight) result = rotateClockwise ? AnchorSide::asTopRight : AnchorSide::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(TickStepStrategy::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 = ((double)ticks.at(i)- (double)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 TickStepStrategy::tssReadability:
  5405. {
  5406. return pickClosest(mantissa, QVector<double>() << 1.0 << 2.0 << 2.5 << 5.0 << 10.0)*magnitude;
  5407. }
  5408. case TickStepStrategy::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(DateStrategy::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 = DateStrategy::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.0 << 2.5 << 5.0 << 10.0 << 15.0 << 30.0 << 60.0 << 2.5*60.0 << 5.0*60.0 << 10.0*60.0
  5572. << 15.0*60.0 << 30.0*60.0 << 60.0*60.0 // second, minute, hour range
  5573. << 3600.0*2.0 << 3600.0*3.0 << 3600.0*6.0 << 3600.0*12.0 << 3600.0*24.0 // hour to day range
  5574. << 86400.0*2.0 << 86400.0*5.0 << 86400.0*7.0 << 86400.0*14.0 << 86400.0*30.4375 << 86400.0*30.4375*2.0
  5575. << 86400.0*30.4375*3.0 << 86400.0*30.4375*6.0 << 86400.0*30.4375*12.0); // day, week, month range (avg. days per month includes leap years)
  5576. if (result > 86400*30.4375-1) // month tick intervals or larger
  5577. mDateStrategy = DateStrategy::dsUniformDayInMonth;
  5578. else if (result > (3600.0*24.0-1.0)) // day tick intervals or larger
  5579. mDateStrategy = DateStrategy::dsUniformTimeInDay;
  5580. } else // more than a year, go back to normal clean mantissa algorithm but in units of years
  5581. {
  5582. const double secondsPerYear = 86400*30.4375*12; // average including leap years
  5583. result = cleanMantissa(result/secondsPerYear)*secondsPerYear;
  5584. mDateStrategy = DateStrategy::dsUniformDayInMonth;
  5585. }
  5586. return result;
  5587. }
  5588. /*! \internal
  5589. Returns a sensible sub tick count with intervals appropriate for a date-time-display, such as weekly,
  5590. monthly, bi-monthly, etc.
  5591. \seebaseclassmethod
  5592. */
  5593. int QCPAxisTickerDateTime::getSubTickCount(double tickStep)
  5594. {
  5595. int result = QCPAxisTicker::getSubTickCount(tickStep);
  5596. switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day/week/month range (as specified in getTickStep)
  5597. {
  5598. case 5*60: result = 4; break;
  5599. case 10*60: result = 1; break;
  5600. case 15*60: result = 2; break;
  5601. case 30*60: result = 1; break;
  5602. case 60*60: result = 3; break;
  5603. case 3600*2: result = 3; break;
  5604. case 3600*3: result = 2; break;
  5605. case 3600*6: result = 1; break;
  5606. case 3600*12: result = 3; break;
  5607. case 3600*24: result = 3; break;
  5608. case 86400*2: result = 1; break;
  5609. case 86400*5: result = 4; break;
  5610. case 86400*7: result = 6; break;
  5611. case 86400*14: result = 1; break;
  5612. case int(86400*30.4375+0.5): result = 3; break;
  5613. case int(86400*30.4375*2+0.5): result = 1; break;
  5614. case int(86400*30.4375*3+0.5): result = 2; break;
  5615. case int(86400*30.4375*6+0.5): result = 5; break;
  5616. case int(86400*30.4375*12+0.5): result = 3; break;
  5617. }
  5618. return result;
  5619. }
  5620. /*! \internal
  5621. Generates a date/time tick label for tick coordinate \a tick, based on the currently set format
  5622. (\ref setDateTimeFormat), time spec (\ref setDateTimeSpec), and possibly time zone (\ref
  5623. setTimeZone).
  5624. \seebaseclassmethod
  5625. */
  5626. QString QCPAxisTickerDateTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5627. {
  5628. Q_UNUSED(precision)
  5629. Q_UNUSED(formatChar)
  5630. # if QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)
  5631. if (mDateTimeSpec == Qt::TimeZone)
  5632. return locale.toString(keyToDateTime(tick).toTimeZone(mTimeZone), mDateTimeFormat);
  5633. else
  5634. return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
  5635. # else
  5636. return locale.toString(keyToDateTime(tick).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
  5637. # endif
  5638. }
  5639. /*! \internal
  5640. Uses the passed \a tickStep as a guiding value and applies corrections in order to obtain
  5641. non-uniform tick intervals but intuitive tick labels, e.g. falling on the same day of each month.
  5642. \seebaseclassmethod
  5643. */
  5644. QVector<double> QCPAxisTickerDateTime::createTickVector(double tickStep, const QCPRange &range)
  5645. {
  5646. QVector<double> result = QCPAxisTicker::createTickVector(tickStep, range);
  5647. if (!result.isEmpty())
  5648. {
  5649. if (mDateStrategy == DateStrategy::dsUniformTimeInDay)
  5650. {
  5651. QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // the time of this datetime will be set for all other ticks, if possible
  5652. QDateTime tickDateTime;
  5653. for (int i=0; i<result.size(); ++i)
  5654. {
  5655. tickDateTime = keyToDateTime(result.at(i));
  5656. tickDateTime.setTime(uniformDateTime.time());
  5657. result[i] = dateTimeToKey(tickDateTime);
  5658. }
  5659. } else if (mDateStrategy == DateStrategy::dsUniformDayInMonth)
  5660. {
  5661. QDateTime uniformDateTime = keyToDateTime(mTickOrigin); // this day (in month) and time will be set for all other ticks, if possible
  5662. QDateTime tickDateTime;
  5663. for (int i=0; i<result.size(); ++i)
  5664. {
  5665. tickDateTime = keyToDateTime(result.at(i));
  5666. tickDateTime.setTime(uniformDateTime.time());
  5667. 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)
  5668. 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. 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
  5671. tickDateTime = tickDateTime.addMonths(-1);
  5672. tickDateTime.setDate(QDate(tickDateTime.date().year(), tickDateTime.date().month(), thisUniformDay));
  5673. result[i] = dateTimeToKey(tickDateTime);
  5674. }
  5675. }
  5676. }
  5677. return result;
  5678. }
  5679. /*!
  5680. A convenience method which turns \a key (in seconds since Epoch 1. Jan 1970, 00:00 UTC) into a
  5681. QDateTime object. This can be used to turn axis coordinates to actual QDateTimes.
  5682. The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
  5683. works around the lack of a QDateTime::fromMSecsSinceEpoch in Qt 4.6)
  5684. \see dateTimeToKey
  5685. */
  5686. QDateTime QCPAxisTickerDateTime::keyToDateTime(double key)
  5687. {
  5688. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5689. return QDateTime::fromTime_t(key).addMSecs((key-(qint64)key)*1000);
  5690. # else
  5691. return QDateTime::fromMSecsSinceEpoch(qint64(key*1000.0));
  5692. # endif
  5693. }
  5694. /*! \overload
  5695. A convenience method which turns a QDateTime object into a double value that corresponds to
  5696. seconds since Epoch (1. Jan 1970, 00:00 UTC). This is the format used as axis coordinates by
  5697. QCPAxisTickerDateTime.
  5698. The accuracy achieved by this method is one millisecond, irrespective of the used Qt version (it
  5699. works around the lack of a QDateTime::toMSecsSinceEpoch in Qt 4.6)
  5700. \see keyToDateTime
  5701. */
  5702. double QCPAxisTickerDateTime::dateTimeToKey(const QDateTime &dateTime)
  5703. {
  5704. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5705. return dateTime.toTime_t()+dateTime.time().msec()/1000.0;
  5706. # else
  5707. return dateTime.toMSecsSinceEpoch()/1000.0;
  5708. # endif
  5709. }
  5710. /*! \overload
  5711. A convenience method which turns a QDate object into a double value that corresponds to seconds
  5712. since Epoch (1. Jan 1970, 00:00 UTC). This is the format used
  5713. as axis coordinates by QCPAxisTickerDateTime.
  5714. The returned value will be the start of the passed day of \a date, interpreted in the given \a
  5715. timeSpec.
  5716. \see keyToDateTime
  5717. */
  5718. double QCPAxisTickerDateTime::dateTimeToKey(const QDate &date, Qt::TimeSpec timeSpec)
  5719. {
  5720. # if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
  5721. return QDateTime(date, QTime(0, 0), timeSpec).toTime_t();
  5722. # elif QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  5723. return QDateTime(date, QTime(0, 0), timeSpec).toMSecsSinceEpoch()/1000.0;
  5724. # else
  5725. return date.startOfDay(timeSpec).toMSecsSinceEpoch()/1000.0;
  5726. # endif
  5727. }
  5728. /* end of 'src/axis/axistickerdatetime.cpp' */
  5729. /* including file 'src/axis/axistickertime.cpp' */
  5730. /* modified 2021-03-29T02:30:44, size 11745 */
  5731. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5732. //////////////////// QCPAxisTickerTime
  5733. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5734. /*! \class QCPAxisTickerTime
  5735. \brief Specialized axis ticker for time spans in units of milliseconds to days
  5736. \image html axisticker-time.png
  5737. This QCPAxisTicker subclass generates ticks that corresponds to time intervals.
  5738. The format of the time display in the tick labels is controlled with \ref setTimeFormat and \ref
  5739. setFieldWidth. The time coordinate is in the unit of seconds with respect to the time coordinate
  5740. zero. Unlike with QCPAxisTickerDateTime, the ticks don't correspond to a specific calendar date
  5741. and time.
  5742. The time can be displayed in milliseconds, seconds, minutes, hours and days. Depending on the
  5743. largest available unit in the format specified with \ref setTimeFormat, any time spans above will
  5744. be carried in that largest unit. So for example if the format string is "%m:%s" and a tick at
  5745. coordinate value 7815 (being 2 hours, 10 minutes and 15 seconds) is created, the resulting tick
  5746. label will show "130:15" (130 minutes, 15 seconds). If the format string is "%h:%m:%s", the hour
  5747. unit will be used and the label will thus be "02:10:15". Negative times with respect to the axis
  5748. zero will carry a leading minus sign.
  5749. The ticker can be created and assigned to an axis like this:
  5750. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation
  5751. Here is an example of a time axis providing time information in days, hours and minutes. Due to
  5752. the axis range spanning a few days and the wanted tick count (\ref setTickCount), the ticker
  5753. decided to use tick steps of 12 hours:
  5754. \image html axisticker-time2.png
  5755. The format string for this example is
  5756. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertime-creation-2
  5757. \note If you rather wish to display calendar dates and times, have a look at QCPAxisTickerDateTime
  5758. instead.
  5759. */
  5760. /*!
  5761. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5762. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5763. */
  5764. QCPAxisTickerTime::QCPAxisTickerTime() :
  5765. mTimeFormat(QLatin1String("%h:%m:%s")),
  5766. mSmallestUnit(TimeUnit::tuSeconds),
  5767. mBiggestUnit(TimeUnit::tuHours)
  5768. {
  5769. setTickCount(4);
  5770. mFieldWidth[TimeUnit::tuMilliseconds] = 3;
  5771. mFieldWidth[TimeUnit::tuSeconds] = 2;
  5772. mFieldWidth[TimeUnit::tuMinutes] = 2;
  5773. mFieldWidth[TimeUnit::tuHours] = 2;
  5774. mFieldWidth[TimeUnit::tuDays] = 1;
  5775. mFormatPattern[TimeUnit::tuMilliseconds] = QLatin1String("%z");
  5776. mFormatPattern[TimeUnit::tuSeconds] = QLatin1String("%s");
  5777. mFormatPattern[TimeUnit::tuMinutes] = QLatin1String("%m");
  5778. mFormatPattern[TimeUnit::tuHours] = QLatin1String("%h");
  5779. mFormatPattern[TimeUnit::tuDays] = QLatin1String("%d");
  5780. }
  5781. /*!
  5782. Sets the format that will be used to display time in the tick labels.
  5783. The available patterns are:
  5784. - %%z for milliseconds
  5785. - %%s for seconds
  5786. - %%m for minutes
  5787. - %%h for hours
  5788. - %%d for days
  5789. The field width (zero padding) can be controlled for each unit with \ref setFieldWidth.
  5790. The largest unit that appears in \a format will carry all the remaining time of a certain tick
  5791. coordinate, even if it overflows the natural limit of the unit. For example, if %%m is the
  5792. largest unit it might become larger than 59 in order to consume larger time values. If on the
  5793. other hand %%h is available, the minutes will wrap around to zero after 59 and the time will
  5794. carry to the hour digit.
  5795. */
  5796. void QCPAxisTickerTime::setTimeFormat(const QString &format)
  5797. {
  5798. mTimeFormat = format;
  5799. // determine smallest and biggest unit in format, to optimize unit replacement and allow biggest
  5800. // unit to consume remaining time of a tick value and grow beyond its modulo (e.g. min > 59)
  5801. mSmallestUnit = TimeUnit::tuMilliseconds;
  5802. mBiggestUnit = TimeUnit::tuMilliseconds;
  5803. bool hasSmallest = false;
  5804. for (int i = (int)TimeUnit::tuMilliseconds; i <= (int)TimeUnit::tuDays; ++i)
  5805. {
  5806. TimeUnit unit = static_cast<TimeUnit>(i);
  5807. if (mTimeFormat.contains(mFormatPattern.value(unit)))
  5808. {
  5809. if (!hasSmallest)
  5810. {
  5811. mSmallestUnit = unit;
  5812. hasSmallest = true;
  5813. }
  5814. mBiggestUnit = unit;
  5815. }
  5816. }
  5817. }
  5818. /*!
  5819. Sets the field widh of the specified \a unit to be \a width digits, when displayed in the tick
  5820. label. If the number for the specific unit is shorter than \a width, it will be padded with an
  5821. according number of zeros to the left in order to reach the field width.
  5822. \see setTimeFormat
  5823. */
  5824. void QCPAxisTickerTime::setFieldWidth(QCPAxisTickerTime::TimeUnit unit, int width)
  5825. {
  5826. mFieldWidth[unit] = qMax(width, 1);
  5827. }
  5828. /*! \internal
  5829. Returns the tick step appropriate for time displays, depending on the provided \a range and the
  5830. smallest available time unit in the current format (\ref setTimeFormat). For example if the unit
  5831. of seconds isn't available in the format, this method will not generate steps (like 2.5 minutes)
  5832. that require sub-minute precision to be displayed correctly.
  5833. \seebaseclassmethod
  5834. */
  5835. double QCPAxisTickerTime::getTickStep(const QCPRange &range)
  5836. {
  5837. double result = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  5838. if (result < 1) // ideal tick step is below 1 second -> use normal clean mantissa algorithm in units of seconds
  5839. {
  5840. if (mSmallestUnit == TimeUnit::tuMilliseconds)
  5841. result = qMax(cleanMantissa(result), 0.001); // smallest tick step is 1 millisecond
  5842. else // have no milliseconds available in format, so stick with 1 second tickstep
  5843. result = 1.0;
  5844. } else if (result < 3600*24) // below a day
  5845. {
  5846. // the filling of availableSteps seems a bit contorted but it fills in a sorted fashion and thus saves a post-fill sorting run
  5847. QVector<double> availableSteps;
  5848. // seconds range:
  5849. if (mSmallestUnit <= TimeUnit::tuSeconds)
  5850. availableSteps << 1;
  5851. if (mSmallestUnit == TimeUnit::tuMilliseconds)
  5852. availableSteps << 2.5; // only allow half second steps if milliseconds are there to display it
  5853. else if (mSmallestUnit == TimeUnit::tuSeconds)
  5854. availableSteps << 2.0;
  5855. if (mSmallestUnit <= TimeUnit::tuSeconds)
  5856. availableSteps << 5.0 << 10.0 << 15.0 << 30.0;
  5857. // minutes range:
  5858. if (mSmallestUnit <= TimeUnit::tuMinutes)
  5859. availableSteps << 1.0 *60.0;
  5860. if (mSmallestUnit <= TimeUnit::tuSeconds)
  5861. availableSteps << 2.5*60.0; // only allow half minute steps if seconds are there to display it
  5862. else if (mSmallestUnit == TimeUnit::tuMinutes)
  5863. availableSteps << 2.0 *60.0;
  5864. if (mSmallestUnit <= TimeUnit::tuMinutes)
  5865. availableSteps << 5.0 *60.0 << 10.0 *60.0 << 15.0 *60.0 << 30.0 *60.0;
  5866. // hours range:
  5867. if (mSmallestUnit <= TimeUnit::tuHours)
  5868. availableSteps << 1.0 * 3600.0 << 2.0 * 3600.0 << 3.0 *3600.0 << 6.0 *3600.0 << 12.0 *3600.0 << 24.0 *3600.0;
  5869. // pick available step that is most appropriate to approximate ideal step:
  5870. result = pickClosest(result, availableSteps);
  5871. } else // more than a day, go back to normal clean mantissa algorithm but in units of days
  5872. {
  5873. const double secondsPerDay = 3600*24;
  5874. result = cleanMantissa(result/secondsPerDay)*secondsPerDay;
  5875. }
  5876. return result;
  5877. }
  5878. /*! \internal
  5879. Returns the sub tick count appropriate for the provided \a tickStep and time displays.
  5880. \seebaseclassmethod
  5881. */
  5882. int QCPAxisTickerTime::getSubTickCount(double tickStep)
  5883. {
  5884. int result = QCPAxisTicker::getSubTickCount(tickStep);
  5885. switch (qRound(tickStep)) // hand chosen subticks for specific minute/hour/day range (as specified in getTickStep)
  5886. {
  5887. case 5*60: result = 4; break;
  5888. case 10*60: result = 1; break;
  5889. case 15*60: result = 2; break;
  5890. case 30*60: result = 1; break;
  5891. case 60*60: result = 3; break;
  5892. case 3600*2: result = 3; break;
  5893. case 3600*3: result = 2; break;
  5894. case 3600*6: result = 1; break;
  5895. case 3600*12: result = 3; break;
  5896. case 3600*24: result = 3; break;
  5897. }
  5898. return result;
  5899. }
  5900. /*! \internal
  5901. Returns the tick label corresponding to the provided \a tick and the configured format and field
  5902. widths (\ref setTimeFormat, \ref setFieldWidth).
  5903. \seebaseclassmethod
  5904. */
  5905. QString QCPAxisTickerTime::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  5906. {
  5907. Q_UNUSED(precision)
  5908. Q_UNUSED(formatChar)
  5909. Q_UNUSED(locale)
  5910. bool negative = tick < 0;
  5911. if (negative) tick *= -1;
  5912. double values[(int)TimeUnit::tuDays+1]; // contains the msec/sec/min/... value with its respective modulo (e.g. minute 0..59)
  5913. double restValues[(int)TimeUnit::tuDays+1]; // contains the msec/sec/min/... value as if it's the largest available unit and thus consumes the remaining time
  5914. restValues[(int)TimeUnit::tuMilliseconds] = tick*1000;
  5915. values[(int)TimeUnit::tuMilliseconds] = modf(restValues[(int)TimeUnit::tuMilliseconds]/1000, &restValues[(int)TimeUnit::tuSeconds])*1000;
  5916. values[(int)TimeUnit::tuSeconds] = modf(restValues[(int)TimeUnit::tuSeconds]/60, &restValues[(int)TimeUnit::tuMinutes])*60;
  5917. values[(int)TimeUnit::tuMinutes] = modf(restValues[(int)TimeUnit::tuMinutes]/60, &restValues[(int)TimeUnit::tuHours])*60;
  5918. values[(int)TimeUnit::tuHours] = modf(restValues[(int)TimeUnit::tuHours]/24, &restValues[(int)TimeUnit::tuDays])*24;
  5919. // no need to set values[tuDays] because days are always a rest value (there is no higher unit so it consumes all remaining time)
  5920. QString result = mTimeFormat;
  5921. for (int i = mSmallestUnit; i <= mBiggestUnit; ++i)
  5922. {
  5923. TimeUnit iUnit = static_cast<TimeUnit>(i);
  5924. replaceUnit(result, iUnit, qRound(iUnit == mBiggestUnit ? restValues[iUnit] : values[iUnit]));
  5925. }
  5926. if (negative)
  5927. result.prepend(QLatin1Char('-'));
  5928. return result;
  5929. }
  5930. /*! \internal
  5931. Replaces all occurrences of the format pattern belonging to \a unit in \a text with the specified
  5932. \a value, using the field width as specified with \ref setFieldWidth for the \a unit.
  5933. */
  5934. void QCPAxisTickerTime::replaceUnit(QString &text, QCPAxisTickerTime::TimeUnit unit, int value) const
  5935. {
  5936. QString valueStr = QString::number(value);
  5937. while (valueStr.size() < mFieldWidth.value(unit))
  5938. valueStr.prepend(QLatin1Char('0'));
  5939. text.replace(mFormatPattern.value(unit), valueStr);
  5940. }
  5941. /* end of 'src/axis/axistickertime.cpp' */
  5942. /* including file 'src/axis/axistickerfixed.cpp' */
  5943. /* modified 2021-03-29T02:30:44, size 5575 */
  5944. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5945. //////////////////// QCPAxisTickerFixed
  5946. ////////////////////////////////////////////////////////////////////////////////////////////////////
  5947. /*! \class QCPAxisTickerFixed
  5948. \brief Specialized axis ticker with a fixed tick step
  5949. \image html axisticker-fixed.png
  5950. This QCPAxisTicker subclass generates ticks with a fixed tick step set with \ref setTickStep. It
  5951. is also possible to allow integer multiples and integer powers of the specified tick step with
  5952. \ref setScaleStrategy.
  5953. A typical application of this ticker is to make an axis only display integers, by setting the
  5954. tick step of the ticker to 1.0 and the scale strategy to \ref ssMultiples.
  5955. Another case is when a certain number has a special meaning and axis ticks should only appear at
  5956. multiples of that value. In this case you might also want to consider \ref QCPAxisTickerPi
  5957. because despite the name it is not limited to only pi symbols/values.
  5958. The ticker can be created and assigned to an axis like this:
  5959. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerfixed-creation
  5960. */
  5961. /*!
  5962. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  5963. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  5964. */
  5965. QCPAxisTickerFixed::QCPAxisTickerFixed() :
  5966. mTickStep(1.0),
  5967. mScaleStrategy(ScaleStrategy::ssNone)
  5968. {
  5969. }
  5970. /*!
  5971. Sets the fixed tick interval to \a step.
  5972. The axis ticker will only use this tick step when generating axis ticks. This might cause a very
  5973. high tick density and overlapping labels if the axis range is zoomed out. Using \ref
  5974. setScaleStrategy it is possible to relax the fixed step and also allow multiples or powers of \a
  5975. step. This will enable the ticker to reduce the number of ticks to a reasonable amount (see \ref
  5976. setTickCount).
  5977. */
  5978. void QCPAxisTickerFixed::setTickStep(double step)
  5979. {
  5980. if (step > 0)
  5981. mTickStep = step;
  5982. else
  5983. qDebug() << Q_FUNC_INFO << "tick step must be greater than zero:" << step;
  5984. }
  5985. /*!
  5986. Sets whether the specified tick step (\ref setTickStep) is absolutely fixed or whether
  5987. modifications may be applied to it before calculating the finally used tick step, such as
  5988. permitting multiples or powers. See \ref ScaleStrategy for details.
  5989. The default strategy is \ref ssNone, which means the tick step is absolutely fixed.
  5990. */
  5991. void QCPAxisTickerFixed::setScaleStrategy(QCPAxisTickerFixed::ScaleStrategy strategy)
  5992. {
  5993. mScaleStrategy = strategy;
  5994. }
  5995. /*! \internal
  5996. Determines the actually used tick step from the specified tick step and scale strategy (\ref
  5997. setTickStep, \ref setScaleStrategy).
  5998. This method either returns the specified tick step exactly, or, if the scale strategy is not \ref
  5999. ssNone, a modification of it to allow varying the number of ticks in the current axis range.
  6000. \seebaseclassmethod
  6001. */
  6002. double QCPAxisTickerFixed::getTickStep(const QCPRange &range)
  6003. {
  6004. switch (mScaleStrategy)
  6005. {
  6006. case ScaleStrategy::ssNone:
  6007. {
  6008. return mTickStep;
  6009. }
  6010. case ScaleStrategy::ssMultiples:
  6011. {
  6012. double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  6013. if (exactStep < mTickStep)
  6014. return mTickStep;
  6015. else
  6016. return qint64(cleanMantissa(exactStep/mTickStep)+0.5)*mTickStep;
  6017. }
  6018. case ScaleStrategy::ssPowers:
  6019. {
  6020. double exactStep = range.size()/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  6021. return qPow(mTickStep, int(qLn(exactStep)/qLn(mTickStep)+0.5));
  6022. }
  6023. }
  6024. return mTickStep;
  6025. }
  6026. /* end of 'src/axis/axistickerfixed.cpp' */
  6027. /* including file 'src/axis/axistickertext.cpp' */
  6028. /* modified 2021-03-29T02:30:44, size 8742 */
  6029. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6030. //////////////////// QCPAxisTickerText
  6031. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6032. /*! \class QCPAxisTickerText
  6033. \brief Specialized axis ticker which allows arbitrary labels at specified coordinates
  6034. \image html axisticker-text.png
  6035. This QCPAxisTicker subclass generates ticks which can be directly specified by the user as
  6036. coordinates and associated strings. They can be passed as a whole with \ref setTicks or one at a
  6037. time with \ref addTick. Alternatively you can directly access the internal storage via \ref ticks
  6038. and modify the tick/label data there.
  6039. This is useful for cases where the axis represents categories rather than numerical values.
  6040. If you are updating the ticks of this ticker regularly and in a dynamic fasion (e.g. dependent on
  6041. the axis range), it is a sign that you should probably create an own ticker by subclassing
  6042. QCPAxisTicker, instead of using this one.
  6043. The ticker can be created and assigned to an axis like this:
  6044. \snippet documentation/doc-image-generator/mainwindow.cpp axistickertext-creation
  6045. */
  6046. /* start of documentation of inline functions */
  6047. /*! \fn QMap<double, QString> &QCPAxisTickerText::ticks()
  6048. Returns a non-const reference to the internal map which stores the tick coordinates and their
  6049. labels.
  6050. You can access the map directly in order to add, remove or manipulate ticks, as an alternative to
  6051. using the methods provided by QCPAxisTickerText, such as \ref setTicks and \ref addTick.
  6052. */
  6053. /* end of documentation of inline functions */
  6054. /*!
  6055. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  6056. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  6057. */
  6058. QCPAxisTickerText::QCPAxisTickerText() :
  6059. mSubTickCount(0)
  6060. {
  6061. }
  6062. /*! \overload
  6063. Sets the ticks that shall appear on the axis. The map key of \a ticks corresponds to the axis
  6064. coordinate, and the map value is the string that will appear as tick label.
  6065. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6066. getter.
  6067. \see addTicks, addTick, clear
  6068. */
  6069. void QCPAxisTickerText::setTicks(const QMap<double, QString> &ticks)
  6070. {
  6071. mTicks = ticks;
  6072. }
  6073. /*! \overload
  6074. Sets the ticks that shall appear on the axis. The entries of \a positions correspond to the axis
  6075. coordinates, and the entries of \a labels are the respective strings that will appear as tick
  6076. labels.
  6077. \see addTicks, addTick, clear
  6078. */
  6079. void QCPAxisTickerText::setTicks(const QVector<double> &positions, const QVector<QString> &labels)
  6080. {
  6081. clear();
  6082. addTicks(positions, labels);
  6083. }
  6084. /*!
  6085. Sets the number of sub ticks that shall appear between ticks. For QCPAxisTickerText, there is no
  6086. automatic sub tick count calculation. So if sub ticks are needed, they must be configured with this
  6087. method.
  6088. */
  6089. void QCPAxisTickerText::setSubTickCount(int subTicks)
  6090. {
  6091. if (subTicks >= 0)
  6092. mSubTickCount = subTicks;
  6093. else
  6094. qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
  6095. }
  6096. /*!
  6097. Clears all ticks.
  6098. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6099. getter.
  6100. \see setTicks, addTicks, addTick
  6101. */
  6102. void QCPAxisTickerText::clear()
  6103. {
  6104. mTicks.clear();
  6105. }
  6106. /*!
  6107. Adds a single tick to the axis at the given axis coordinate \a position, with the provided tick \a
  6108. label.
  6109. \see addTicks, setTicks, clear
  6110. */
  6111. void QCPAxisTickerText::addTick(double position, const QString &label)
  6112. {
  6113. mTicks.insert(position, label);
  6114. }
  6115. /*! \overload
  6116. Adds the provided \a ticks to the ones already existing. The map key of \a ticks corresponds to
  6117. the axis coordinate, and the map value is the string that will appear as tick label.
  6118. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6119. getter.
  6120. \see addTick, setTicks, clear
  6121. */
  6122. void QCPAxisTickerText::addTicks(const QMap<double, QString> &ticks)
  6123. {
  6124. #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
  6125. mTicks.unite(ticks);
  6126. #else
  6127. mTicks.insert(ticks);
  6128. #endif
  6129. }
  6130. /*! \overload
  6131. Adds the provided ticks to the ones already existing. The entries of \a positions correspond to
  6132. the axis coordinates, and the entries of \a labels are the respective strings that will appear as
  6133. tick labels.
  6134. An alternative to manipulate ticks is to directly access the internal storage with the \ref ticks
  6135. getter.
  6136. \see addTick, setTicks, clear
  6137. */
  6138. void QCPAxisTickerText::addTicks(const QVector<double> &positions, const QVector<QString> &labels)
  6139. {
  6140. if (positions.size() != labels.size())
  6141. qDebug() << Q_FUNC_INFO << "passed unequal length vectors for positions and labels:" << positions.size() << labels.size();
  6142. int n = qMin(positions.size(), labels.size());
  6143. for (int i=0; i<n; ++i)
  6144. mTicks.insert(positions.at(i), labels.at(i));
  6145. }
  6146. /*!
  6147. Since the tick coordinates are provided externally, this method implementation does nothing.
  6148. \seebaseclassmethod
  6149. */
  6150. double QCPAxisTickerText::getTickStep(const QCPRange &range)
  6151. {
  6152. // text axis ticker has manual tick positions, so doesn't need this method
  6153. Q_UNUSED(range)
  6154. return 1.0;
  6155. }
  6156. /*!
  6157. Returns the sub tick count that was configured with \ref setSubTickCount.
  6158. \seebaseclassmethod
  6159. */
  6160. int QCPAxisTickerText::getSubTickCount(double tickStep)
  6161. {
  6162. Q_UNUSED(tickStep)
  6163. return mSubTickCount;
  6164. }
  6165. /*!
  6166. Returns the tick label which corresponds to the key \a tick in the internal tick storage. Since
  6167. the labels are provided externally, \a locale, \a formatChar, and \a precision are ignored.
  6168. \seebaseclassmethod
  6169. */
  6170. QString QCPAxisTickerText::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  6171. {
  6172. Q_UNUSED(locale)
  6173. Q_UNUSED(formatChar)
  6174. Q_UNUSED(precision)
  6175. return mTicks.value(tick);
  6176. }
  6177. /*!
  6178. Returns the externally provided tick coordinates which are in the specified \a range. If
  6179. available, one tick above and below the range is provided in addition, to allow possible sub tick
  6180. calculation. The parameter \a tickStep is ignored.
  6181. \seebaseclassmethod
  6182. */
  6183. QVector<double> QCPAxisTickerText::createTickVector(double tickStep, const QCPRange &range)
  6184. {
  6185. Q_UNUSED(tickStep)
  6186. QVector<double> result;
  6187. if (mTicks.isEmpty())
  6188. return result;
  6189. QMap<double, QString>::const_iterator start = mTicks.lowerBound(range.lower);
  6190. QMap<double, QString>::const_iterator end = mTicks.upperBound(range.upper);
  6191. // this method should try to give one tick outside of range so proper subticks can be generated:
  6192. if (start != mTicks.constBegin()) --start;
  6193. if (end != mTicks.constEnd()) ++end;
  6194. for (QMap<double, QString>::const_iterator it = start; it != end; ++it)
  6195. result.append(it.key());
  6196. return result;
  6197. }
  6198. /* end of 'src/axis/axistickertext.cpp' */
  6199. /* including file 'src/axis/axistickerpi.cpp' */
  6200. /* modified 2021-03-29T02:30:44, size 11177 */
  6201. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6202. //////////////////// QCPAxisTickerPi
  6203. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6204. /*! \class QCPAxisTickerPi
  6205. \brief Specialized axis ticker to display ticks in units of an arbitrary constant, for example pi
  6206. \image html axisticker-pi.png
  6207. This QCPAxisTicker subclass generates ticks that are expressed with respect to a given symbolic
  6208. constant with a numerical value specified with \ref setPiValue and an appearance in the tick
  6209. labels specified with \ref setPiSymbol.
  6210. Ticks may be generated at fractions of the symbolic constant. How these fractions appear in the
  6211. tick label can be configured with \ref setFractionStyle.
  6212. The ticker can be created and assigned to an axis like this:
  6213. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerpi-creation
  6214. */
  6215. /*!
  6216. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  6217. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  6218. */
  6219. QCPAxisTickerPi::QCPAxisTickerPi() :
  6220. mPiSymbol(QLatin1String(" ")+QChar(0x03C0)),
  6221. mPiValue(M_PI),
  6222. mPeriodicity(0),
  6223. mFractionStyle(FractionStyle::fsUnicodeFractions),
  6224. mPiTickStep(0)
  6225. {
  6226. setTickCount(4);
  6227. }
  6228. /*!
  6229. Sets how the symbol part (which is always a suffix to the number) shall appear in the axis tick
  6230. label.
  6231. If a space shall appear between the number and the symbol, make sure the space is contained in \a
  6232. symbol.
  6233. */
  6234. void QCPAxisTickerPi::setPiSymbol(QString symbol)
  6235. {
  6236. mPiSymbol = symbol;
  6237. }
  6238. /*!
  6239. Sets the numerical value that the symbolic constant has.
  6240. This will be used to place the appropriate fractions of the symbol at the respective axis
  6241. coordinates.
  6242. */
  6243. void QCPAxisTickerPi::setPiValue(double pi)
  6244. {
  6245. mPiValue = pi;
  6246. }
  6247. /*!
  6248. Sets whether the axis labels shall appear periodicly and if so, at which multiplicity of the
  6249. symbolic constant.
  6250. To disable periodicity, set \a multiplesOfPi to zero.
  6251. For example, an axis that identifies 0 with 2pi would set \a multiplesOfPi to two.
  6252. */
  6253. void QCPAxisTickerPi::setPeriodicity(int multiplesOfPi)
  6254. {
  6255. mPeriodicity = qAbs(multiplesOfPi);
  6256. }
  6257. /*!
  6258. Sets how the numerical/fractional part preceding the symbolic constant is displayed in tick
  6259. labels. See \ref FractionStyle for the various options.
  6260. */
  6261. void QCPAxisTickerPi::setFractionStyle(QCPAxisTickerPi::FractionStyle style)
  6262. {
  6263. mFractionStyle = style;
  6264. }
  6265. /*! \internal
  6266. Returns the tick step, using the constant's value (\ref setPiValue) as base unit. In consequence
  6267. the numerical/fractional part preceding the symbolic constant is made to have a readable
  6268. mantissa.
  6269. \seebaseclassmethod
  6270. */
  6271. double QCPAxisTickerPi::getTickStep(const QCPRange &range)
  6272. {
  6273. mPiTickStep = range.size()/mPiValue/double(mTickCount+1e-10); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers
  6274. mPiTickStep = cleanMantissa(mPiTickStep);
  6275. return mPiTickStep*mPiValue;
  6276. }
  6277. /*! \internal
  6278. Returns the sub tick count, using the constant's value (\ref setPiValue) as base unit. In
  6279. consequence the sub ticks divide the numerical/fractional part preceding the symbolic constant
  6280. reasonably, and not the total tick coordinate.
  6281. \seebaseclassmethod
  6282. */
  6283. int QCPAxisTickerPi::getSubTickCount(double tickStep)
  6284. {
  6285. return QCPAxisTicker::getSubTickCount(tickStep/mPiValue);
  6286. }
  6287. /*! \internal
  6288. Returns the tick label as a fractional/numerical part and a symbolic string as suffix. The
  6289. formatting of the fraction is done according to the specified \ref setFractionStyle. The appended
  6290. symbol is specified with \ref setPiSymbol.
  6291. \seebaseclassmethod
  6292. */
  6293. QString QCPAxisTickerPi::getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision)
  6294. {
  6295. double tickInPis = tick/mPiValue;
  6296. if (mPeriodicity > 0)
  6297. tickInPis = fmod(tickInPis, mPeriodicity);
  6298. if (mFractionStyle != FractionStyle::fsFloatingPoint && mPiTickStep > 0.09 && mPiTickStep < 50)
  6299. {
  6300. // simply construct fraction from decimal like 1.234 -> 1234/1000 and then simplify fraction, smaller digits are irrelevant due to mPiTickStep conditional above
  6301. int denominator = 1000;
  6302. int numerator = qRound(tickInPis*denominator);
  6303. simplifyFraction(numerator, denominator);
  6304. if (qAbs(numerator) == 1 && denominator == 1)
  6305. return (numerator < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
  6306. else if (numerator == 0)
  6307. return QLatin1String("0");
  6308. else
  6309. return fractionToString(numerator, denominator) + mPiSymbol;
  6310. } else
  6311. {
  6312. if (qFuzzyIsNull(tickInPis))
  6313. return QLatin1String("0");
  6314. else if (qFuzzyCompare(qAbs(tickInPis), 1.0))
  6315. return (tickInPis < 0 ? QLatin1String("-") : QLatin1String("")) + mPiSymbol.trimmed();
  6316. else
  6317. return QCPAxisTicker::getTickLabel(tickInPis, locale, formatChar, precision) + mPiSymbol;
  6318. }
  6319. }
  6320. /*! \internal
  6321. Takes the fraction given by \a numerator and \a denominator and modifies the values to make sure
  6322. the fraction is in irreducible form, i.e. numerator and denominator don't share any common
  6323. factors which could be cancelled.
  6324. */
  6325. void QCPAxisTickerPi::simplifyFraction(int &numerator, int &denominator) const
  6326. {
  6327. if (numerator == 0 || denominator == 0)
  6328. return;
  6329. int num = numerator;
  6330. int denom = denominator;
  6331. while (denom != 0) // euclidean gcd algorithm
  6332. {
  6333. int oldDenom = denom;
  6334. denom = num % denom;
  6335. num = oldDenom;
  6336. }
  6337. // num is now gcd of numerator and denominator
  6338. numerator /= num;
  6339. denominator /= num;
  6340. }
  6341. /*! \internal
  6342. Takes the fraction given by \a numerator and \a denominator and returns a string representation.
  6343. The result depends on the configured fraction style (\ref setFractionStyle).
  6344. This method is used to format the numerical/fractional part when generating tick labels. It
  6345. simplifies the passed fraction to an irreducible form using \ref simplifyFraction and factors out
  6346. any integer parts of the fraction (e.g. "10/4" becomes "2 1/2").
  6347. */
  6348. QString QCPAxisTickerPi::fractionToString(int numerator, int denominator) const
  6349. {
  6350. if (denominator == 0)
  6351. {
  6352. qDebug() << Q_FUNC_INFO << "called with zero denominator";
  6353. return QString();
  6354. }
  6355. if (mFractionStyle == FractionStyle::fsFloatingPoint) // should never be the case when calling this function
  6356. {
  6357. qDebug() << Q_FUNC_INFO << "shouldn't be called with fraction style fsDecimal";
  6358. return QString::number(numerator/double(denominator)); // failsafe
  6359. }
  6360. int sign = numerator*denominator < 0 ? -1 : 1;
  6361. numerator = qAbs(numerator);
  6362. denominator = qAbs(denominator);
  6363. if (denominator == 1)
  6364. {
  6365. return QString::number(sign*numerator);
  6366. } else
  6367. {
  6368. int integerPart = numerator/denominator;
  6369. int remainder = numerator%denominator;
  6370. if (remainder == 0)
  6371. {
  6372. return QString::number(sign*integerPart);
  6373. } else
  6374. {
  6375. if (mFractionStyle == FractionStyle::fsAsciiFractions)
  6376. {
  6377. return QString(QLatin1String("%1%2%3/%4"))
  6378. .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
  6379. .arg(integerPart > 0 ? QString::number(integerPart)+QLatin1String(" ") : QString(QLatin1String("")))
  6380. .arg(remainder)
  6381. .arg(denominator);
  6382. } else if (mFractionStyle == FractionStyle::fsUnicodeFractions)
  6383. {
  6384. return QString(QLatin1String("%1%2%3"))
  6385. .arg(sign == -1 ? QLatin1String("-") : QLatin1String(""))
  6386. .arg(integerPart > 0 ? QString::number(integerPart) : QLatin1String(""))
  6387. .arg(unicodeFraction(remainder, denominator));
  6388. }
  6389. }
  6390. }
  6391. return QString();
  6392. }
  6393. /*! \internal
  6394. Returns the unicode string representation of the fraction given by \a numerator and \a
  6395. denominator. This is the representation used in \ref fractionToString when the fraction style
  6396. (\ref setFractionStyle) is \ref fsUnicodeFractions.
  6397. This method doesn't use the single-character common fractions but builds each fraction from a
  6398. superscript unicode number, the unicode fraction character, and a subscript unicode number.
  6399. */
  6400. QString QCPAxisTickerPi::unicodeFraction(int numerator, int denominator) const
  6401. {
  6402. return unicodeSuperscript(numerator)+QChar(0x2044)+unicodeSubscript(denominator);
  6403. }
  6404. /*! \internal
  6405. Returns the unicode string representing \a number as superscript. This is used to build
  6406. unicode fractions in \ref unicodeFraction.
  6407. */
  6408. QString QCPAxisTickerPi::unicodeSuperscript(int number) const
  6409. {
  6410. if (number == 0)
  6411. return QString(QChar(0x2070));
  6412. QString result;
  6413. while (number > 0)
  6414. {
  6415. const int digit = number%10;
  6416. switch (digit)
  6417. {
  6418. case 1: { result.prepend(QChar(0x00B9)); break; }
  6419. case 2: { result.prepend(QChar(0x00B2)); break; }
  6420. case 3: { result.prepend(QChar(0x00B3)); break; }
  6421. default: { result.prepend(QChar(0x2070+digit)); break; }
  6422. }
  6423. number /= 10;
  6424. }
  6425. return result;
  6426. }
  6427. /*! \internal
  6428. Returns the unicode string representing \a number as subscript. This is used to build unicode
  6429. fractions in \ref unicodeFraction.
  6430. */
  6431. QString QCPAxisTickerPi::unicodeSubscript(int number) const
  6432. {
  6433. if (number == 0)
  6434. return QString(QChar(0x2080));
  6435. QString result;
  6436. while (number > 0)
  6437. {
  6438. result.prepend(QChar(0x2080+number%10));
  6439. number /= 10;
  6440. }
  6441. return result;
  6442. }
  6443. /* end of 'src/axis/axistickerpi.cpp' */
  6444. /* including file 'src/axis/axistickerlog.cpp' */
  6445. /* modified 2021-03-29T02:30:44, size 7890 */
  6446. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6447. //////////////////// QCPAxisTickerLog
  6448. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6449. /*! \class QCPAxisTickerLog
  6450. \brief Specialized axis ticker suited for logarithmic axes
  6451. \image html axisticker-log.png
  6452. This QCPAxisTicker subclass generates ticks with unequal tick intervals suited for logarithmic
  6453. axis scales. The ticks are placed at powers of the specified log base (\ref setLogBase).
  6454. Especially in the case of a log base equal to 10 (the default), it might be desirable to have
  6455. tick labels in the form of powers of ten without mantissa display. To achieve this, set the
  6456. number precision (\ref QCPAxis::setNumberPrecision) to zero and the number format (\ref
  6457. QCPAxis::setNumberFormat) to scientific (exponential) display with beautifully typeset decimal
  6458. powers, so a format string of <tt>"eb"</tt>. This will result in the following axis tick labels:
  6459. \image html axisticker-log-powers.png
  6460. The ticker can be created and assigned to an axis like this:
  6461. \snippet documentation/doc-image-generator/mainwindow.cpp axistickerlog-creation
  6462. Note that the nature of logarithmic ticks imply that there exists a smallest possible tick step,
  6463. corresponding to one multiplication by the log base. If the user zooms in further than that, no
  6464. new ticks would appear, leading to very sparse or even no axis ticks on the axis. To prevent this
  6465. situation, this ticker falls back to regular tick generation if the axis range would be covered
  6466. by too few logarithmically placed ticks.
  6467. */
  6468. /*!
  6469. Constructs the ticker and sets reasonable default values. Axis tickers are commonly created
  6470. managed by a QSharedPointer, which then can be passed to QCPAxis::setTicker.
  6471. */
  6472. QCPAxisTickerLog::QCPAxisTickerLog() :
  6473. mLogBase(10.0),
  6474. mSubTickCount(8), // generates 10 intervals
  6475. mLogBaseLnInv(1.0/qLn(mLogBase))
  6476. {
  6477. }
  6478. /*!
  6479. Sets the logarithm base used for tick coordinate generation. The ticks will be placed at integer
  6480. powers of \a base.
  6481. */
  6482. void QCPAxisTickerLog::setLogBase(double base)
  6483. {
  6484. if (base > 0)
  6485. {
  6486. mLogBase = base;
  6487. mLogBaseLnInv = 1.0/qLn(mLogBase);
  6488. } else
  6489. qDebug() << Q_FUNC_INFO << "log base has to be greater than zero:" << base;
  6490. }
  6491. /*!
  6492. Sets the number of sub ticks in a tick interval. Within each interval, the sub ticks are spaced
  6493. linearly to provide a better visual guide, so the sub tick density increases toward the higher
  6494. tick.
  6495. Note that \a subTicks is the number of sub ticks (not sub intervals) in one tick interval. So in
  6496. the case of logarithm base 10 an intuitive sub tick spacing would be achieved with eight sub
  6497. ticks (the default). This means e.g. between the ticks 10 and 100 there will be eight ticks,
  6498. namely at 20, 30, 40, 50, 60, 70, 80 and 90.
  6499. */
  6500. void QCPAxisTickerLog::setSubTickCount(int subTicks)
  6501. {
  6502. if (subTicks >= 0)
  6503. mSubTickCount = subTicks;
  6504. else
  6505. qDebug() << Q_FUNC_INFO << "sub tick count can't be negative:" << subTicks;
  6506. }
  6507. /*! \internal
  6508. Returns the sub tick count specified in \ref setSubTickCount. For QCPAxisTickerLog, there is no
  6509. automatic sub tick count calculation necessary.
  6510. \seebaseclassmethod
  6511. */
  6512. int QCPAxisTickerLog::getSubTickCount(double tickStep)
  6513. {
  6514. Q_UNUSED(tickStep)
  6515. return mSubTickCount;
  6516. }
  6517. /*! \internal
  6518. Creates ticks with a spacing given by the logarithm base and an increasing integer power in the
  6519. provided \a range. The step in which the power increases tick by tick is chosen in order to keep
  6520. the total number of ticks as close as possible to the tick count (\ref setTickCount).
  6521. The parameter \a tickStep is ignored for the normal logarithmic ticker generation. Only when
  6522. zoomed in very far such that not enough logarithmically placed ticks would be visible, this
  6523. function falls back to the regular QCPAxisTicker::createTickVector, which then uses \a tickStep.
  6524. \seebaseclassmethod
  6525. */
  6526. QVector<double> QCPAxisTickerLog::createTickVector(double tickStep, const QCPRange &range)
  6527. {
  6528. QVector<double> result;
  6529. if (range.lower > 0 && range.upper > 0) // positive range
  6530. {
  6531. const double baseTickCount = qLn(range.upper/range.lower)*mLogBaseLnInv;
  6532. if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation
  6533. return QCPAxisTicker::createTickVector(tickStep, range);
  6534. const double exactPowerStep = baseTickCount/double(mTickCount+1e-10);
  6535. const double newLogBase = qPow(mLogBase, qMax(int(cleanMantissa(exactPowerStep)), 1));
  6536. double currentTick = qPow(newLogBase, qFloor(qLn(range.lower)/qLn(newLogBase)));
  6537. result.append(currentTick);
  6538. while (currentTick < range.upper && currentTick > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  6539. {
  6540. currentTick *= newLogBase;
  6541. result.append(currentTick);
  6542. }
  6543. } else if (range.lower < 0 && range.upper < 0) // negative range
  6544. {
  6545. const double baseTickCount = qLn(range.lower/range.upper)*mLogBaseLnInv;
  6546. if (baseTickCount < 1.6) // if too few log ticks would be visible in axis range, fall back to regular tick vector generation
  6547. return QCPAxisTicker::createTickVector(tickStep, range);
  6548. const double exactPowerStep = baseTickCount/double(mTickCount+1e-10);
  6549. const double newLogBase = qPow(mLogBase, qMax(int(cleanMantissa(exactPowerStep)), 1));
  6550. double currentTick = -qPow(newLogBase, qCeil(qLn(-range.lower)/qLn(newLogBase)));
  6551. result.append(currentTick);
  6552. while (currentTick < range.upper && currentTick < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case
  6553. {
  6554. currentTick /= newLogBase;
  6555. result.append(currentTick);
  6556. }
  6557. } else // invalid range for logarithmic scale, because lower and upper have different sign
  6558. {
  6559. qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << range.lower << ".." << range.upper;
  6560. }
  6561. return result;
  6562. }
  6563. /* end of 'src/axis/axistickerlog.cpp' */
  6564. /* including file 'src/axis/axis.cpp' */
  6565. /* modified 2021-03-29T02:30:44, size 99883 */
  6566. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6567. //////////////////// QCPGrid
  6568. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6569. /*! \class QCPGrid
  6570. \brief Responsible for drawing the grid of a QCPAxis.
  6571. This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the
  6572. grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref
  6573. QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself.
  6574. The axis and grid drawing was split into two classes to allow them to be placed on different
  6575. layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid
  6576. in the background and the axes in the foreground, and any plottables/items in between. This
  6577. described situation is the default setup, see the QCPLayer documentation.
  6578. */
  6579. /*!
  6580. Creates a QCPGrid instance and sets default values.
  6581. You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid.
  6582. */
  6583. QCPGrid::QCPGrid(QCPAxis *parentAxis) :
  6584. QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
  6585. mSubGridVisible{},
  6586. mAntialiasedSubGrid{},
  6587. mAntialiasedZeroLine{},
  6588. mParentAxis(parentAxis)
  6589. {
  6590. // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called
  6591. setParent(parentAxis);
  6592. setPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  6593. setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  6594. setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
  6595. setSubGridVisible(false);
  6596. setAntialiased(false);
  6597. setAntialiasedSubGrid(false);
  6598. setAntialiasedZeroLine(false);
  6599. }
  6600. /*!
  6601. Sets whether grid lines at sub tick marks are drawn.
  6602. \see setSubGridPen
  6603. */
  6604. void QCPGrid::setSubGridVisible(bool visible)
  6605. {
  6606. mSubGridVisible = visible;
  6607. }
  6608. /*!
  6609. Sets whether sub grid lines are drawn antialiased.
  6610. */
  6611. void QCPGrid::setAntialiasedSubGrid(bool enabled)
  6612. {
  6613. mAntialiasedSubGrid = enabled;
  6614. }
  6615. /*!
  6616. Sets whether zero lines are drawn antialiased.
  6617. */
  6618. void QCPGrid::setAntialiasedZeroLine(bool enabled)
  6619. {
  6620. mAntialiasedZeroLine = enabled;
  6621. }
  6622. /*!
  6623. Sets the pen with which (major) grid lines are drawn.
  6624. */
  6625. void QCPGrid::setPen(const QPen &pen)
  6626. {
  6627. mPen = pen;
  6628. }
  6629. /*!
  6630. Sets the pen with which sub grid lines are drawn.
  6631. */
  6632. void QCPGrid::setSubGridPen(const QPen &pen)
  6633. {
  6634. mSubGridPen = pen;
  6635. }
  6636. /*!
  6637. Sets the pen with which zero lines are drawn.
  6638. Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid
  6639. lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen.
  6640. */
  6641. void QCPGrid::setZeroLinePen(const QPen &pen)
  6642. {
  6643. mZeroLinePen = pen;
  6644. }
  6645. /*! \internal
  6646. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  6647. before drawing the major grid lines.
  6648. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  6649. This function takes into account the local setting of the antialiasing flag as well as the
  6650. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  6651. QCustomPlot::setNotAntialiasedElements.
  6652. \see setAntialiased
  6653. */
  6654. void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
  6655. {
  6656. applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
  6657. }
  6658. /*! \internal
  6659. Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
  6660. over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
  6661. */
  6662. void QCPGrid::draw(QCPPainter *painter)
  6663. {
  6664. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6665. if (mParentAxis->subTicks() && mSubGridVisible)
  6666. drawSubGridLines(painter);
  6667. drawGridLines(painter);
  6668. }
  6669. /*! \internal
  6670. Draws the main grid lines and possibly a zero line with the specified painter.
  6671. This is a helper function called by \ref draw.
  6672. */
  6673. void QCPGrid::drawGridLines(QCPPainter *painter) const
  6674. {
  6675. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6676. const int tickCount = mParentAxis->mTickVector.size();
  6677. double t; // helper variable, result of coordinate-to-pixel transforms
  6678. if (mParentAxis->orientation() == Qt::Horizontal)
  6679. {
  6680. // draw zeroline:
  6681. int zeroLineIndex = -1;
  6682. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
  6683. {
  6684. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  6685. painter->setPen(mZeroLinePen);
  6686. double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero
  6687. for (int i=0; i<tickCount; ++i)
  6688. {
  6689. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
  6690. {
  6691. zeroLineIndex = i;
  6692. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  6693. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6694. break;
  6695. }
  6696. }
  6697. }
  6698. // draw grid lines:
  6699. applyDefaultAntialiasingHint(painter);
  6700. painter->setPen(mPen);
  6701. for (int i=0; i<tickCount; ++i)
  6702. {
  6703. if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
  6704. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x
  6705. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6706. }
  6707. } else
  6708. {
  6709. // draw zeroline:
  6710. int zeroLineIndex = -1;
  6711. if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0)
  6712. {
  6713. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  6714. painter->setPen(mZeroLinePen);
  6715. double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero
  6716. for (int i=0; i<tickCount; ++i)
  6717. {
  6718. if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon)
  6719. {
  6720. zeroLineIndex = i;
  6721. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  6722. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6723. break;
  6724. }
  6725. }
  6726. }
  6727. // draw grid lines:
  6728. applyDefaultAntialiasingHint(painter);
  6729. painter->setPen(mPen);
  6730. for (int i=0; i<tickCount; ++i)
  6731. {
  6732. if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline
  6733. t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y
  6734. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6735. }
  6736. }
  6737. }
  6738. /*! \internal
  6739. Draws the sub grid lines with the specified painter.
  6740. This is a helper function called by \ref draw.
  6741. */
  6742. void QCPGrid::drawSubGridLines(QCPPainter *painter) const
  6743. {
  6744. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  6745. applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid);
  6746. double t; // helper variable, result of coordinate-to-pixel transforms
  6747. painter->setPen(mSubGridPen);
  6748. if (mParentAxis->orientation() == Qt::Horizontal)
  6749. {
  6750. foreach (double tickCoord, mParentAxis->mSubTickVector)
  6751. {
  6752. t = mParentAxis->coordToPixel(tickCoord); // x
  6753. painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top()));
  6754. }
  6755. } else
  6756. {
  6757. foreach (double tickCoord, mParentAxis->mSubTickVector)
  6758. {
  6759. t = mParentAxis->coordToPixel(tickCoord); // y
  6760. painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t));
  6761. }
  6762. }
  6763. }
  6764. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6765. //////////////////// QCPAxis
  6766. ////////////////////////////////////////////////////////////////////////////////////////////////////
  6767. /*! \class QCPAxis
  6768. \brief Manages a single axis inside a QCustomPlot.
  6769. Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via
  6770. QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and
  6771. QCustomPlot::yAxis2 (right).
  6772. Axes are always part of an axis rect, see QCPAxisRect.
  6773. \image html AxisNamesOverview.png
  6774. <center>Naming convention of axis parts</center>
  6775. \n
  6776. \image html AxisRectSpacingOverview.png
  6777. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line
  6778. on the left represents the QCustomPlot widget border.</center>
  6779. Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
  6780. tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
  6781. the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
  6782. documentation of QCPAxisTicker.
  6783. */
  6784. /* start of documentation of inline functions */
  6785. /*! \fn Qt::Orientation QCPAxis::orientation() const
  6786. Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced
  6787. from the axis type (left, top, right or bottom).
  6788. \see orientation(AxisType type), pixelOrientation
  6789. */
  6790. /*! \fn QCPGrid *QCPAxis::grid() const
  6791. Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the
  6792. grid is displayed.
  6793. */
  6794. /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type)
  6795. Returns the orientation of the specified axis type
  6796. \see orientation(), pixelOrientation
  6797. */
  6798. /*! \fn int QCPAxis::pixelOrientation() const
  6799. Returns which direction points towards higher coordinate values/keys, in pixel space.
  6800. This method returns either 1 or -1. If it returns 1, then going in the positive direction along
  6801. the orientation of the axis in pixels corresponds to going from lower to higher axis coordinates.
  6802. On the other hand, if this method returns -1, going to smaller pixel values corresponds to going
  6803. from lower to higher axis coordinates.
  6804. For example, this is useful to easily shift axis coordinates by a certain amount given in pixels,
  6805. without having to care about reversed or vertically aligned axes:
  6806. \code
  6807. double newKey = keyAxis->pixelToCoord(keyAxis->coordToPixel(oldKey)+10*keyAxis->pixelOrientation());
  6808. \endcode
  6809. \a newKey will then contain a key that is ten pixels towards higher keys, starting from \a oldKey.
  6810. */
  6811. /*! \fn QSharedPointer<QCPAxisTicker> QCPAxis::ticker() const
  6812. Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
  6813. responsible for generating the tick positions and tick labels of this axis. You can access the
  6814. \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
  6815. (\ref QCPAxisTicker::setTickCount).
  6816. You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
  6817. the documentation there. A new axis ticker can be set with \ref setTicker.
  6818. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  6819. ticker simply by passing the same shared pointer to multiple axes.
  6820. \see setTicker
  6821. */
  6822. /* end of documentation of inline functions */
  6823. /* start of documentation of signals */
  6824. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange)
  6825. This signal is emitted when the range of this axis has changed. You can connect it to the \ref
  6826. setRange slot of another axis to communicate the new range to the other axis, in order for it to
  6827. be synchronized.
  6828. You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
  6829. This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
  6830. range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
  6831. slot would limit the x axis to ranges between 0 and 10:
  6832. \code
  6833. customPlot->xAxis->setRange(newRange.bounded(0, 10))
  6834. \endcode
  6835. */
  6836. /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
  6837. \overload
  6838. Additionally to the new range, this signal also provides the previous range held by the axis as
  6839. \a oldRange.
  6840. */
  6841. /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType);
  6842. This signal is emitted when the scale type changes, by calls to \ref setScaleType
  6843. */
  6844. /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection)
  6845. This signal is emitted when the selection state of this axis has changed, either by user interaction
  6846. or by a direct call to \ref setSelectedParts.
  6847. */
  6848. /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts);
  6849. This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
  6850. */
  6851. /* end of documentation of signals */
  6852. /*!
  6853. Constructs an Axis instance of Type \a type for the axis rect \a parent.
  6854. Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
  6855. them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
  6856. create them manually and then inject them also via \ref QCPAxisRect::addAxis.
  6857. */
  6858. QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) :
  6859. QCPLayerable(parent->parentPlot(), QString(), parent),
  6860. // axis base:
  6861. mAxisType(type),
  6862. mAxisRect(parent),
  6863. mPadding(5),
  6864. mOrientation(orientation(type)),
  6865. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  6866. mSelectedParts(spNone),
  6867. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6868. mSelectedBasePen(QPen(Qt::blue, 2)),
  6869. // axis label:
  6870. mLabel(),
  6871. mLabelFont(mParentPlot->font()),
  6872. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  6873. mLabelColor(Qt::black),
  6874. mSelectedLabelColor(Qt::blue),
  6875. // tick labels:
  6876. mTickLabels(true),
  6877. mTickLabelFont(mParentPlot->font()),
  6878. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  6879. mTickLabelColor(Qt::black),
  6880. mSelectedTickLabelColor(Qt::blue),
  6881. mNumberPrecision(6),
  6882. mNumberFormatChar('g'),
  6883. mNumberBeautifulPowers(true),
  6884. // ticks and subticks:
  6885. mTicks(true),
  6886. mSubTicks(true),
  6887. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6888. mSelectedTickPen(QPen(Qt::blue, 2)),
  6889. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  6890. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  6891. // scale and range:
  6892. mRange(0, 5),
  6893. mRangeReversed(false),
  6894. mScaleType(ScaleType::stLinear),
  6895. // internal members:
  6896. mGrid(new QCPGrid(this)),
  6897. mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())),
  6898. mTicker(new QCPAxisTicker),
  6899. mCachedMarginValid(false),
  6900. mCachedMargin(0),
  6901. mDragging(false)
  6902. {
  6903. setParent(parent);
  6904. mGrid->setVisible(false);
  6905. setAntialiased(false);
  6906. 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
  6907. if (type == AxisType::atTop)
  6908. {
  6909. setTickLabelPadding(3);
  6910. setLabelPadding(6);
  6911. } else if (type == AxisType::atRight)
  6912. {
  6913. setTickLabelPadding(7);
  6914. setLabelPadding(12);
  6915. } else if (type == AxisType::atBottom)
  6916. {
  6917. setTickLabelPadding(3);
  6918. setLabelPadding(3);
  6919. } else if (type == AxisType::atLeft)
  6920. {
  6921. setTickLabelPadding(5);
  6922. setLabelPadding(10);
  6923. }
  6924. }
  6925. QCPAxis::~QCPAxis()
  6926. {
  6927. delete mAxisPainter;
  6928. delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
  6929. }
  6930. /* No documentation as it is a property getter */
  6931. int QCPAxis::tickLabelPadding() const
  6932. {
  6933. return mAxisPainter->tickLabelPadding;
  6934. }
  6935. /* No documentation as it is a property getter */
  6936. double QCPAxis::tickLabelRotation() const
  6937. {
  6938. return mAxisPainter->tickLabelRotation;
  6939. }
  6940. /* No documentation as it is a property getter */
  6941. QCPAxis::LabelSide QCPAxis::tickLabelSide() const
  6942. {
  6943. return mAxisPainter->tickLabelSide;
  6944. }
  6945. /* No documentation as it is a property getter */
  6946. QString QCPAxis::numberFormat() const
  6947. {
  6948. QString result;
  6949. result.append(mNumberFormatChar);
  6950. if (mNumberBeautifulPowers)
  6951. {
  6952. result.append(QLatin1Char('b'));
  6953. if (mAxisPainter->numberMultiplyCross)
  6954. result.append(QLatin1Char('c'));
  6955. }
  6956. return result;
  6957. }
  6958. /* No documentation as it is a property getter */
  6959. int QCPAxis::tickLengthIn() const
  6960. {
  6961. return mAxisPainter->tickLengthIn;
  6962. }
  6963. /* No documentation as it is a property getter */
  6964. int QCPAxis::tickLengthOut() const
  6965. {
  6966. return mAxisPainter->tickLengthOut;
  6967. }
  6968. /* No documentation as it is a property getter */
  6969. int QCPAxis::subTickLengthIn() const
  6970. {
  6971. return mAxisPainter->subTickLengthIn;
  6972. }
  6973. /* No documentation as it is a property getter */
  6974. int QCPAxis::subTickLengthOut() const
  6975. {
  6976. return mAxisPainter->subTickLengthOut;
  6977. }
  6978. /* No documentation as it is a property getter */
  6979. int QCPAxis::labelPadding() const
  6980. {
  6981. return mAxisPainter->labelPadding;
  6982. }
  6983. /* No documentation as it is a property getter */
  6984. int QCPAxis::offset() const
  6985. {
  6986. return mAxisPainter->offset;
  6987. }
  6988. /* No documentation as it is a property getter */
  6989. QCPLineEnding QCPAxis::lowerEnding() const
  6990. {
  6991. return mAxisPainter->lowerEnding;
  6992. }
  6993. /* No documentation as it is a property getter */
  6994. QCPLineEnding QCPAxis::upperEnding() const
  6995. {
  6996. return mAxisPainter->upperEnding;
  6997. }
  6998. /*!
  6999. Sets whether the axis uses a linear scale or a logarithmic scale.
  7000. Note that this method controls the coordinate transformation. For logarithmic scales, you will
  7001. likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
  7002. the axis ticker to an instance of \ref QCPAxisTickerLog :
  7003. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation
  7004. See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
  7005. creation.
  7006. \ref setNumberPrecision
  7007. */
  7008. void QCPAxis::setScaleType(QCPAxis::ScaleType type)
  7009. {
  7010. if (mScaleType != type)
  7011. {
  7012. mScaleType = type;
  7013. if (mScaleType == ScaleType::stLogarithmic)
  7014. setRange(mRange.sanitizedForLogScale());
  7015. mCachedMarginValid = false;
  7016. emit scaleTypeChanged(mScaleType);
  7017. }
  7018. }
  7019. /*!
  7020. Sets the range of the axis.
  7021. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  7022. is always synchronized with the other axis range, when it changes.
  7023. To invert the direction of an axis, use \ref setRangeReversed.
  7024. */
  7025. void QCPAxis::setRange(const QCPRange &range)
  7026. {
  7027. if (range.lower == mRange.lower && range.upper == mRange.upper)
  7028. return;
  7029. if (!QCPRange::validRange(range)) return;
  7030. QCPRange oldRange = mRange;
  7031. if (mScaleType == ScaleType::stLogarithmic)
  7032. {
  7033. mRange = range.sanitizedForLogScale();
  7034. } else
  7035. {
  7036. mRange = range.sanitizedForLinScale();
  7037. }
  7038. emit rangeChanged(mRange);
  7039. emit rangeChanged(mRange, oldRange);
  7040. }
  7041. /*!
  7042. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  7043. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  7044. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  7045. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  7046. directly.
  7047. \see SelectablePart, setSelectedParts
  7048. */
  7049. void QCPAxis::setSelectableParts(const SelectableParts &selectable)
  7050. {
  7051. if (mSelectableParts != selectable)
  7052. {
  7053. mSelectableParts = selectable;
  7054. emit selectableChanged(mSelectableParts);
  7055. }
  7056. }
  7057. /*!
  7058. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  7059. is selected, it uses a different pen/font.
  7060. The entire selection mechanism for axes is handled automatically when \ref
  7061. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  7062. wish to change the selection state manually.
  7063. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  7064. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  7065. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  7066. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  7067. */
  7068. void QCPAxis::setSelectedParts(const SelectableParts &selected)
  7069. {
  7070. if (mSelectedParts != selected)
  7071. {
  7072. mSelectedParts = selected;
  7073. emit selectionChanged(mSelectedParts);
  7074. }
  7075. }
  7076. /*!
  7077. \overload
  7078. Sets the lower and upper bound of the axis range.
  7079. To invert the direction of an axis, use \ref setRangeReversed.
  7080. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  7081. */
  7082. void QCPAxis::setRange(double lower, double upper)
  7083. {
  7084. if (lower == mRange.lower && upper == mRange.upper)
  7085. return;
  7086. if (!QCPRange::validRange(lower, upper)) return;
  7087. QCPRange oldRange = mRange;
  7088. mRange.lower = lower;
  7089. mRange.upper = upper;
  7090. if (mScaleType == ScaleType::stLogarithmic)
  7091. {
  7092. mRange = mRange.sanitizedForLogScale();
  7093. } else
  7094. {
  7095. mRange = mRange.sanitizedForLinScale();
  7096. }
  7097. emit rangeChanged(mRange);
  7098. emit rangeChanged(mRange, oldRange);
  7099. }
  7100. /*!
  7101. \overload
  7102. Sets the range of the axis.
  7103. The \a position coordinate indicates together with the \a alignment parameter, where the new
  7104. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  7105. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  7106. or center of the range to be aligned with \a position. Any other values of \a alignment will
  7107. default to Qt::AlignCenter.
  7108. */
  7109. void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment)
  7110. {
  7111. if (alignment == Qt::AlignLeft)
  7112. setRange(position, position+size);
  7113. else if (alignment == Qt::AlignRight)
  7114. setRange(position-size, position);
  7115. else // alignment == Qt::AlignCenter
  7116. setRange(position-size/2.0, position+size/2.0);
  7117. }
  7118. /*!
  7119. Sets the lower bound of the axis range. The upper bound is not changed.
  7120. \see setRange
  7121. */
  7122. void QCPAxis::setRangeLower(double lower)
  7123. {
  7124. if (mRange.lower == lower)
  7125. return;
  7126. QCPRange oldRange = mRange;
  7127. mRange.lower = lower;
  7128. if (mScaleType == ScaleType::stLogarithmic)
  7129. {
  7130. mRange = mRange.sanitizedForLogScale();
  7131. } else
  7132. {
  7133. mRange = mRange.sanitizedForLinScale();
  7134. }
  7135. emit rangeChanged(mRange);
  7136. emit rangeChanged(mRange, oldRange);
  7137. }
  7138. /*!
  7139. Sets the upper bound of the axis range. The lower bound is not changed.
  7140. \see setRange
  7141. */
  7142. void QCPAxis::setRangeUpper(double upper)
  7143. {
  7144. if (mRange.upper == upper)
  7145. return;
  7146. QCPRange oldRange = mRange;
  7147. mRange.upper = upper;
  7148. if (mScaleType == ScaleType::stLogarithmic)
  7149. {
  7150. mRange = mRange.sanitizedForLogScale();
  7151. } else
  7152. {
  7153. mRange = mRange.sanitizedForLinScale();
  7154. }
  7155. emit rangeChanged(mRange);
  7156. emit rangeChanged(mRange, oldRange);
  7157. }
  7158. /*!
  7159. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  7160. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  7161. direction of increasing values is inverted.
  7162. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  7163. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  7164. upper part.
  7165. */
  7166. void QCPAxis::setRangeReversed(bool reversed)
  7167. {
  7168. mRangeReversed = reversed;
  7169. }
  7170. /*!
  7171. The axis ticker is responsible for generating the tick positions and tick labels. See the
  7172. documentation of QCPAxisTicker for details on how to work with axis tickers.
  7173. You can change the tick positioning/labeling behaviour of this axis by setting a different
  7174. QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
  7175. ticker, access it via \ref ticker.
  7176. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  7177. ticker simply by passing the same shared pointer to multiple axes.
  7178. \see ticker
  7179. */
  7180. void QCPAxis::setTicker(QSharedPointer<QCPAxisTicker> ticker)
  7181. {
  7182. if (ticker)
  7183. mTicker = ticker;
  7184. else
  7185. qDebug() << Q_FUNC_INFO << "can not set nullptr as axis ticker";
  7186. // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
  7187. }
  7188. /*!
  7189. Sets whether tick marks are displayed.
  7190. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  7191. that, see \ref setTickLabels.
  7192. \see setSubTicks
  7193. */
  7194. void QCPAxis::setTicks(bool show)
  7195. {
  7196. if (mTicks != show)
  7197. {
  7198. mTicks = show;
  7199. mCachedMarginValid = false;
  7200. }
  7201. }
  7202. /*!
  7203. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  7204. */
  7205. void QCPAxis::setTickLabels(bool show)
  7206. {
  7207. if (mTickLabels != show)
  7208. {
  7209. mTickLabels = show;
  7210. mCachedMarginValid = false;
  7211. if (!mTickLabels)
  7212. mTickVectorLabels.clear();
  7213. }
  7214. }
  7215. /*!
  7216. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  7217. \see setLabelPadding, setPadding
  7218. */
  7219. void QCPAxis::setTickLabelPadding(int padding)
  7220. {
  7221. if (mAxisPainter->tickLabelPadding != padding)
  7222. {
  7223. mAxisPainter->tickLabelPadding = padding;
  7224. mCachedMarginValid = false;
  7225. }
  7226. }
  7227. /*!
  7228. Sets the font of the tick labels.
  7229. \see setTickLabels, setTickLabelColor
  7230. */
  7231. void QCPAxis::setTickLabelFont(const QFont &font)
  7232. {
  7233. if (font != mTickLabelFont)
  7234. {
  7235. mTickLabelFont = font;
  7236. mCachedMarginValid = false;
  7237. }
  7238. }
  7239. /*!
  7240. Sets the color of the tick labels.
  7241. \see setTickLabels, setTickLabelFont
  7242. */
  7243. void QCPAxis::setTickLabelColor(const QColor &color)
  7244. {
  7245. mTickLabelColor = color;
  7246. }
  7247. /*!
  7248. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  7249. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  7250. from -90 to 90 degrees.
  7251. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  7252. other angles, the label is drawn with an offset such that it seems to point toward or away from
  7253. the tick mark.
  7254. */
  7255. void QCPAxis::setTickLabelRotation(double degrees)
  7256. {
  7257. if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation))
  7258. {
  7259. mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0);
  7260. mCachedMarginValid = false;
  7261. }
  7262. }
  7263. /*!
  7264. Sets whether the tick labels (numbers) shall appear inside or outside the axis rect.
  7265. The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels
  7266. to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels
  7267. appear on the inside are additionally clipped to the axis rect.
  7268. */
  7269. void QCPAxis::setTickLabelSide(LabelSide side)
  7270. {
  7271. mAxisPainter->tickLabelSide = side;
  7272. mCachedMarginValid = false;
  7273. }
  7274. /*!
  7275. Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
  7276. of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
  7277. that, see the "Argument Formats" section in the detailed description of the QString class.
  7278. \a formatCode is a string of one, two or three characters.
  7279. <b>The first character</b> is identical to
  7280. the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
  7281. format, 'g'/'G' scientific or fixed, whichever is shorter. For the 'e', 'E', and 'f' formats,
  7282. the precision set by \ref setNumberPrecision represents the number of digits after the decimal
  7283. point. For the 'g' and 'G' formats, the precision represents the maximum number of significant
  7284. digits, trailing zeroes are omitted.
  7285. <b>The second and third characters</b> are optional and specific to QCustomPlot:\n
  7286. If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
  7287. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
  7288. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  7289. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  7290. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  7291. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  7292. cross and 183 (0xB7) for the dot.
  7293. Examples for \a formatCode:
  7294. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  7295. normal scientific format is used
  7296. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  7297. beautifully typeset decimal powers and a dot as multiplication sign
  7298. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  7299. multiplication sign
  7300. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  7301. powers. Format code will be reduced to 'f'.
  7302. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  7303. code will not be changed.
  7304. */
  7305. void QCPAxis::setNumberFormat(const QString &formatCode)
  7306. {
  7307. if (formatCode.isEmpty())
  7308. {
  7309. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  7310. return;
  7311. }
  7312. mCachedMarginValid = false;
  7313. // interpret first char as number format char:
  7314. QString allowedFormatChars(QLatin1String("eEfgG"));
  7315. if (allowedFormatChars.contains(formatCode.at(0)))
  7316. {
  7317. mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
  7318. } else
  7319. {
  7320. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  7321. return;
  7322. }
  7323. if (formatCode.length() < 2)
  7324. {
  7325. mNumberBeautifulPowers = false;
  7326. mAxisPainter->numberMultiplyCross = false;
  7327. return;
  7328. }
  7329. // interpret second char as indicator for beautiful decimal powers:
  7330. if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
  7331. {
  7332. mNumberBeautifulPowers = true;
  7333. } else
  7334. {
  7335. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  7336. return;
  7337. }
  7338. if (formatCode.length() < 3)
  7339. {
  7340. mAxisPainter->numberMultiplyCross = false;
  7341. return;
  7342. }
  7343. // interpret third char as indicator for dot or cross multiplication symbol:
  7344. if (formatCode.at(2) == QLatin1Char('c'))
  7345. {
  7346. mAxisPainter->numberMultiplyCross = true;
  7347. } else if (formatCode.at(2) == QLatin1Char('d'))
  7348. {
  7349. mAxisPainter->numberMultiplyCross = false;
  7350. } else
  7351. {
  7352. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  7353. return;
  7354. }
  7355. }
  7356. /*!
  7357. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  7358. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  7359. \ref setNumberFormat
  7360. */
  7361. void QCPAxis::setNumberPrecision(int precision)
  7362. {
  7363. if (mNumberPrecision != precision)
  7364. {
  7365. mNumberPrecision = precision;
  7366. mCachedMarginValid = false;
  7367. }
  7368. }
  7369. /*!
  7370. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  7371. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  7372. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  7373. they won't collide with the ticks.
  7374. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  7375. */
  7376. void QCPAxis::setTickLength(int inside, int outside)
  7377. {
  7378. setTickLengthIn(inside);
  7379. setTickLengthOut(outside);
  7380. }
  7381. /*!
  7382. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  7383. inside the plot.
  7384. \see setTickLengthOut, setTickLength, setSubTickLength
  7385. */
  7386. void QCPAxis::setTickLengthIn(int inside)
  7387. {
  7388. if (mAxisPainter->tickLengthIn != inside)
  7389. {
  7390. mAxisPainter->tickLengthIn = inside;
  7391. }
  7392. }
  7393. /*!
  7394. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  7395. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  7396. increase their distance to the axis accordingly, so they won't collide with the ticks.
  7397. \see setTickLengthIn, setTickLength, setSubTickLength
  7398. */
  7399. void QCPAxis::setTickLengthOut(int outside)
  7400. {
  7401. if (mAxisPainter->tickLengthOut != outside)
  7402. {
  7403. mAxisPainter->tickLengthOut = outside;
  7404. mCachedMarginValid = false; // only outside tick length can change margin
  7405. }
  7406. }
  7407. /*!
  7408. Sets whether sub tick marks are displayed.
  7409. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
  7410. \see setTicks
  7411. */
  7412. void QCPAxis::setSubTicks(bool show)
  7413. {
  7414. if (mSubTicks != show)
  7415. {
  7416. mSubTicks = show;
  7417. mCachedMarginValid = false;
  7418. }
  7419. }
  7420. /*!
  7421. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  7422. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  7423. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  7424. so they won't collide with the ticks.
  7425. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  7426. */
  7427. void QCPAxis::setSubTickLength(int inside, int outside)
  7428. {
  7429. setSubTickLengthIn(inside);
  7430. setSubTickLengthOut(outside);
  7431. }
  7432. /*!
  7433. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  7434. the plot.
  7435. \see setSubTickLengthOut, setSubTickLength, setTickLength
  7436. */
  7437. void QCPAxis::setSubTickLengthIn(int inside)
  7438. {
  7439. if (mAxisPainter->subTickLengthIn != inside)
  7440. {
  7441. mAxisPainter->subTickLengthIn = inside;
  7442. }
  7443. }
  7444. /*!
  7445. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  7446. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  7447. distance to the axis accordingly, so they won't collide with the ticks.
  7448. \see setSubTickLengthIn, setSubTickLength, setTickLength
  7449. */
  7450. void QCPAxis::setSubTickLengthOut(int outside)
  7451. {
  7452. if (mAxisPainter->subTickLengthOut != outside)
  7453. {
  7454. mAxisPainter->subTickLengthOut = outside;
  7455. mCachedMarginValid = false; // only outside tick length can change margin
  7456. }
  7457. }
  7458. /*!
  7459. Sets the pen, the axis base line is drawn with.
  7460. \see setTickPen, setSubTickPen
  7461. */
  7462. void QCPAxis::setBasePen(const QPen &pen)
  7463. {
  7464. mBasePen = pen;
  7465. }
  7466. /*!
  7467. Sets the pen, tick marks will be drawn with.
  7468. \see setTickLength, setBasePen
  7469. */
  7470. void QCPAxis::setTickPen(const QPen &pen)
  7471. {
  7472. mTickPen = pen;
  7473. }
  7474. /*!
  7475. Sets the pen, subtick marks will be drawn with.
  7476. \see setSubTickCount, setSubTickLength, setBasePen
  7477. */
  7478. void QCPAxis::setSubTickPen(const QPen &pen)
  7479. {
  7480. mSubTickPen = pen;
  7481. }
  7482. /*!
  7483. Sets the font of the axis label.
  7484. \see setLabelColor
  7485. */
  7486. void QCPAxis::setLabelFont(const QFont &font)
  7487. {
  7488. if (mLabelFont != font)
  7489. {
  7490. mLabelFont = font;
  7491. mCachedMarginValid = false;
  7492. }
  7493. }
  7494. /*!
  7495. Sets the color of the axis label.
  7496. \see setLabelFont
  7497. */
  7498. void QCPAxis::setLabelColor(const QColor &color)
  7499. {
  7500. mLabelColor = color;
  7501. }
  7502. /*!
  7503. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  7504. its orientation. To disable axis labels, pass an empty string as \a str.
  7505. */
  7506. void QCPAxis::setLabel(const QString &str)
  7507. {
  7508. if (mLabel != str)
  7509. {
  7510. mLabel = str;
  7511. mCachedMarginValid = false;
  7512. }
  7513. }
  7514. /*!
  7515. Sets the distance between the tick labels and the axis label.
  7516. \see setTickLabelPadding, setPadding
  7517. */
  7518. void QCPAxis::setLabelPadding(int padding)
  7519. {
  7520. if (mAxisPainter->labelPadding != padding)
  7521. {
  7522. mAxisPainter->labelPadding = padding;
  7523. mCachedMarginValid = false;
  7524. }
  7525. }
  7526. /*!
  7527. Sets the padding of the axis.
  7528. When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space,
  7529. that is left blank.
  7530. The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled.
  7531. \see setLabelPadding, setTickLabelPadding
  7532. */
  7533. void QCPAxis::setPadding(int padding)
  7534. {
  7535. if (mPadding != padding)
  7536. {
  7537. mPadding = padding;
  7538. mCachedMarginValid = false;
  7539. }
  7540. }
  7541. /*!
  7542. Sets the offset the axis has to its axis rect side.
  7543. If an axis rect side has multiple axes and automatic margin calculation is enabled for that side,
  7544. only the offset of the inner most axis has meaning (even if it is set to be invisible). The
  7545. offset of the other, outer axes is controlled automatically, to place them at appropriate
  7546. positions.
  7547. */
  7548. void QCPAxis::setOffset(int offset)
  7549. {
  7550. mAxisPainter->offset = offset;
  7551. }
  7552. /*!
  7553. Sets the font that is used for tick labels when they are selected.
  7554. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7555. */
  7556. void QCPAxis::setSelectedTickLabelFont(const QFont &font)
  7557. {
  7558. if (font != mSelectedTickLabelFont)
  7559. {
  7560. mSelectedTickLabelFont = font;
  7561. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  7562. }
  7563. }
  7564. /*!
  7565. Sets the font that is used for the axis label when it is selected.
  7566. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7567. */
  7568. void QCPAxis::setSelectedLabelFont(const QFont &font)
  7569. {
  7570. mSelectedLabelFont = font;
  7571. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  7572. }
  7573. /*!
  7574. Sets the color that is used for tick labels when they are selected.
  7575. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7576. */
  7577. void QCPAxis::setSelectedTickLabelColor(const QColor &color)
  7578. {
  7579. if (color != mSelectedTickLabelColor)
  7580. {
  7581. mSelectedTickLabelColor = color;
  7582. }
  7583. }
  7584. /*!
  7585. Sets the color that is used for the axis label when it is selected.
  7586. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7587. */
  7588. void QCPAxis::setSelectedLabelColor(const QColor &color)
  7589. {
  7590. mSelectedLabelColor = color;
  7591. }
  7592. /*!
  7593. Sets the pen that is used to draw the axis base line when selected.
  7594. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7595. */
  7596. void QCPAxis::setSelectedBasePen(const QPen &pen)
  7597. {
  7598. mSelectedBasePen = pen;
  7599. }
  7600. /*!
  7601. Sets the pen that is used to draw the (major) ticks when selected.
  7602. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7603. */
  7604. void QCPAxis::setSelectedTickPen(const QPen &pen)
  7605. {
  7606. mSelectedTickPen = pen;
  7607. }
  7608. /*!
  7609. Sets the pen that is used to draw the subticks when selected.
  7610. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  7611. */
  7612. void QCPAxis::setSelectedSubTickPen(const QPen &pen)
  7613. {
  7614. mSelectedSubTickPen = pen;
  7615. }
  7616. /*!
  7617. Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available
  7618. styles.
  7619. For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending.
  7620. Note that this meaning does not change when the axis range is reversed with \ref
  7621. setRangeReversed.
  7622. \see setUpperEnding
  7623. */
  7624. void QCPAxis::setLowerEnding(const QCPLineEnding &ending)
  7625. {
  7626. mAxisPainter->lowerEnding = ending;
  7627. }
  7628. /*!
  7629. Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available
  7630. styles.
  7631. For horizontal axes, this method refers to the right ending, for vertical axes the top ending.
  7632. Note that this meaning does not change when the axis range is reversed with \ref
  7633. setRangeReversed.
  7634. \see setLowerEnding
  7635. */
  7636. void QCPAxis::setUpperEnding(const QCPLineEnding &ending)
  7637. {
  7638. mAxisPainter->upperEnding = ending;
  7639. }
  7640. /*!
  7641. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  7642. bounds of the range. The range is simply moved by \a diff.
  7643. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  7644. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  7645. */
  7646. void QCPAxis::moveRange(double diff)
  7647. {
  7648. QCPRange oldRange = mRange;
  7649. if (mScaleType == ScaleType::stLinear)
  7650. {
  7651. mRange.lower += diff;
  7652. mRange.upper += diff;
  7653. } else // mScaleType == stLogarithmic
  7654. {
  7655. mRange.lower *= diff;
  7656. mRange.upper *= diff;
  7657. }
  7658. emit rangeChanged(mRange);
  7659. emit rangeChanged(mRange, oldRange);
  7660. }
  7661. /*!
  7662. Scales the range of this axis by \a factor around the center of the current axis range. For
  7663. example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
  7664. range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
  7665. the center will have moved symmetrically closer).
  7666. If you wish to scale around a different coordinate than the current axis range center, use the
  7667. overload \ref scaleRange(double factor, double center).
  7668. */
  7669. void QCPAxis::scaleRange(double factor)
  7670. {
  7671. scaleRange(factor, range().center());
  7672. }
  7673. /*! \overload
  7674. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  7675. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  7676. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  7677. around 1.0 will have moved symmetrically closer to 1.0).
  7678. \see scaleRange(double factor)
  7679. */
  7680. void QCPAxis::scaleRange(double factor, double center)
  7681. {
  7682. QCPRange oldRange = mRange;
  7683. if (mScaleType == ScaleType::stLinear)
  7684. {
  7685. QCPRange newRange;
  7686. newRange.lower = (mRange.lower-center)*factor + center;
  7687. newRange.upper = (mRange.upper-center)*factor + center;
  7688. if (QCPRange::validRange(newRange))
  7689. mRange = newRange.sanitizedForLinScale();
  7690. } else // mScaleType == stLogarithmic
  7691. {
  7692. if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
  7693. {
  7694. QCPRange newRange;
  7695. newRange.lower = qPow(mRange.lower/center, factor)*center;
  7696. newRange.upper = qPow(mRange.upper/center, factor)*center;
  7697. if (QCPRange::validRange(newRange))
  7698. mRange = newRange.sanitizedForLogScale();
  7699. } else
  7700. qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
  7701. }
  7702. emit rangeChanged(mRange);
  7703. emit rangeChanged(mRange, oldRange);
  7704. }
  7705. /*!
  7706. Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will
  7707. be done around the center of the current axis range.
  7708. For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs
  7709. plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the
  7710. axis rect has.
  7711. This is an operation that changes the range of this axis once, it doesn't fix the scale ratio
  7712. indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent
  7713. won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent
  7714. will follow.
  7715. */
  7716. void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio)
  7717. {
  7718. int otherPixelSize, ownPixelSize;
  7719. if (otherAxis->orientation() == Qt::Horizontal)
  7720. otherPixelSize = otherAxis->axisRect()->width();
  7721. else
  7722. otherPixelSize = otherAxis->axisRect()->height();
  7723. if (orientation() == Qt::Horizontal)
  7724. ownPixelSize = axisRect()->width();
  7725. else
  7726. ownPixelSize = axisRect()->height();
  7727. double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/double(otherPixelSize);
  7728. setRange(range().center(), newRangeSize, Qt::AlignCenter);
  7729. }
  7730. /*!
  7731. Changes the axis range such that all plottables associated with this axis are fully visible in
  7732. that dimension.
  7733. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  7734. */
  7735. void QCPAxis::rescale(bool onlyVisiblePlottables)
  7736. {
  7737. QCPRange newRange;
  7738. bool haveRange = false;
  7739. foreach (QCPAbstractPlottable *plottable, plottables())
  7740. {
  7741. if (!plottable->realVisibility() && onlyVisiblePlottables)
  7742. continue;
  7743. QCPRange plottableRange;
  7744. bool currentFoundRange;
  7745. QCP::SignDomain signDomain = QCP::SignDomain::sdBoth;
  7746. if (mScaleType == ScaleType::stLogarithmic)
  7747. signDomain = (mRange.upper < 0 ? QCP::SignDomain::sdNegative : QCP::SignDomain::sdPositive);
  7748. if (plottable->keyAxis() == this)
  7749. plottableRange = plottable->getKeyRange(currentFoundRange, signDomain);
  7750. else
  7751. plottableRange = plottable->getValueRange(currentFoundRange, signDomain);
  7752. if (currentFoundRange)
  7753. {
  7754. if (!haveRange)
  7755. newRange = plottableRange;
  7756. else
  7757. newRange.expand(plottableRange);
  7758. haveRange = true;
  7759. }
  7760. }
  7761. if (haveRange)
  7762. {
  7763. 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
  7764. {
  7765. 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
  7766. if (mScaleType == ScaleType::stLinear)
  7767. {
  7768. newRange.lower = center-mRange.size()/2.0;
  7769. newRange.upper = center+mRange.size()/2.0;
  7770. } else // mScaleType == ScaleType::stLogarithmic
  7771. {
  7772. newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
  7773. newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
  7774. }
  7775. }
  7776. setRange(newRange);
  7777. }
  7778. }
  7779. /*!
  7780. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  7781. */
  7782. double QCPAxis::pixelToCoord(double value) const
  7783. {
  7784. if (orientation() == Qt::Horizontal)
  7785. {
  7786. if (mScaleType == ScaleType::stLinear)
  7787. {
  7788. if (!mRangeReversed)
  7789. return (value-mAxisRect->left())/double(mAxisRect->width())*mRange.size()+mRange.lower;
  7790. else
  7791. return -(value-mAxisRect->left())/double(mAxisRect->width())*mRange.size()+mRange.upper;
  7792. } else // mScaleType == ScaleType::stLogarithmic
  7793. {
  7794. if (!mRangeReversed)
  7795. return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/double(mAxisRect->width()))*mRange.lower;
  7796. else
  7797. return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/double(mAxisRect->width()))*mRange.upper;
  7798. }
  7799. } else // orientation() == Qt::Vertical
  7800. {
  7801. if (mScaleType == ScaleType::stLinear)
  7802. {
  7803. if (!mRangeReversed)
  7804. return (mAxisRect->bottom()-value)/double(mAxisRect->height())*mRange.size()+mRange.lower;
  7805. else
  7806. return -(mAxisRect->bottom()-value)/double(mAxisRect->height())*mRange.size()+mRange.upper;
  7807. } else // mScaleType == ScaleType::stLogarithmic
  7808. {
  7809. if (!mRangeReversed)
  7810. return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/double(mAxisRect->height()))*mRange.lower;
  7811. else
  7812. return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/double(mAxisRect->height()))*mRange.upper;
  7813. }
  7814. }
  7815. }
  7816. /*!
  7817. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  7818. */
  7819. double QCPAxis::coordToPixel(double value) const
  7820. {
  7821. if (orientation() == Qt::Horizontal)
  7822. {
  7823. if (mScaleType == ScaleType::stLinear)
  7824. {
  7825. if (!mRangeReversed)
  7826. return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left();
  7827. else
  7828. return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left();
  7829. } else // mScaleType == ScaleType::stLogarithmic
  7830. {
  7831. if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7832. return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200;
  7833. else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7834. return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200;
  7835. else
  7836. {
  7837. if (!mRangeReversed)
  7838. return qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
  7839. else
  7840. return qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left();
  7841. }
  7842. }
  7843. } else // orientation() == Qt::Vertical
  7844. {
  7845. if (mScaleType == ScaleType::stLinear)
  7846. {
  7847. if (!mRangeReversed)
  7848. return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height();
  7849. else
  7850. return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height();
  7851. } else // mScaleType == ScaleType::stLogarithmic
  7852. {
  7853. if (value >= 0.0 && mRange.upper < 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7854. return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200;
  7855. else if (value <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just draw it outside visible range
  7856. return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200;
  7857. else
  7858. {
  7859. if (!mRangeReversed)
  7860. return mAxisRect->bottom()-qLn(value/mRange.lower)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
  7861. else
  7862. return mAxisRect->bottom()-qLn(mRange.upper/value)/qLn(mRange.upper/mRange.lower)*mAxisRect->height();
  7863. }
  7864. }
  7865. }
  7866. }
  7867. /*!
  7868. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  7869. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  7870. function does not change the current selection state of the axis.
  7871. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  7872. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  7873. */
  7874. QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const
  7875. {
  7876. if (!mVisible)
  7877. return spNone;
  7878. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  7879. return spAxis;
  7880. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  7881. return spTickLabels;
  7882. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  7883. return spAxisLabel;
  7884. else
  7885. return spNone;
  7886. }
  7887. /* inherits documentation from base class */
  7888. double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  7889. {
  7890. if (!mParentPlot) return -1;
  7891. SelectablePart part = getPartAt(pos);
  7892. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  7893. return -1;
  7894. if (details)
  7895. details->setValue(part);
  7896. return mParentPlot->selectionTolerance()*0.99;
  7897. }
  7898. /*!
  7899. Returns a list of all the plottables that have this axis as key or value axis.
  7900. If you are only interested in plottables of type QCPGraph, see \ref graphs.
  7901. \see graphs, items
  7902. */
  7903. QList<QCPAbstractPlottable*> QCPAxis::plottables() const
  7904. {
  7905. QList<QCPAbstractPlottable*> result;
  7906. if (!mParentPlot) return result;
  7907. foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables)
  7908. {
  7909. if (plottable->keyAxis() == this || plottable->valueAxis() == this)
  7910. result.append(plottable);
  7911. }
  7912. return result;
  7913. }
  7914. /*!
  7915. Returns a list of all the graphs that have this axis as key or value axis.
  7916. \see plottables, items
  7917. */
  7918. QList<QCPGraph*> QCPAxis::graphs() const
  7919. {
  7920. QList<QCPGraph*> result;
  7921. if (!mParentPlot) return result;
  7922. foreach (QCPGraph *graph, mParentPlot->mGraphs)
  7923. {
  7924. if (graph->keyAxis() == this || graph->valueAxis() == this)
  7925. result.append(graph);
  7926. }
  7927. return result;
  7928. }
  7929. /*!
  7930. Returns a list of all the items that are associated with this axis. An item is considered
  7931. associated with an axis if at least one of its positions uses the axis as key or value axis.
  7932. \see plottables, graphs
  7933. */
  7934. QList<QCPAbstractItem*> QCPAxis::items() const
  7935. {
  7936. QList<QCPAbstractItem*> result;
  7937. if (!mParentPlot) return result;
  7938. foreach (QCPAbstractItem *item, mParentPlot->mItems)
  7939. {
  7940. foreach (QCPItemPosition *position, item->positions())
  7941. {
  7942. if (position->keyAxis() == this || position->valueAxis() == this)
  7943. {
  7944. result.append(item);
  7945. break;
  7946. }
  7947. }
  7948. }
  7949. return result;
  7950. }
  7951. /*!
  7952. Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to
  7953. QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.)
  7954. */
  7955. QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side)
  7956. {
  7957. switch (side)
  7958. {
  7959. case QCP::MarginSide::msLeft: return AxisType::atLeft;
  7960. case QCP::MarginSide::msRight: return AxisType::atRight;
  7961. case QCP::MarginSide::msTop: return AxisType::atTop;
  7962. case QCP::MarginSide::msBottom: return AxisType::atBottom;
  7963. default: break;
  7964. }
  7965. qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << static_cast<int>(side);
  7966. return AxisType::atLeft;
  7967. }
  7968. /*!
  7969. Returns the axis type that describes the opposite axis of an axis with the specified \a type.
  7970. */
  7971. QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type)
  7972. {
  7973. switch (type)
  7974. {
  7975. case AxisType::atLeft: return AxisType::atRight;
  7976. case AxisType::atRight: return AxisType::atLeft;
  7977. case AxisType::atBottom: return AxisType::atTop;
  7978. case AxisType::atTop: return AxisType::atBottom;
  7979. }
  7980. qDebug() << Q_FUNC_INFO << "invalid axis type";
  7981. return AxisType::atLeft;
  7982. }
  7983. /* inherits documentation from base class */
  7984. void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  7985. {
  7986. Q_UNUSED(event)
  7987. SelectablePart part = details.value<SelectablePart>();
  7988. if (mSelectableParts.testFlag(part))
  7989. {
  7990. SelectableParts selBefore = mSelectedParts;
  7991. setSelectedParts(additive ? mSelectedParts^part : part);
  7992. if (selectionStateChanged)
  7993. *selectionStateChanged = mSelectedParts != selBefore;
  7994. }
  7995. }
  7996. /* inherits documentation from base class */
  7997. void QCPAxis::deselectEvent(bool *selectionStateChanged)
  7998. {
  7999. SelectableParts selBefore = mSelectedParts;
  8000. setSelectedParts(mSelectedParts & ~mSelectableParts);
  8001. if (selectionStateChanged)
  8002. *selectionStateChanged = mSelectedParts != selBefore;
  8003. }
  8004. /*! \internal
  8005. This mouse event reimplementation provides the functionality to let the user drag individual axes
  8006. exclusively, by startig the drag on top of the axis.
  8007. For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect
  8008. must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis
  8009. (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref
  8010. QCPAxisRect::setRangeDragAxes)
  8011. \seebaseclassmethod
  8012. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  8013. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  8014. */
  8015. void QCPAxis::mousePressEvent(QMouseEvent *event, const QVariant &details)
  8016. {
  8017. Q_UNUSED(details)
  8018. if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag) ||
  8019. !mAxisRect->rangeDrag().testFlag(orientation()) ||
  8020. !mAxisRect->rangeDragAxes(orientation()).contains(this))
  8021. {
  8022. event->ignore();
  8023. return;
  8024. }
  8025. if (event->buttons() & Qt::LeftButton)
  8026. {
  8027. mDragging = true;
  8028. // initialize antialiasing backup in case we start dragging:
  8029. if (mParentPlot->noAntialiasingOnDrag())
  8030. {
  8031. mAADragBackup = mParentPlot->antialiasedElements();
  8032. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  8033. }
  8034. // Mouse range dragging interaction:
  8035. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  8036. mDragStartRange = mRange;
  8037. }
  8038. }
  8039. /*! \internal
  8040. This mouse event reimplementation provides the functionality to let the user drag individual axes
  8041. exclusively, by startig the drag on top of the axis.
  8042. \seebaseclassmethod
  8043. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  8044. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  8045. \see QCPAxis::mousePressEvent
  8046. */
  8047. void QCPAxis::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  8048. {
  8049. if (mDragging)
  8050. {
  8051. const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y();
  8052. const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y();
  8053. if (mScaleType == QCPAxis::ScaleType::stLinear)
  8054. {
  8055. const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel);
  8056. setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff);
  8057. } else if (mScaleType == QCPAxis::ScaleType::stLogarithmic)
  8058. {
  8059. const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel);
  8060. setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff);
  8061. }
  8062. if (mParentPlot->noAntialiasingOnDrag())
  8063. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  8064. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  8065. }
  8066. }
  8067. /*! \internal
  8068. This mouse event reimplementation provides the functionality to let the user drag individual axes
  8069. exclusively, by startig the drag on top of the axis.
  8070. \seebaseclassmethod
  8071. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  8072. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  8073. \see QCPAxis::mousePressEvent
  8074. */
  8075. void QCPAxis::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  8076. {
  8077. Q_UNUSED(event)
  8078. Q_UNUSED(startPos)
  8079. mDragging = false;
  8080. if (mParentPlot->noAntialiasingOnDrag())
  8081. {
  8082. mParentPlot->setAntialiasedElements(mAADragBackup);
  8083. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  8084. }
  8085. }
  8086. /*! \internal
  8087. This mouse event reimplementation provides the functionality to let the user zoom individual axes
  8088. exclusively, by performing the wheel event on top of the axis.
  8089. For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect
  8090. must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis
  8091. (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref
  8092. QCPAxisRect::setRangeZoomAxes)
  8093. \seebaseclassmethod
  8094. \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the
  8095. axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent.
  8096. */
  8097. void QCPAxis::wheelEvent(QWheelEvent *event)
  8098. {
  8099. // Mouse range zooming interaction:
  8100. if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom) ||
  8101. !mAxisRect->rangeZoom().testFlag(orientation()) ||
  8102. !mAxisRect->rangeZoomAxes(orientation()).contains(this))
  8103. {
  8104. event->ignore();
  8105. return;
  8106. }
  8107. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  8108. const double delta = event->delta();
  8109. #else
  8110. const double delta = event->angleDelta().y();
  8111. #endif
  8112. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  8113. const QPointF pos = event->pos();
  8114. #else
  8115. const QPointF pos = event->position();
  8116. #endif
  8117. const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
  8118. const double factor = qPow(mAxisRect->rangeZoomFactor(orientation()), wheelSteps);
  8119. scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? pos.x() : pos.y()));
  8120. mParentPlot->replot();
  8121. }
  8122. /*! \internal
  8123. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  8124. before drawing axis lines.
  8125. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  8126. This function takes into account the local setting of the antialiasing flag as well as the
  8127. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  8128. QCustomPlot::setNotAntialiasedElements.
  8129. \seebaseclassmethod
  8130. \see setAntialiased
  8131. */
  8132. void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const
  8133. {
  8134. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  8135. }
  8136. /*! \internal
  8137. Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
  8138. \seebaseclassmethod
  8139. */
  8140. void QCPAxis::draw(QCPPainter *painter)
  8141. {
  8142. QVector<double> subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  8143. QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  8144. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  8145. tickPositions.reserve(mTickVector.size());
  8146. tickLabels.reserve(mTickVector.size());
  8147. subTickPositions.reserve(mSubTickVector.size());
  8148. if (mTicks)
  8149. {
  8150. for (int i=0; i<mTickVector.size(); ++i)
  8151. {
  8152. tickPositions.append(coordToPixel(mTickVector.at(i)));
  8153. if (mTickLabels)
  8154. tickLabels.append(mTickVectorLabels.at(i));
  8155. }
  8156. if (mSubTicks)
  8157. {
  8158. const int subTickCount = mSubTickVector.size();
  8159. for (int i=0; i<subTickCount; ++i)
  8160. subTickPositions.append(coordToPixel(mSubTickVector.at(i)));
  8161. }
  8162. }
  8163. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to draw the axis.
  8164. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
  8165. mAxisPainter->type = mAxisType;
  8166. mAxisPainter->basePen = getBasePen();
  8167. mAxisPainter->labelFont = getLabelFont();
  8168. mAxisPainter->labelColor = getLabelColor();
  8169. mAxisPainter->label = mLabel;
  8170. mAxisPainter->substituteExponent = mNumberBeautifulPowers;
  8171. mAxisPainter->tickPen = getTickPen();
  8172. mAxisPainter->subTickPen = getSubTickPen();
  8173. mAxisPainter->tickLabelFont = getTickLabelFont();
  8174. mAxisPainter->tickLabelColor = getTickLabelColor();
  8175. mAxisPainter->axisRect = mAxisRect->rect();
  8176. mAxisPainter->viewportRect = mParentPlot->viewport();
  8177. mAxisPainter->abbreviateDecimalPowers = mScaleType == ScaleType::stLogarithmic;
  8178. mAxisPainter->reversedEndings = mRangeReversed;
  8179. mAxisPainter->tickPositions = tickPositions;
  8180. mAxisPainter->tickLabels = tickLabels;
  8181. mAxisPainter->subTickPositions = subTickPositions;
  8182. mAxisPainter->draw(painter);
  8183. }
  8184. /*! \internal
  8185. Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
  8186. QCPAxisTicker::generate on the currently installed ticker.
  8187. If a change in the label text/count is detected, the cached axis margin is invalidated to make
  8188. sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
  8189. */
  8190. void QCPAxis::setupTickVectors()
  8191. {
  8192. if (!mParentPlot) return;
  8193. if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
  8194. QVector<QString> oldLabels = mTickVectorLabels;
  8195. mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : nullptr, mTickLabels ? &mTickVectorLabels : nullptr);
  8196. mCachedMarginValid &= mTickVectorLabels == oldLabels; // if labels have changed, margin might have changed, too
  8197. }
  8198. /*! \internal
  8199. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  8200. is either mSelectedBasePen or mBasePen.
  8201. */
  8202. QPen QCPAxis::getBasePen() const
  8203. {
  8204. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  8205. }
  8206. /*! \internal
  8207. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  8208. is either mSelectedTickPen or mTickPen.
  8209. */
  8210. QPen QCPAxis::getTickPen() const
  8211. {
  8212. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  8213. }
  8214. /*! \internal
  8215. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  8216. is either mSelectedSubTickPen or mSubTickPen.
  8217. */
  8218. QPen QCPAxis::getSubTickPen() const
  8219. {
  8220. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  8221. }
  8222. /*! \internal
  8223. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  8224. is either mSelectedTickLabelFont or mTickLabelFont.
  8225. */
  8226. QFont QCPAxis::getTickLabelFont() const
  8227. {
  8228. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  8229. }
  8230. /*! \internal
  8231. Returns the font that is used to draw the axis label. Depending on the selection state, this
  8232. is either mSelectedLabelFont or mLabelFont.
  8233. */
  8234. QFont QCPAxis::getLabelFont() const
  8235. {
  8236. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  8237. }
  8238. /*! \internal
  8239. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  8240. is either mSelectedTickLabelColor or mTickLabelColor.
  8241. */
  8242. QColor QCPAxis::getTickLabelColor() const
  8243. {
  8244. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  8245. }
  8246. /*! \internal
  8247. Returns the color that is used to draw the axis label. Depending on the selection state, this
  8248. is either mSelectedLabelColor or mLabelColor.
  8249. */
  8250. QColor QCPAxis::getLabelColor() const
  8251. {
  8252. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  8253. }
  8254. /*! \internal
  8255. Returns the appropriate outward margin for this axis. It is needed if \ref
  8256. QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref
  8257. atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom
  8258. margin and so forth. For the calculation, this function goes through similar steps as \ref draw,
  8259. so changing one function likely requires the modification of the other one as well.
  8260. The margin consists of the outward tick length, tick label padding, tick label size, label
  8261. padding, label size, and padding.
  8262. The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc.
  8263. unchanged are very fast.
  8264. */
  8265. int QCPAxis::calculateMargin()
  8266. {
  8267. if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis
  8268. return 0;
  8269. if (mCachedMarginValid)
  8270. return mCachedMargin;
  8271. // run through similar steps as QCPAxis::draw, and calculate margin needed to fit axis and its labels
  8272. int margin = 0;
  8273. QVector<double> tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter
  8274. QVector<QString> tickLabels; // the final vector passed to QCPAxisPainter
  8275. tickPositions.reserve(mTickVector.size());
  8276. tickLabels.reserve(mTickVector.size());
  8277. if (mTicks)
  8278. {
  8279. for (int i=0; i<mTickVector.size(); ++i)
  8280. {
  8281. tickPositions.append(coordToPixel(mTickVector.at(i)));
  8282. if (mTickLabels)
  8283. tickLabels.append(mTickVectorLabels.at(i));
  8284. }
  8285. }
  8286. // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size.
  8287. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters
  8288. mAxisPainter->type = mAxisType;
  8289. mAxisPainter->labelFont = getLabelFont();
  8290. mAxisPainter->label = mLabel;
  8291. mAxisPainter->tickLabelFont = mTickLabelFont;
  8292. mAxisPainter->axisRect = mAxisRect->rect();
  8293. mAxisPainter->viewportRect = mParentPlot->viewport();
  8294. mAxisPainter->tickPositions = tickPositions;
  8295. mAxisPainter->tickLabels = tickLabels;
  8296. margin += mAxisPainter->size();
  8297. margin += mPadding;
  8298. mCachedMargin = margin;
  8299. mCachedMarginValid = true;
  8300. return margin;
  8301. }
  8302. /* inherits documentation from base class */
  8303. QCP::Interaction QCPAxis::selectionCategory() const
  8304. {
  8305. return QCP::iSelectAxes;
  8306. }
  8307. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8308. //////////////////// QCPAxisPainterPrivate
  8309. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8310. /*! \class QCPAxisPainterPrivate
  8311. \internal
  8312. \brief (Private)
  8313. This is a private class and not part of the public QCustomPlot interface.
  8314. It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and
  8315. axis label. It also buffers the labels to reduce replot times. The parameters are configured by
  8316. directly accessing the public member variables.
  8317. */
  8318. /*!
  8319. Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every
  8320. redraw, to utilize the caching mechanisms.
  8321. */
  8322. QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) :
  8323. type(QCPAxis::AxisType::atLeft),
  8324. basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  8325. lowerEnding(QCPLineEnding:: EndingStyle::esNone),
  8326. upperEnding(QCPLineEnding::EndingStyle::esNone),
  8327. labelPadding(0),
  8328. tickLabelPadding(0),
  8329. tickLabelRotation(0),
  8330. tickLabelSide(QCPAxis::LabelSide::lsOutside),
  8331. substituteExponent(true),
  8332. numberMultiplyCross(false),
  8333. tickLengthIn(5),
  8334. tickLengthOut(0),
  8335. subTickLengthIn(2),
  8336. subTickLengthOut(0),
  8337. tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  8338. subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  8339. offset(0),
  8340. abbreviateDecimalPowers(false),
  8341. reversedEndings(false),
  8342. mParentPlot(parentPlot),
  8343. mLabelCache(16) // cache at most 16 (tick) labels
  8344. {
  8345. }
  8346. QCPAxisPainterPrivate::~QCPAxisPainterPrivate()
  8347. {
  8348. }
  8349. /*! \internal
  8350. Draws the axis with the specified \a painter.
  8351. The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set
  8352. here, too.
  8353. */
  8354. void QCPAxisPainterPrivate::draw(QCPPainter *painter)
  8355. {
  8356. QByteArray newHash = generateLabelParameterHash();
  8357. if (newHash != mLabelParameterHash)
  8358. {
  8359. mLabelCache.clear();
  8360. mLabelParameterHash = newHash;
  8361. }
  8362. QPoint origin;
  8363. switch (type)
  8364. {
  8365. case QCPAxis::AxisType::atLeft: origin = axisRect.bottomLeft() +QPoint(-offset, 0); break;
  8366. case QCPAxis::AxisType::atRight: origin = axisRect.bottomRight()+QPoint(+offset, 0); break;
  8367. case QCPAxis::AxisType::atTop: origin = axisRect.topLeft() +QPoint(0, -offset); break;
  8368. case QCPAxis::AxisType::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break;
  8369. }
  8370. double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes)
  8371. switch (type)
  8372. {
  8373. case QCPAxis::AxisType::atTop: yCor = -1; break;
  8374. case QCPAxis::AxisType::atRight: xCor = 1; break;
  8375. default: break;
  8376. }
  8377. int margin = 0;
  8378. // draw baseline:
  8379. QLineF baseLine;
  8380. painter->setPen(basePen);
  8381. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8382. baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor));
  8383. else
  8384. baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor));
  8385. if (reversedEndings)
  8386. baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later
  8387. painter->drawLine(baseLine);
  8388. // draw ticks:
  8389. if (!tickPositions.isEmpty())
  8390. {
  8391. painter->setPen(tickPen);
  8392. int tickDir = (type == QCPAxis::AxisType::atBottom || type == QCPAxis::AxisType::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis)
  8393. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8394. {
  8395. foreach (double tickPos, tickPositions)
  8396. painter->drawLine(QLineF((double)tickPos+ (double)xCor, (double)origin.y()- (double)tickLengthOut* (double)tickDir+ (double)yCor, (double)tickPos+ (double)xCor, (double)origin.y()+ (double)tickLengthIn* (double)tickDir+ (double)yCor));
  8397. } else
  8398. {
  8399. foreach (double tickPos, tickPositions)
  8400. painter->drawLine(QLineF((double)origin.x()- (double)tickLengthOut* (double)tickDir+ (double)xCor, (double)tickPos+ (double)yCor, (double)origin.x()+ (double)tickLengthIn* (double)tickDir+ (double)xCor, (double)tickPos+ (double)yCor));
  8401. }
  8402. }
  8403. // draw subticks:
  8404. if (!subTickPositions.isEmpty())
  8405. {
  8406. painter->setPen(subTickPen);
  8407. // direction of ticks ("inward" is right for left axis and left for right axis)
  8408. int tickDir = (type == QCPAxis::AxisType::atBottom || type == QCPAxis::AxisType::atRight) ? -1 : 1;
  8409. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8410. {
  8411. foreach (double subTickPos, subTickPositions)
  8412. painter->drawLine(QLineF(subTickPos+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPos+xCor, origin.y()+subTickLengthIn*tickDir+yCor));
  8413. } else
  8414. {
  8415. foreach (double subTickPos, subTickPositions)
  8416. painter->drawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPos+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPos+yCor));
  8417. }
  8418. }
  8419. margin += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  8420. // draw axis base endings:
  8421. bool antialiasingBackup = painter->antialiasing();
  8422. painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't
  8423. painter->setBrush(QBrush(basePen.color()));
  8424. QCPVector2D baseLineVector(baseLine.dx(), baseLine.dy());
  8425. if (lowerEnding.style() != QCPLineEnding::EndingStyle::esNone)
  8426. lowerEnding.draw(painter, QCPVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector);
  8427. if (upperEnding.style() != QCPLineEnding::EndingStyle::esNone)
  8428. upperEnding.draw(painter, QCPVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector);
  8429. painter->setAntialiasing(antialiasingBackup);
  8430. // tick labels:
  8431. QRect oldClipRect;
  8432. if (tickLabelSide == QCPAxis::LabelSide::lsInside) // if using inside labels, clip them to the axis rect
  8433. {
  8434. oldClipRect = painter->clipRegion().boundingRect();
  8435. painter->setClipRect(axisRect);
  8436. }
  8437. QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label
  8438. if (!tickLabels.isEmpty())
  8439. {
  8440. if (tickLabelSide == QCPAxis::LabelSide::lsOutside)
  8441. margin += tickLabelPadding;
  8442. painter->setFont(tickLabelFont);
  8443. painter->setPen(QPen(tickLabelColor));
  8444. const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size());
  8445. int distanceToAxis = margin;
  8446. if (tickLabelSide == QCPAxis::LabelSide::lsInside)
  8447. distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
  8448. for (int i=0; i<maxLabelIndex; ++i)
  8449. placeTickLabel(painter, tickPositions.at(i), distanceToAxis, tickLabels.at(i), &tickLabelsSize);
  8450. if (tickLabelSide == QCPAxis::LabelSide::lsOutside)
  8451. margin += (QCPAxis::orientation(type) == Qt::Horizontal) ? tickLabelsSize.height() : tickLabelsSize.width();
  8452. }
  8453. if (tickLabelSide == QCPAxis::LabelSide::lsInside)
  8454. painter->setClipRect(oldClipRect);
  8455. // axis label:
  8456. QRect labelBounds;
  8457. if (!label.isEmpty())
  8458. {
  8459. margin += labelPadding;
  8460. painter->setFont(labelFont);
  8461. painter->setPen(QPen(labelColor));
  8462. labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label);
  8463. if (type == QCPAxis::AxisType::atLeft)
  8464. {
  8465. QTransform oldTransform = painter->transform();
  8466. painter->translate((origin.x()-margin-labelBounds.height()), origin.y());
  8467. painter->rotate(-90);
  8468. painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8469. painter->setTransform(oldTransform);
  8470. }
  8471. else if (type == QCPAxis::AxisType::atRight)
  8472. {
  8473. QTransform oldTransform = painter->transform();
  8474. painter->translate(((double)origin.x()+ (double)margin+labelBounds.height()), (double)origin.y()- (double)axisRect.height());
  8475. painter->rotate(90);
  8476. painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8477. painter->setTransform(oldTransform);
  8478. }
  8479. else if (type == QCPAxis::AxisType::atTop)
  8480. painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8481. else if (type == QCPAxis::AxisType::atBottom)
  8482. painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label);
  8483. }
  8484. // set selection boxes:
  8485. int selectionTolerance = 0;
  8486. if (mParentPlot)
  8487. selectionTolerance = mParentPlot->selectionTolerance();
  8488. else
  8489. qDebug() << Q_FUNC_INFO << "mParentPlot is null";
  8490. int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance);
  8491. int selAxisInSize = selectionTolerance;
  8492. int selTickLabelSize;
  8493. int selTickLabelOffset;
  8494. if (tickLabelSide == QCPAxis::LabelSide::lsOutside)
  8495. {
  8496. selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
  8497. selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding;
  8498. } else
  8499. {
  8500. selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width());
  8501. selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding);
  8502. }
  8503. int selLabelSize = labelBounds.height();
  8504. int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::LabelSide::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding;
  8505. if (type == QCPAxis::AxisType::atLeft)
  8506. {
  8507. mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom());
  8508. mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom());
  8509. mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom());
  8510. } else if (type == QCPAxis::AxisType::atRight)
  8511. {
  8512. mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom());
  8513. mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom());
  8514. mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom());
  8515. } else if (type == QCPAxis::AxisType::atTop)
  8516. {
  8517. mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize);
  8518. mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset);
  8519. mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset);
  8520. } else if (type == QCPAxis::AxisType::atBottom)
  8521. {
  8522. mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize);
  8523. mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset);
  8524. mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset);
  8525. }
  8526. mAxisSelectionBox = mAxisSelectionBox.normalized();
  8527. mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized();
  8528. mLabelSelectionBox = mLabelSelectionBox.normalized();
  8529. // draw hitboxes for debug purposes:
  8530. //painter->setBrush(Qt::NoBrush);
  8531. //painter->drawRects(QVector<QRect>() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox);
  8532. }
  8533. /*! \internal
  8534. Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone
  8535. direction) needed to fit the axis.
  8536. */
  8537. int QCPAxisPainterPrivate::size()
  8538. {
  8539. int result = 0;
  8540. QByteArray newHash = generateLabelParameterHash();
  8541. if (newHash != mLabelParameterHash)
  8542. {
  8543. mLabelCache.clear();
  8544. mLabelParameterHash = newHash;
  8545. }
  8546. // get length of tick marks pointing outwards:
  8547. if (!tickPositions.isEmpty())
  8548. result += qMax(0, qMax(tickLengthOut, subTickLengthOut));
  8549. // calculate size of tick labels:
  8550. if (tickLabelSide == QCPAxis::LabelSide::lsOutside)
  8551. {
  8552. QSize tickLabelsSize(0, 0);
  8553. if (!tickLabels.isEmpty())
  8554. {
  8555. foreach (const QString &tickLabel, tickLabels)
  8556. getMaxTickLabelSize(tickLabelFont, tickLabel, &tickLabelsSize);
  8557. result += QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width();
  8558. result += tickLabelPadding;
  8559. }
  8560. }
  8561. // calculate size of axis label (only height needed, because left/right labels are rotated by 90 degrees):
  8562. if (!label.isEmpty())
  8563. {
  8564. QFontMetrics fontMetrics(labelFont);
  8565. QRect bounds;
  8566. bounds = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter | Qt::AlignVCenter, label);
  8567. result += bounds.height() + labelPadding;
  8568. }
  8569. return result;
  8570. }
  8571. /*! \internal
  8572. Clears the internal label cache. Upon the next \ref draw, all labels will be created new. This
  8573. method is called automatically in \ref draw, if any parameters have changed that invalidate the
  8574. cached labels, such as font, color, etc.
  8575. */
  8576. void QCPAxisPainterPrivate::clearCache()
  8577. {
  8578. mLabelCache.clear();
  8579. }
  8580. /*! \internal
  8581. Returns a hash that allows uniquely identifying whether the label parameters have changed such
  8582. that the cached labels must be refreshed (\ref clearCache). It is used in \ref draw. If the
  8583. return value of this method hasn't changed since the last redraw, the respective label parameters
  8584. haven't changed and cached labels may be used.
  8585. */
  8586. QByteArray QCPAxisPainterPrivate::generateLabelParameterHash() const
  8587. {
  8588. QByteArray result;
  8589. result.append(QByteArray::number(mParentPlot->bufferDevicePixelRatio()));
  8590. result.append(QByteArray::number(tickLabelRotation));
  8591. result.append(QByteArray::number(int(tickLabelSide)));
  8592. result.append(QByteArray::number(int(substituteExponent)));
  8593. result.append(QByteArray::number(int(numberMultiplyCross)));
  8594. result.append(tickLabelColor.name().toLatin1()+QByteArray::number(tickLabelColor.alpha(), 16));
  8595. result.append(tickLabelFont.toString().toLatin1());
  8596. return result;
  8597. }
  8598. /*! \internal
  8599. Draws a single tick label with the provided \a painter, utilizing the internal label cache to
  8600. significantly speed up drawing of labels that were drawn in previous calls. The tick label is
  8601. always bound to an axis, the distance to the axis is controllable via \a distanceToAxis in
  8602. pixels. The pixel position in the axis direction is passed in the \a position parameter. Hence
  8603. for the bottom axis, \a position would indicate the horizontal pixel position (not coordinate),
  8604. at which the label should be drawn.
  8605. In order to later draw the axis label in a place that doesn't overlap with the tick labels, the
  8606. largest tick label size is needed. This is acquired by passing a \a tickLabelsSize to the \ref
  8607. drawTickLabel calls during the process of drawing all tick labels of one axis. In every call, \a
  8608. tickLabelsSize is expanded, if the drawn label exceeds the value \a tickLabelsSize currently
  8609. holds.
  8610. The label is drawn with the font and pen that are currently set on the \a painter. To draw
  8611. superscripted powers, the font is temporarily made smaller by a fixed factor (see \ref
  8612. getTickLabelData).
  8613. */
  8614. void QCPAxisPainterPrivate::placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize)
  8615. {
  8616. // warning: if you change anything here, also adapt getMaxTickLabelSize() accordingly!
  8617. if (text.isEmpty()) return;
  8618. QSize finalSize;
  8619. QPointF labelAnchor;
  8620. switch (type)
  8621. {
  8622. case QCPAxis::AxisType::atLeft: labelAnchor = QPointF((double)axisRect.left()- (double)distanceToAxis- (double)offset, position); break;
  8623. case QCPAxis::AxisType::atRight: labelAnchor = QPointF((double)axisRect.right()+ (double)distanceToAxis+ (double)offset, position); break;
  8624. case QCPAxis::AxisType::atTop: labelAnchor = QPointF(position, (double)axisRect.top()- (double)distanceToAxis- (double)offset); break;
  8625. case QCPAxis::AxisType::atBottom: labelAnchor = QPointF(position, (double)axisRect.bottom()+ (double)distanceToAxis+ (double)offset); break;
  8626. }
  8627. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled
  8628. {
  8629. CachedLabel *cachedLabel = mLabelCache.take(text); // attempt to get label from cache
  8630. if (!cachedLabel) // no cached label existed, create it
  8631. {
  8632. cachedLabel = new CachedLabel;
  8633. TickLabelData labelData = getTickLabelData(painter->font(), text);
  8634. cachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft();
  8635. if (!qFuzzyCompare(1.0, mParentPlot->bufferDevicePixelRatio()))
  8636. {
  8637. cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()*mParentPlot->bufferDevicePixelRatio());
  8638. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  8639. # ifdef QCP_DEVICEPIXELRATIO_FLOAT
  8640. cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatioF());
  8641. # else
  8642. cachedLabel->pixmap.setDevicePixelRatio(mParentPlot->devicePixelRatio());
  8643. # endif
  8644. #endif
  8645. } else
  8646. cachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size());
  8647. cachedLabel->pixmap.fill(Qt::transparent);
  8648. QCPPainter cachePainter(&cachedLabel->pixmap);
  8649. cachePainter.setPen(painter->pen());
  8650. drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData);
  8651. }
  8652. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  8653. bool labelClippedByBorder = false;
  8654. if (tickLabelSide == QCPAxis::LabelSide::lsOutside)
  8655. {
  8656. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8657. labelClippedByBorder = labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width()/mParentPlot->bufferDevicePixelRatio() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left();
  8658. else
  8659. labelClippedByBorder = labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height()/mParentPlot->bufferDevicePixelRatio() > viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top();
  8660. }
  8661. if (!labelClippedByBorder)
  8662. {
  8663. painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap);
  8664. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
  8665. }
  8666. mLabelCache.insert(text, cachedLabel); // return label to cache or insert for the first time if newly created
  8667. } else // label caching disabled, draw text directly on surface:
  8668. {
  8669. TickLabelData labelData = getTickLabelData(painter->font(), text);
  8670. QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData);
  8671. // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels):
  8672. bool labelClippedByBorder = false;
  8673. if (tickLabelSide == QCPAxis::LabelSide::lsOutside)
  8674. {
  8675. if (QCPAxis::orientation(type) == Qt::Horizontal)
  8676. labelClippedByBorder = (double)finalPosition.x()+((double)labelData.rotatedTotalBounds.width()+ (double)labelData.rotatedTotalBounds.left()) > viewportRect.right() || (double)finalPosition.x()+ (double)labelData.rotatedTotalBounds.left() < viewportRect.left();
  8677. else
  8678. labelClippedByBorder = (double)finalPosition.y()+((double)labelData.rotatedTotalBounds.height()+ (double)labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || (double)finalPosition.y()+ (double)labelData.rotatedTotalBounds.top() < viewportRect.top();
  8679. }
  8680. if (!labelClippedByBorder)
  8681. {
  8682. drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData);
  8683. finalSize = labelData.rotatedTotalBounds.size();
  8684. }
  8685. }
  8686. // expand passed tickLabelsSize if current tick label is larger:
  8687. if (finalSize.width() > tickLabelsSize->width())
  8688. tickLabelsSize->setWidth(finalSize.width());
  8689. if (finalSize.height() > tickLabelsSize->height())
  8690. tickLabelsSize->setHeight(finalSize.height());
  8691. }
  8692. /*! \internal
  8693. This is a \ref placeTickLabel helper function.
  8694. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a
  8695. y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to
  8696. directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when
  8697. QCP::phCacheLabels plotting hint is not set.
  8698. */
  8699. void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const
  8700. {
  8701. // backup painter settings that we're about to change:
  8702. QTransform oldTransform = painter->transform();
  8703. QFont oldFont = painter->font();
  8704. // transform painter to position/rotation:
  8705. painter->translate(x, y);
  8706. if (!qFuzzyIsNull(tickLabelRotation))
  8707. painter->rotate(tickLabelRotation);
  8708. // draw text:
  8709. if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used
  8710. {
  8711. painter->setFont(labelData.baseFont);
  8712. painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart);
  8713. if (!labelData.suffixPart.isEmpty())
  8714. painter->drawText(labelData.baseBounds.width()+1+labelData.expBounds.width(), 0, 0, 0, Qt::TextDontClip, labelData.suffixPart);
  8715. painter->setFont(labelData.expFont);
  8716. painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart);
  8717. } else
  8718. {
  8719. painter->setFont(labelData.baseFont);
  8720. painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart);
  8721. }
  8722. // reset painter settings to what it was before:
  8723. painter->setTransform(oldTransform);
  8724. painter->setFont(oldFont);
  8725. }
  8726. /*! \internal
  8727. This is a \ref placeTickLabel helper function.
  8728. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further
  8729. processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and
  8730. exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes.
  8731. */
  8732. QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const
  8733. {
  8734. TickLabelData result;
  8735. // determine whether beautiful decimal powers should be used
  8736. bool useBeautifulPowers = false;
  8737. int ePos = -1; // first index of exponent part, text before that will be basePart, text until eLast will be expPart
  8738. int eLast = -1; // last index of exponent part, rest of text after this will be suffixPart
  8739. if (substituteExponent)
  8740. {
  8741. ePos = text.indexOf(QLatin1Char('e'));
  8742. if (ePos > 0 && text.at(ePos-1).isDigit())
  8743. {
  8744. eLast = ePos;
  8745. while (eLast+1 < text.size() && (text.at(eLast+1) == QLatin1Char('+') || text.at(eLast+1) == QLatin1Char('-') || text.at(eLast+1).isDigit()))
  8746. ++eLast;
  8747. if (eLast > ePos) // only if also to right of 'e' is a digit/+/- interpret it as beautifiable power
  8748. useBeautifulPowers = true;
  8749. }
  8750. }
  8751. // calculate text bounding rects and do string preparation for beautiful decimal powers:
  8752. result.baseFont = font;
  8753. if (result.baseFont.pointSizeF() > 0) // might return -1 if specified with setPixelSize, in that case we can't do correction in next line
  8754. 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
  8755. if (useBeautifulPowers)
  8756. {
  8757. // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent:
  8758. result.basePart = text.left(ePos);
  8759. result.suffixPart = text.mid(eLast+1); // also drawn normally but after exponent
  8760. // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base:
  8761. if (abbreviateDecimalPowers && result.basePart == QLatin1String("1"))
  8762. result.basePart = QLatin1String("10");
  8763. else
  8764. result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + QLatin1String("10");
  8765. result.expPart = text.mid(ePos+1, eLast-ePos);
  8766. // clip "+" and leading zeros off expPart:
  8767. while (result.expPart.length() > 2 && result.expPart.at(1) == QLatin1Char('0')) // length > 2 so we leave one zero when numberFormatChar is 'e'
  8768. result.expPart.remove(1, 1);
  8769. if (!result.expPart.isEmpty() && result.expPart.at(0) == QLatin1Char('+'))
  8770. result.expPart.remove(0, 1);
  8771. // prepare smaller font for exponent:
  8772. result.expFont = font;
  8773. if (result.expFont.pointSize() > 0)
  8774. result.expFont.setPointSize(int(result.expFont.pointSize()*0.75));
  8775. else
  8776. result.expFont.setPixelSize(int(result.expFont.pixelSize()*0.75));
  8777. // calculate bounding rects of base part(s), exponent part and total one:
  8778. result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart);
  8779. result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart);
  8780. if (!result.suffixPart.isEmpty())
  8781. result.suffixBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.suffixPart);
  8782. 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
  8783. } else // useBeautifulPowers == false
  8784. {
  8785. result.basePart = text;
  8786. result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart);
  8787. }
  8788. 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
  8789. // calculate possibly different bounding rect after rotation:
  8790. result.rotatedTotalBounds = result.totalBounds;
  8791. if (!qFuzzyIsNull(tickLabelRotation))
  8792. {
  8793. QTransform transform;
  8794. transform.rotate(tickLabelRotation);
  8795. result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds);
  8796. }
  8797. return result;
  8798. }
  8799. /*! \internal
  8800. This is a \ref placeTickLabel helper function.
  8801. Calculates the offset at which the top left corner of the specified tick label shall be drawn.
  8802. The offset is relative to a point right next to the tick the label belongs to.
  8803. This function is thus responsible for e.g. centering tick labels under ticks and positioning them
  8804. appropriately when they are rotated.
  8805. */
  8806. QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const
  8807. {
  8808. /*
  8809. calculate label offset from base point at tick (non-trivial, for best visual appearance): short
  8810. explanation for bottom axis: The anchor, i.e. the point in the label that is placed
  8811. horizontally under the corresponding tick is always on the label side that is closer to the
  8812. axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height
  8813. is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text
  8814. will be centered under the tick (i.e. displaced horizontally by half its height). At the same
  8815. time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick
  8816. labels.
  8817. */
  8818. bool doRotation = !qFuzzyIsNull(tickLabelRotation);
  8819. bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes.
  8820. double radians = tickLabelRotation/180.0*M_PI;
  8821. double x = 0;
  8822. double y = 0;
  8823. if ((type == QCPAxis::AxisType::atLeft && tickLabelSide == QCPAxis::LabelSide::lsOutside) || (type == QCPAxis::AxisType::atRight && tickLabelSide == QCPAxis::LabelSide::lsInside)) // Anchor at right side of tick label
  8824. {
  8825. if (doRotation)
  8826. {
  8827. if (tickLabelRotation > 0)
  8828. {
  8829. x = -qCos(radians)*labelData.totalBounds.width();
  8830. y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0;
  8831. } else
  8832. {
  8833. x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height();
  8834. y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0;
  8835. }
  8836. } else
  8837. {
  8838. x = -labelData.totalBounds.width();
  8839. y = -labelData.totalBounds.height()/2.0;
  8840. }
  8841. } else if ((type == QCPAxis::AxisType::atRight && tickLabelSide == QCPAxis::LabelSide::lsOutside) || (type == QCPAxis::AxisType::atLeft && tickLabelSide == QCPAxis::LabelSide::lsInside)) // Anchor at left side of tick label
  8842. {
  8843. if (doRotation)
  8844. {
  8845. if (tickLabelRotation > 0)
  8846. {
  8847. x = +qSin(radians)*labelData.totalBounds.height();
  8848. y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0;
  8849. } else
  8850. {
  8851. x = 0;
  8852. y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0;
  8853. }
  8854. } else
  8855. {
  8856. x = 0;
  8857. y = -labelData.totalBounds.height()/2.0;
  8858. }
  8859. } else if ((type == QCPAxis::AxisType::atTop && tickLabelSide == QCPAxis::LabelSide::lsOutside) || (type == QCPAxis::AxisType::atBottom && tickLabelSide == QCPAxis::LabelSide::lsInside)) // Anchor at bottom side of tick label
  8860. {
  8861. if (doRotation)
  8862. {
  8863. if (tickLabelRotation > 0)
  8864. {
  8865. x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0;
  8866. y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height();
  8867. } else
  8868. {
  8869. x = -qSin(-radians)*labelData.totalBounds.height()/2.0;
  8870. y = -qCos(-radians)*labelData.totalBounds.height();
  8871. }
  8872. } else
  8873. {
  8874. x = -labelData.totalBounds.width()/2.0;
  8875. y = -labelData.totalBounds.height();
  8876. }
  8877. } else if ((type == QCPAxis::AxisType::atBottom && tickLabelSide == QCPAxis::LabelSide::lsOutside) || (type == QCPAxis::AxisType::atTop && tickLabelSide == QCPAxis::LabelSide::lsInside)) // Anchor at top side of tick label
  8878. {
  8879. if (doRotation)
  8880. {
  8881. if (tickLabelRotation > 0)
  8882. {
  8883. x = +qSin(radians)*labelData.totalBounds.height()/2.0;
  8884. y = 0;
  8885. } else
  8886. {
  8887. x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0;
  8888. y = +qSin(-radians)*labelData.totalBounds.width();
  8889. }
  8890. } else
  8891. {
  8892. x = -labelData.totalBounds.width()/2.0;
  8893. y = 0;
  8894. }
  8895. }
  8896. return {x, y};
  8897. }
  8898. /*! \internal
  8899. Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label
  8900. to be drawn, depending on number format etc. Since only the largest tick label is wanted for the
  8901. margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a
  8902. smaller width/height.
  8903. */
  8904. void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const
  8905. {
  8906. // note: this function must return the same tick label sizes as the placeTickLabel function.
  8907. QSize finalSize;
  8908. if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label
  8909. {
  8910. const CachedLabel *cachedLabel = mLabelCache.object(text);
  8911. finalSize = cachedLabel->pixmap.size()/mParentPlot->bufferDevicePixelRatio();
  8912. } else // label caching disabled or no label with this text cached:
  8913. {
  8914. TickLabelData labelData = getTickLabelData(font, text);
  8915. finalSize = labelData.rotatedTotalBounds.size();
  8916. }
  8917. // expand passed tickLabelsSize if current tick label is larger:
  8918. if (finalSize.width() > tickLabelsSize->width())
  8919. tickLabelsSize->setWidth(finalSize.width());
  8920. if (finalSize.height() > tickLabelsSize->height())
  8921. tickLabelsSize->setHeight(finalSize.height());
  8922. }
  8923. /* end of 'src/axis/axis.cpp' */
  8924. /* including file 'src/scatterstyle.cpp' */
  8925. /* modified 2021-03-29T02:30:44, size 17466 */
  8926. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8927. //////////////////// QCPScatterStyle
  8928. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8929. /*! \class QCPScatterStyle
  8930. \brief Represents the visual appearance of scatter points
  8931. This class holds information about shape, color and size of scatter points. In plottables like
  8932. QCPGraph it is used to store how scatter points shall be drawn. For example, \ref
  8933. QCPGraph::setScatterStyle takes a QCPScatterStyle instance.
  8934. A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a
  8935. fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can
  8936. be controlled with \ref setSize.
  8937. \section QCPScatterStyle-defining Specifying a scatter style
  8938. You can set all these configurations either by calling the respective functions on an instance:
  8939. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-1
  8940. Or you can use one of the various constructors that take different parameter combinations, making
  8941. it easy to specify a scatter style in a single call, like so:
  8942. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-creation-2
  8943. \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable
  8944. There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref
  8945. QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref
  8946. isPenDefined will return false. It leads to scatter points that inherit the pen from the
  8947. plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line
  8948. color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes
  8949. it very convenient to set up typical scatter settings:
  8950. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpscatterstyle-shortcreation
  8951. Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works
  8952. because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly
  8953. into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size)
  8954. constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref
  8955. ScatterShape, where actually a QCPScatterStyle is expected.
  8956. \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps
  8957. QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points.
  8958. For custom shapes, you can provide a QPainterPath with the desired shape to the \ref
  8959. setCustomPath function or call the constructor that takes a painter path. The scatter shape will
  8960. automatically be set to \ref ssCustom.
  8961. For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the
  8962. constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap.
  8963. Note that \ref setSize does not influence the appearance of the pixmap.
  8964. */
  8965. /* start documentation of inline functions */
  8966. /*! \fn bool QCPScatterStyle::isNone() const
  8967. Returns whether the scatter shape is \ref ssNone.
  8968. \see setShape
  8969. */
  8970. /*! \fn bool QCPScatterStyle::isPenDefined() const
  8971. Returns whether a pen has been defined for this scatter style.
  8972. The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those
  8973. are \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen
  8974. is undefined, the pen of the respective plottable will be used for drawing scatters.
  8975. If a pen was defined for this scatter style instance, and you now wish to undefine the pen, call
  8976. \ref undefinePen.
  8977. \see setPen
  8978. */
  8979. /* end documentation of inline functions */
  8980. /*!
  8981. Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined.
  8982. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  8983. from the plottable that uses this scatter style.
  8984. */
  8985. QCPScatterStyle::QCPScatterStyle() :
  8986. mSize(6),
  8987. mShape(ssNone),
  8988. mPen(Qt::NoPen),
  8989. mBrush(Qt::NoBrush),
  8990. mPenDefined(false)
  8991. {
  8992. }
  8993. /*!
  8994. Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or
  8995. brush is defined.
  8996. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited
  8997. from the plottable that uses this scatter style.
  8998. */
  8999. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) :
  9000. mSize(size),
  9001. mShape(shape),
  9002. mPen(Qt::NoPen),
  9003. mBrush(Qt::NoBrush),
  9004. mPenDefined(false)
  9005. {
  9006. }
  9007. /*!
  9008. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  9009. and size to \a size. No brush is defined, i.e. the scatter point will not be filled.
  9010. */
  9011. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) :
  9012. mSize(size),
  9013. mShape(shape),
  9014. mPen(QPen(color)),
  9015. mBrush(Qt::NoBrush),
  9016. mPenDefined(true)
  9017. {
  9018. }
  9019. /*!
  9020. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color,
  9021. the brush color to \a fill (with a solid pattern), and size to \a size.
  9022. */
  9023. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) :
  9024. mSize(size),
  9025. mShape(shape),
  9026. mPen(QPen(color)),
  9027. mBrush(QBrush(fill)),
  9028. mPenDefined(true)
  9029. {
  9030. }
  9031. /*!
  9032. Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the
  9033. brush to \a brush, and size to \a size.
  9034. \warning In some cases it might be tempting to directly use a pen style like <tt>Qt::NoPen</tt> as \a pen
  9035. and a color like <tt>Qt::blue</tt> as \a brush. Notice however, that the corresponding call\n
  9036. <tt>QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)</tt>\n
  9037. doesn't necessarily lead C++ to use this constructor in some cases, but might mistake
  9038. <tt>Qt::NoPen</tt> for a QColor and use the
  9039. \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size)
  9040. constructor instead (which will lead to an unexpected look of the scatter points). To prevent
  9041. this, be more explicit with the parameter types. For example, use <tt>QBrush(Qt::blue)</tt>
  9042. instead of just <tt>Qt::blue</tt>, to clearly point out to the compiler that this constructor is
  9043. wanted.
  9044. */
  9045. QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) :
  9046. mSize(size),
  9047. mShape(shape),
  9048. mPen(pen),
  9049. mBrush(brush),
  9050. mPenDefined(pen.style() != Qt::NoPen)
  9051. {
  9052. }
  9053. /*!
  9054. Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape
  9055. is set to \ref ssPixmap.
  9056. */
  9057. QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) :
  9058. mSize(5),
  9059. mShape(ssPixmap),
  9060. mPen(Qt::NoPen),
  9061. mBrush(Qt::NoBrush),
  9062. mPixmap(pixmap),
  9063. mPenDefined(false)
  9064. {
  9065. }
  9066. /*!
  9067. Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The
  9068. scatter shape is set to \ref ssCustom.
  9069. The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly
  9070. different meaning than for built-in scatter points: The custom path will be drawn scaled by a
  9071. factor of \a size/6.0. Since the default \a size is 6, the custom path will appear in its
  9072. original size by default. To for example double the size of the path, set \a size to 12.
  9073. */
  9074. QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) :
  9075. mSize(size),
  9076. mShape(ssCustom),
  9077. mPen(pen),
  9078. mBrush(brush),
  9079. mCustomPath(customPath),
  9080. mPenDefined(pen.style() != Qt::NoPen)
  9081. {
  9082. }
  9083. /*!
  9084. Copies the specified \a properties from the \a other scatter style to this scatter style.
  9085. */
  9086. void QCPScatterStyle::setFromOther(const QCPScatterStyle &other, ScatterProperties properties)
  9087. {
  9088. if (properties.testFlag(spPen))
  9089. {
  9090. setPen(other.pen());
  9091. if (!other.isPenDefined())
  9092. undefinePen();
  9093. }
  9094. if (properties.testFlag(spBrush))
  9095. setBrush(other.brush());
  9096. if (properties.testFlag(spSize))
  9097. setSize(other.size());
  9098. if (properties.testFlag(spShape))
  9099. {
  9100. setShape(other.shape());
  9101. if (other.shape() == ssPixmap)
  9102. setPixmap(other.pixmap());
  9103. else if (other.shape() == ssCustom)
  9104. setCustomPath(other.customPath());
  9105. }
  9106. }
  9107. /*!
  9108. Sets the size (pixel diameter) of the drawn scatter points to \a size.
  9109. \see setShape
  9110. */
  9111. void QCPScatterStyle::setSize(double size)
  9112. {
  9113. mSize = size;
  9114. }
  9115. /*!
  9116. Sets the shape to \a shape.
  9117. Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref
  9118. ssPixmap and \ref ssCustom, respectively.
  9119. \see setSize
  9120. */
  9121. void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape)
  9122. {
  9123. mShape = shape;
  9124. }
  9125. /*!
  9126. Sets the pen that will be used to draw scatter points to \a pen.
  9127. If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after
  9128. a call to this function, even if \a pen is <tt>Qt::NoPen</tt>. If you have defined a pen
  9129. previously by calling this function and now wish to undefine the pen, call \ref undefinePen.
  9130. \see setBrush
  9131. */
  9132. void QCPScatterStyle::setPen(const QPen &pen)
  9133. {
  9134. mPenDefined = true;
  9135. mPen = pen;
  9136. }
  9137. /*!
  9138. Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter
  9139. shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does.
  9140. \see setPen
  9141. */
  9142. void QCPScatterStyle::setBrush(const QBrush &brush)
  9143. {
  9144. mBrush = brush;
  9145. }
  9146. /*!
  9147. Sets the pixmap that will be drawn as scatter point to \a pixmap.
  9148. Note that \ref setSize does not influence the appearance of the pixmap.
  9149. The scatter shape is automatically set to \ref ssPixmap.
  9150. */
  9151. void QCPScatterStyle::setPixmap(const QPixmap &pixmap)
  9152. {
  9153. setShape(ssPixmap);
  9154. mPixmap = pixmap;
  9155. }
  9156. /*!
  9157. Sets the custom shape that will be drawn as scatter point to \a customPath.
  9158. The scatter shape is automatically set to \ref ssCustom.
  9159. */
  9160. void QCPScatterStyle::setCustomPath(const QPainterPath &customPath)
  9161. {
  9162. setShape(ssCustom);
  9163. mCustomPath = customPath;
  9164. }
  9165. /*!
  9166. Sets this scatter style to have an undefined pen (see \ref isPenDefined for what an undefined pen
  9167. implies).
  9168. A call to \ref setPen will define a pen.
  9169. */
  9170. void QCPScatterStyle::undefinePen()
  9171. {
  9172. mPenDefined = false;
  9173. }
  9174. /*!
  9175. Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an
  9176. undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead.
  9177. This function is used by plottables (or any class that wants to draw scatters) just before a
  9178. number of scatters with this style shall be drawn with the \a painter.
  9179. \see drawShape
  9180. */
  9181. void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const
  9182. {
  9183. painter->setPen(mPenDefined ? mPen : defaultPen);
  9184. painter->setBrush(mBrush);
  9185. }
  9186. /*!
  9187. Draws the scatter shape with \a painter at position \a pos.
  9188. This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be
  9189. called before scatter points are drawn with \ref drawShape.
  9190. \see applyTo
  9191. */
  9192. void QCPScatterStyle::drawShape(QCPPainter *painter, const QPointF &pos) const
  9193. {
  9194. drawShape(painter, pos.x(), pos.y());
  9195. }
  9196. /*! \overload
  9197. Draws the scatter shape with \a painter at position \a x and \a y.
  9198. */
  9199. void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const
  9200. {
  9201. double w = mSize/2.0;
  9202. switch (mShape)
  9203. {
  9204. case ssNone: break;
  9205. case ssDot:
  9206. {
  9207. painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y));
  9208. break;
  9209. }
  9210. case ssCross:
  9211. {
  9212. painter->drawLine(QLineF(x-w, y-w, x+w, y+w));
  9213. painter->drawLine(QLineF(x-w, y+w, x+w, y-w));
  9214. break;
  9215. }
  9216. case ssPlus:
  9217. {
  9218. painter->drawLine(QLineF(x-w, y, x+w, y));
  9219. painter->drawLine(QLineF( x, y+w, x, y-w));
  9220. break;
  9221. }
  9222. case ssCircle:
  9223. {
  9224. painter->drawEllipse(QPointF(x , y), w, w);
  9225. break;
  9226. }
  9227. case ssDisc:
  9228. {
  9229. QBrush b = painter->brush();
  9230. painter->setBrush(painter->pen().color());
  9231. painter->drawEllipse(QPointF(x , y), w, w);
  9232. painter->setBrush(b);
  9233. break;
  9234. }
  9235. case ssSquare:
  9236. {
  9237. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  9238. break;
  9239. }
  9240. case ssDiamond:
  9241. {
  9242. QPointF lineArray[4] = {QPointF(x-w, y),
  9243. QPointF( x, y-w),
  9244. QPointF(x+w, y),
  9245. QPointF( x, y+w)};
  9246. painter->drawPolygon(lineArray, 4);
  9247. break;
  9248. }
  9249. case ssStar:
  9250. {
  9251. painter->drawLine(QLineF(x-w, y, x+w, y));
  9252. painter->drawLine(QLineF( x, y+w, x, y-w));
  9253. painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707));
  9254. painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707));
  9255. break;
  9256. }
  9257. case ssTriangle:
  9258. {
  9259. QPointF lineArray[3] = {QPointF(x-w, y+0.755*w),
  9260. QPointF(x+w, y+0.755*w),
  9261. QPointF( x, y-0.977*w)};
  9262. painter->drawPolygon(lineArray, 3);
  9263. break;
  9264. }
  9265. case ssTriangleInverted:
  9266. {
  9267. QPointF lineArray[3] = {QPointF(x-w, y-0.755*w),
  9268. QPointF(x+w, y-0.755*w),
  9269. QPointF( x, y+0.977*w)};
  9270. painter->drawPolygon(lineArray, 3);
  9271. break;
  9272. }
  9273. case ssCrossSquare:
  9274. {
  9275. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  9276. painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95));
  9277. painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w));
  9278. break;
  9279. }
  9280. case ssPlusSquare:
  9281. {
  9282. painter->drawRect(QRectF(x-w, y-w, mSize, mSize));
  9283. painter->drawLine(QLineF(x-w, y, x+w*0.95, y));
  9284. painter->drawLine(QLineF( x, y+w, x, y-w));
  9285. break;
  9286. }
  9287. case ssCrossCircle:
  9288. {
  9289. painter->drawEllipse(QPointF(x, y), w, w);
  9290. painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670));
  9291. painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707));
  9292. break;
  9293. }
  9294. case ssPlusCircle:
  9295. {
  9296. painter->drawEllipse(QPointF(x, y), w, w);
  9297. painter->drawLine(QLineF(x-w, y, x+w, y));
  9298. painter->drawLine(QLineF( x, y+w, x, y-w));
  9299. break;
  9300. }
  9301. case ssPeace:
  9302. {
  9303. painter->drawEllipse(QPointF(x, y), w, w);
  9304. painter->drawLine(QLineF(x, y-w, x, y+w));
  9305. painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707));
  9306. painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707));
  9307. break;
  9308. }
  9309. case ssPixmap:
  9310. {
  9311. const double widthHalf = mPixmap.width()*0.5;
  9312. const double heightHalf = mPixmap.height()*0.5;
  9313. #if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
  9314. const QRectF clipRect = painter->clipRegion().boundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
  9315. #else
  9316. const QRectF clipRect = painter->clipBoundingRect().adjusted(-widthHalf, -heightHalf, widthHalf, heightHalf);
  9317. #endif
  9318. if (clipRect.contains(x, y))
  9319. painter->drawPixmap(qRound(x-widthHalf), qRound(y-heightHalf), mPixmap);
  9320. break;
  9321. }
  9322. case ssCustom:
  9323. {
  9324. QTransform oldTransform = painter->transform();
  9325. painter->translate(x, y);
  9326. painter->scale(mSize/6.0, mSize/6.0);
  9327. painter->drawPath(mCustomPath);
  9328. painter->setTransform(oldTransform);
  9329. break;
  9330. }
  9331. }
  9332. }
  9333. /* end of 'src/scatterstyle.cpp' */
  9334. /* including file 'src/plottable.cpp' */
  9335. /* modified 2021-03-29T02:30:44, size 38818 */
  9336. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9337. //////////////////// QCPSelectionDecorator
  9338. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9339. /*! \class QCPSelectionDecorator
  9340. \brief Controls how a plottable's data selection is drawn
  9341. Each \ref QCPAbstractPlottable instance has one \ref QCPSelectionDecorator (accessible via \ref
  9342. QCPAbstractPlottable::selectionDecorator) and uses it when drawing selected segments of its data.
  9343. The selection decorator controls both pen (\ref setPen) and brush (\ref setBrush), as well as the
  9344. scatter style (\ref setScatterStyle) if the plottable draws scatters. Since a \ref
  9345. QCPScatterStyle is itself composed of different properties such as color shape and size, the
  9346. decorator allows specifying exactly which of those properties shall be used for the selected data
  9347. point, via \ref setUsedScatterProperties.
  9348. A \ref QCPSelectionDecorator subclass instance can be passed to a plottable via \ref
  9349. QCPAbstractPlottable::setSelectionDecorator, allowing greater customizability of the appearance
  9350. of selected segments.
  9351. Use \ref copyFrom to easily transfer the settings of one decorator to another one. This is
  9352. especially useful since plottables take ownership of the passed selection decorator, and thus the
  9353. same decorator instance can not be passed to multiple plottables.
  9354. Selection decorators can also themselves perform drawing operations by reimplementing \ref
  9355. drawDecoration, which is called by the plottable's draw method. The base class \ref
  9356. QCPSelectionDecorator does not make use of this however. For example, \ref
  9357. QCPSelectionDecoratorBracket draws brackets around selected data segments.
  9358. */
  9359. /*!
  9360. Creates a new QCPSelectionDecorator instance with default values
  9361. */
  9362. QCPSelectionDecorator::QCPSelectionDecorator() :
  9363. mPen(QColor(80, 80, 255), 2.5),
  9364. mBrush(Qt::NoBrush),
  9365. mUsedScatterProperties(QCPScatterStyle::spNone),
  9366. mPlottable(nullptr)
  9367. {
  9368. }
  9369. QCPSelectionDecorator::~QCPSelectionDecorator()
  9370. {
  9371. }
  9372. /*!
  9373. Sets the pen that will be used by the parent plottable to draw selected data segments.
  9374. */
  9375. void QCPSelectionDecorator::setPen(const QPen &pen)
  9376. {
  9377. mPen = pen;
  9378. }
  9379. /*!
  9380. Sets the brush that will be used by the parent plottable to draw selected data segments.
  9381. */
  9382. void QCPSelectionDecorator::setBrush(const QBrush &brush)
  9383. {
  9384. mBrush = brush;
  9385. }
  9386. /*!
  9387. Sets the scatter style that will be used by the parent plottable to draw scatters in selected
  9388. data segments.
  9389. \a usedProperties specifies which parts of the passed \a scatterStyle will be used by the
  9390. plottable. The used properties can also be changed via \ref setUsedScatterProperties.
  9391. */
  9392. void QCPSelectionDecorator::setScatterStyle(const QCPScatterStyle &scatterStyle, QCPScatterStyle::ScatterProperties usedProperties)
  9393. {
  9394. mScatterStyle = scatterStyle;
  9395. setUsedScatterProperties(usedProperties);
  9396. }
  9397. /*!
  9398. Use this method to define which properties of the scatter style (set via \ref setScatterStyle)
  9399. will be used for selected data segments. All properties of the scatter style that are not
  9400. specified in \a properties will remain as specified in the plottable's original scatter style.
  9401. \see QCPScatterStyle::ScatterProperty
  9402. */
  9403. void QCPSelectionDecorator::setUsedScatterProperties(const QCPScatterStyle::ScatterProperties &properties)
  9404. {
  9405. mUsedScatterProperties = properties;
  9406. }
  9407. /*!
  9408. Sets the pen of \a painter to the pen of this selection decorator.
  9409. \see applyBrush, getFinalScatterStyle
  9410. */
  9411. void QCPSelectionDecorator::applyPen(QCPPainter *painter) const
  9412. {
  9413. painter->setPen(mPen);
  9414. }
  9415. /*!
  9416. Sets the brush of \a painter to the brush of this selection decorator.
  9417. \see applyPen, getFinalScatterStyle
  9418. */
  9419. void QCPSelectionDecorator::applyBrush(QCPPainter *painter) const
  9420. {
  9421. painter->setBrush(mBrush);
  9422. }
  9423. /*!
  9424. Returns the scatter style that the parent plottable shall use for selected scatter points. The
  9425. plottable's original (unselected) scatter style must be passed as \a unselectedStyle. Depending
  9426. on the setting of \ref setUsedScatterProperties, the returned scatter style is a mixture of this
  9427. selecion decorator's scatter style (\ref setScatterStyle), and \a unselectedStyle.
  9428. \see applyPen, applyBrush, setScatterStyle
  9429. */
  9430. QCPScatterStyle QCPSelectionDecorator::getFinalScatterStyle(const QCPScatterStyle &unselectedStyle) const
  9431. {
  9432. QCPScatterStyle result(unselectedStyle);
  9433. result.setFromOther(mScatterStyle, mUsedScatterProperties);
  9434. // if style shall inherit pen from plottable (has no own pen defined), give it the selected
  9435. // plottable pen explicitly, so it doesn't use the unselected plottable pen when used in the
  9436. // plottable:
  9437. if (!result.isPenDefined())
  9438. result.setPen(mPen);
  9439. return result;
  9440. }
  9441. /*!
  9442. Copies all properties (e.g. color, fill, scatter style) of the \a other selection decorator to
  9443. this selection decorator.
  9444. */
  9445. void QCPSelectionDecorator::copyFrom(const QCPSelectionDecorator *other)
  9446. {
  9447. setPen(other->pen());
  9448. setBrush(other->brush());
  9449. setScatterStyle(other->scatterStyle(), other->usedScatterProperties());
  9450. }
  9451. /*!
  9452. This method is called by all plottables' draw methods to allow custom selection decorations to be
  9453. drawn. Use the passed \a painter to perform the drawing operations. \a selection carries the data
  9454. selection for which the decoration shall be drawn.
  9455. The default base class implementation of \ref QCPSelectionDecorator has no special decoration, so
  9456. this method does nothing.
  9457. */
  9458. void QCPSelectionDecorator::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
  9459. {
  9460. Q_UNUSED(painter)
  9461. Q_UNUSED(selection)
  9462. }
  9463. /*! \internal
  9464. This method is called as soon as a selection decorator is associated with a plottable, by a call
  9465. to \ref QCPAbstractPlottable::setSelectionDecorator. This way the selection decorator can obtain a pointer to the plottable that uses it (e.g. to access
  9466. data points via the \ref QCPAbstractPlottable::interface1D interface).
  9467. If the selection decorator was already added to a different plottable before, this method aborts
  9468. the registration and returns false.
  9469. */
  9470. bool QCPSelectionDecorator::registerWithPlottable(QCPAbstractPlottable *plottable)
  9471. {
  9472. if (!mPlottable)
  9473. {
  9474. mPlottable = plottable;
  9475. return true;
  9476. } else
  9477. {
  9478. qDebug() << Q_FUNC_INFO << "This selection decorator is already registered with plottable:" << reinterpret_cast<quintptr>(mPlottable);
  9479. return false;
  9480. }
  9481. }
  9482. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9483. //////////////////// QCPAbstractPlottable
  9484. ////////////////////////////////////////////////////////////////////////////////////////////////////
  9485. /*! \class QCPAbstractPlottable
  9486. \brief The abstract base class for all data representing objects in a plot.
  9487. It defines a very basic interface like name, pen, brush, visibility etc. Since this class is
  9488. abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to
  9489. create new ways of displaying data (see "Creating own plottables" below). Plottables that display
  9490. one-dimensional data (i.e. data points have a single key dimension and one or multiple values at
  9491. each key) are based off of the template subclass \ref QCPAbstractPlottable1D, see details
  9492. there.
  9493. All further specifics are in the subclasses, for example:
  9494. \li A normal graph with possibly a line and/or scatter points \ref QCPGraph
  9495. (typically created with \ref QCustomPlot::addGraph)
  9496. \li A parametric curve: \ref QCPCurve
  9497. \li A bar chart: \ref QCPBars
  9498. \li A statistical box plot: \ref QCPStatisticalBox
  9499. \li A color encoded two-dimensional map: \ref QCPColorMap
  9500. \li An OHLC/Candlestick chart: \ref QCPFinancial
  9501. \section plottables-subclassing Creating own plottables
  9502. Subclassing directly from QCPAbstractPlottable is only recommended if you wish to display
  9503. two-dimensional data like \ref QCPColorMap, i.e. two logical key dimensions and one (or more)
  9504. data dimensions. If you want to display data with only one logical key dimension, you should
  9505. rather derive from \ref QCPAbstractPlottable1D.
  9506. If subclassing QCPAbstractPlottable directly, these are the pure virtual functions you must
  9507. implement:
  9508. \li \ref selectTest
  9509. \li \ref draw
  9510. \li \ref drawLegendIcon
  9511. \li \ref getKeyRange
  9512. \li \ref getValueRange
  9513. See the documentation of those functions for what they need to do.
  9514. For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot
  9515. coordinates to pixel coordinates. This function is quite convenient, because it takes the
  9516. orientation of the key and value axes into account for you (x and y are swapped when the key axis
  9517. is vertical and the value axis horizontal). If you are worried about performance (i.e. you need
  9518. to translate many points in a loop like QCPGraph), you can directly use \ref
  9519. QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis
  9520. yourself.
  9521. Here are some important members you inherit from QCPAbstractPlottable:
  9522. <table>
  9523. <tr>
  9524. <td>QCustomPlot *\b mParentPlot</td>
  9525. <td>A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.</td>
  9526. </tr><tr>
  9527. <td>QString \b mName</td>
  9528. <td>The name of the plottable.</td>
  9529. </tr><tr>
  9530. <td>QPen \b mPen</td>
  9531. <td>The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable
  9532. (e.g QCPGraph uses this pen for its graph lines and scatters)</td>
  9533. </tr><tr>
  9534. <td>QBrush \b mBrush</td>
  9535. <td>The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable
  9536. (e.g. QCPGraph uses this brush to control filling under the graph)</td>
  9537. </tr><tr>
  9538. <td>QPointer<\ref QCPAxis> \b mKeyAxis, \b mValueAxis</td>
  9539. <td>The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates
  9540. 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
  9541. the axes is null, don't draw the plottable.</td>
  9542. </tr><tr>
  9543. <td>\ref QCPSelectionDecorator \b mSelectionDecorator</td>
  9544. <td>The currently set selection decorator which specifies how selected data of the plottable shall be drawn and decorated.
  9545. When drawing your data, you must consult this decorator for the appropriate pen/brush before drawing unselected/selected data segments.
  9546. Finally, you should call its \ref QCPSelectionDecorator::drawDecoration method at the end of your \ref draw implementation.</td>
  9547. </tr><tr>
  9548. <td>\ref QCP::SelectionType \b mSelectable</td>
  9549. <td>In which composition, if at all, this plottable's data may be selected. Enforcing this setting on the data selection is done
  9550. by QCPAbstractPlottable automatically.</td>
  9551. </tr><tr>
  9552. <td>\ref QCPDataSelection \b mSelection</td>
  9553. <td>Holds the current selection state of the plottable's data, i.e. the selected data ranges (\ref QCPDataRange).</td>
  9554. </tr>
  9555. </table>
  9556. */
  9557. /* start of documentation of inline functions */
  9558. /*! \fn QCPSelectionDecorator *QCPAbstractPlottable::selectionDecorator() const
  9559. Provides access to the selection decorator of this plottable. The selection decorator controls
  9560. how selected data ranges are drawn (e.g. their pen color and fill), see \ref
  9561. QCPSelectionDecorator for details.
  9562. If you wish to use an own \ref QCPSelectionDecorator subclass, pass an instance of it to \ref
  9563. setSelectionDecorator.
  9564. */
  9565. /*! \fn bool QCPAbstractPlottable::selected() const
  9566. Returns true if there are any data points of the plottable currently selected. Use \ref selection
  9567. to retrieve the current \ref QCPDataSelection.
  9568. */
  9569. /*! \fn QCPDataSelection QCPAbstractPlottable::selection() const
  9570. Returns a \ref QCPDataSelection encompassing all the data points that are currently selected on
  9571. this plottable.
  9572. \see selected, setSelection, setSelectable
  9573. */
  9574. /*! \fn virtual QCPPlottableInterface1D *QCPAbstractPlottable::interface1D()
  9575. If this plottable is a one-dimensional plottable, i.e. it implements the \ref
  9576. QCPPlottableInterface1D, returns the \a this pointer with that type. Otherwise (e.g. in the case
  9577. of a \ref QCPColorMap) returns zero.
  9578. You can use this method to gain read access to data coordinates while holding a pointer to the
  9579. abstract base class only.
  9580. */
  9581. /* end of documentation of inline functions */
  9582. /* start of documentation of pure virtual functions */
  9583. /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0
  9584. \internal
  9585. called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation
  9586. of this plottable inside \a rect, next to the plottable name.
  9587. The passed \a painter has its cliprect set to \a rect, so painting outside of \a rect won't
  9588. appear outside the legend icon border.
  9589. */
  9590. /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const = 0
  9591. Returns the coordinate range that all data in this plottable span in the key axis dimension. For
  9592. logarithmic plots, one can set \a inSignDomain to either \ref QCP::SignDomain::sdNegative or \ref
  9593. QCP::sdPositive in order to restrict the returned range to that sign domain. E.g. when only
  9594. negative range is wanted, set \a inSignDomain to \ref QCP::SignDomain::sdNegative and all positive points
  9595. will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref
  9596. QCP::SignDomain::sdBoth (default). \a foundRange is an output parameter that indicates whether a range could
  9597. be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data).
  9598. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  9599. this function may have size zero (e.g. when there is only one data point). In this case \a
  9600. foundRange would return true, but the returned range is not a valid range in terms of \ref
  9601. QCPRange::validRange.
  9602. \see rescaleAxes, getValueRange
  9603. */
  9604. /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const = 0
  9605. Returns the coordinate range that the data points in the specified key range (\a inKeyRange) span
  9606. in the value axis dimension. For logarithmic plots, one can set \a inSignDomain to either \ref
  9607. QCP::SignDomain::sdNegative or \ref QCP::sdPositive in order to restrict the returned range to that sign
  9608. domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref QCP::SignDomain::sdNegative and
  9609. all positive points will be ignored for range calculation. For no restriction, just set \a
  9610. inSignDomain to \ref QCP::SignDomain::sdBoth (default). \a foundRange is an output parameter that indicates
  9611. whether a range could be found or not. If this is false, you shouldn't use the returned range
  9612. (e.g. no points in data).
  9613. If \a inKeyRange has both lower and upper bound set to zero (is equal to <tt>QCPRange()</tt>),
  9614. all data points are considered, without any restriction on the keys.
  9615. Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by
  9616. this function may have size zero (e.g. when there is only one data point). In this case \a
  9617. foundRange would return true, but the returned range is not a valid range in terms of \ref
  9618. QCPRange::validRange.
  9619. \see rescaleAxes, getKeyRange
  9620. */
  9621. /* end of documentation of pure virtual functions */
  9622. /* start of documentation of signals */
  9623. /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected)
  9624. This signal is emitted when the selection state of this plottable has changed, either by user
  9625. interaction or by a direct call to \ref setSelection. The parameter \a selected indicates whether
  9626. there are any points selected or not.
  9627. \see selectionChanged(const QCPDataSelection &selection)
  9628. */
  9629. /*! \fn void QCPAbstractPlottable::selectionChanged(const QCPDataSelection &selection)
  9630. This signal is emitted when the selection state of this plottable has changed, either by user
  9631. interaction or by a direct call to \ref setSelection. The parameter \a selection holds the
  9632. currently selected data ranges.
  9633. \see selectionChanged(bool selected)
  9634. */
  9635. /*! \fn void QCPAbstractPlottable::selectableChanged(QCP::SelectionType selectable);
  9636. This signal is emitted when the selectability of this plottable has changed.
  9637. \see setSelectable
  9638. */
  9639. /* end of documentation of signals */
  9640. /*!
  9641. Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as
  9642. its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance
  9643. and have perpendicular orientations. If either of these restrictions is violated, a corresponding
  9644. message is printed to the debug output (qDebug), the construction is not aborted, though.
  9645. Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables,
  9646. it can't be directly instantiated.
  9647. You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead.
  9648. */
  9649. QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  9650. QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis->axisRect()),
  9651. mName(),
  9652. mAntialiasedFill(true),
  9653. mAntialiasedScatters(true),
  9654. mPen(Qt::black),
  9655. mBrush(Qt::NoBrush),
  9656. mKeyAxis(keyAxis),
  9657. mValueAxis(valueAxis),
  9658. mSelectable(QCP::stWhole),
  9659. mSelectionDecorator(nullptr)
  9660. {
  9661. if (keyAxis->parentPlot() != valueAxis->parentPlot())
  9662. qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
  9663. if (keyAxis->orientation() == valueAxis->orientation())
  9664. qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other.";
  9665. mParentPlot->registerPlottable(this);
  9666. setSelectionDecorator(new QCPSelectionDecorator);
  9667. }
  9668. QCPAbstractPlottable::~QCPAbstractPlottable()
  9669. {
  9670. if (mSelectionDecorator)
  9671. {
  9672. delete mSelectionDecorator;
  9673. mSelectionDecorator = nullptr;
  9674. }
  9675. }
  9676. /*!
  9677. The name is the textual representation of this plottable as it is displayed in the legend
  9678. (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
  9679. */
  9680. void QCPAbstractPlottable::setName(const QString &name)
  9681. {
  9682. mName = name;
  9683. }
  9684. /*!
  9685. Sets whether fills of this plottable are drawn antialiased or not.
  9686. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  9687. QCustomPlot::setNotAntialiasedElements.
  9688. */
  9689. void QCPAbstractPlottable::setAntialiasedFill(bool enabled)
  9690. {
  9691. mAntialiasedFill = enabled;
  9692. }
  9693. /*!
  9694. Sets whether the scatter symbols of this plottable are drawn antialiased or not.
  9695. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  9696. QCustomPlot::setNotAntialiasedElements.
  9697. */
  9698. void QCPAbstractPlottable::setAntialiasedScatters(bool enabled)
  9699. {
  9700. mAntialiasedScatters = enabled;
  9701. }
  9702. /*!
  9703. The pen is used to draw basic lines that make up the plottable representation in the
  9704. plot.
  9705. For example, the \ref QCPGraph subclass draws its graph lines with this pen.
  9706. \see setBrush
  9707. */
  9708. void QCPAbstractPlottable::setPen(const QPen &pen)
  9709. {
  9710. mPen = pen;
  9711. }
  9712. /*!
  9713. The brush is used to draw basic fills of the plottable representation in the
  9714. plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
  9715. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
  9716. it's not set to Qt::NoBrush.
  9717. \see setPen
  9718. */
  9719. void QCPAbstractPlottable::setBrush(const QBrush &brush)
  9720. {
  9721. mBrush = brush;
  9722. }
  9723. /*!
  9724. The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
  9725. to the plottable's value axis. This function performs no checks to make sure this is the case.
  9726. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
  9727. y-axis (QCustomPlot::yAxis) as value axis.
  9728. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  9729. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  9730. \see setValueAxis
  9731. */
  9732. void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis)
  9733. {
  9734. mKeyAxis = axis;
  9735. }
  9736. /*!
  9737. The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
  9738. orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
  9739. case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
  9740. the y-axis (QCustomPlot::yAxis) as value axis.
  9741. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  9742. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  9743. \see setKeyAxis
  9744. */
  9745. void QCPAbstractPlottable::setValueAxis(QCPAxis *axis)
  9746. {
  9747. mValueAxis = axis;
  9748. }
  9749. /*!
  9750. Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
  9751. (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
  9752. selectionDecorator).
  9753. The entire selection mechanism for plottables is handled automatically when \ref
  9754. QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
  9755. you wish to change the selection state programmatically.
  9756. Using \ref setSelectable you can further specify for each plottable whether and to which
  9757. granularity it is selectable. If \a selection is not compatible with the current \ref
  9758. QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
  9759. accordingly (see \ref QCPDataSelection::enforceType).
  9760. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  9761. \see setSelectable, selectTest
  9762. */
  9763. void QCPAbstractPlottable::setSelection(QCPDataSelection selection)
  9764. {
  9765. selection.enforceType(mSelectable);
  9766. if (mSelection != selection)
  9767. {
  9768. mSelection = selection;
  9769. emit selectionChanged(selected());
  9770. emit selectionChanged(mSelection);
  9771. }
  9772. }
  9773. /*!
  9774. Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
  9775. customize the visual representation of selected data ranges further than by using the default
  9776. QCPSelectionDecorator.
  9777. The plottable takes ownership of the \a decorator.
  9778. The currently set decorator can be accessed via \ref selectionDecorator.
  9779. */
  9780. void QCPAbstractPlottable::setSelectionDecorator(QCPSelectionDecorator *decorator)
  9781. {
  9782. if (decorator)
  9783. {
  9784. if (decorator->registerWithPlottable(this))
  9785. {
  9786. delete mSelectionDecorator; // delete old decorator if necessary
  9787. mSelectionDecorator = decorator;
  9788. }
  9789. } else if (mSelectionDecorator) // just clear decorator
  9790. {
  9791. delete mSelectionDecorator;
  9792. mSelectionDecorator = nullptr;
  9793. }
  9794. }
  9795. /*!
  9796. Sets whether and to which granularity this plottable can be selected.
  9797. A selection can happen by clicking on the QCustomPlot surface (When \ref
  9798. QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
  9799. (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
  9800. calling \ref setSelection.
  9801. \see setSelection, QCP::SelectionType
  9802. */
  9803. void QCPAbstractPlottable::setSelectable(QCP::SelectionType selectable)
  9804. {
  9805. if (mSelectable != selectable)
  9806. {
  9807. mSelectable = selectable;
  9808. QCPDataSelection oldSelection = mSelection;
  9809. mSelection.enforceType(mSelectable);
  9810. emit selectableChanged(mSelectable);
  9811. if (mSelection != oldSelection)
  9812. {
  9813. emit selectionChanged(selected());
  9814. emit selectionChanged(mSelection);
  9815. }
  9816. }
  9817. }
  9818. /*!
  9819. Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface,
  9820. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  9821. represents x or y).
  9822. \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y.
  9823. \see pixelsToCoords, QCPAxis::coordToPixel
  9824. */
  9825. void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const
  9826. {
  9827. QCPAxis *keyAxis = mKeyAxis.data();
  9828. QCPAxis *valueAxis = mValueAxis.data();
  9829. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  9830. if (keyAxis->orientation() == Qt::Horizontal)
  9831. {
  9832. x = keyAxis->coordToPixel(key);
  9833. y = valueAxis->coordToPixel(value);
  9834. } else
  9835. {
  9836. y = keyAxis->coordToPixel(key);
  9837. x = valueAxis->coordToPixel(value);
  9838. }
  9839. }
  9840. /*! \overload
  9841. Transforms the given \a key and \a value to pixel coordinates and returns them in a QPointF.
  9842. */
  9843. const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const
  9844. {
  9845. QCPAxis *keyAxis = mKeyAxis.data();
  9846. QCPAxis *valueAxis = mValueAxis.data();
  9847. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); }
  9848. if (keyAxis->orientation() == Qt::Horizontal)
  9849. return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value));
  9850. else
  9851. return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key));
  9852. }
  9853. /*!
  9854. Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates,
  9855. taking the orientations of the axes associated with this plottable into account (e.g. whether key
  9856. represents x or y).
  9857. \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value.
  9858. \see coordsToPixels, QCPAxis::coordToPixel
  9859. */
  9860. void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const
  9861. {
  9862. QCPAxis *keyAxis = mKeyAxis.data();
  9863. QCPAxis *valueAxis = mValueAxis.data();
  9864. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  9865. if (keyAxis->orientation() == Qt::Horizontal)
  9866. {
  9867. key = keyAxis->pixelToCoord(x);
  9868. value = valueAxis->pixelToCoord(y);
  9869. } else
  9870. {
  9871. key = keyAxis->pixelToCoord(y);
  9872. value = valueAxis->pixelToCoord(x);
  9873. }
  9874. }
  9875. /*! \overload
  9876. Returns the pixel input \a pixelPos as plot coordinates \a key and \a value.
  9877. */
  9878. void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
  9879. {
  9880. pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value);
  9881. }
  9882. /*!
  9883. Rescales the key and value axes associated with this plottable to contain all displayed data, so
  9884. the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make
  9885. sure not to rescale to an illegal range i.e. a range containing different signs and/or zero.
  9886. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie
  9887. outside of that domain.
  9888. \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show
  9889. multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has
  9890. \a onlyEnlarge set to false (the default), and all subsequent set to true.
  9891. \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale
  9892. */
  9893. void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const
  9894. {
  9895. rescaleKeyAxis(onlyEnlarge);
  9896. rescaleValueAxis(onlyEnlarge);
  9897. }
  9898. /*!
  9899. Rescales the key axis of the plottable so the whole plottable is visible.
  9900. See \ref rescaleAxes for detailed behaviour.
  9901. */
  9902. void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const
  9903. {
  9904. QCPAxis *keyAxis = mKeyAxis.data();
  9905. if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  9906. QCP::SignDomain signDomain = QCP::SignDomain::sdBoth;
  9907. if (keyAxis->scaleType() == QCPAxis::ScaleType::stLogarithmic)
  9908. signDomain = (keyAxis->range().upper < 0 ? QCP::SignDomain::sdNegative : QCP::SignDomain::sdPositive);
  9909. bool foundRange;
  9910. QCPRange newRange = getKeyRange(foundRange, signDomain);
  9911. if (foundRange)
  9912. {
  9913. if (onlyEnlarge)
  9914. newRange.expand(keyAxis->range());
  9915. 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
  9916. {
  9917. 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
  9918. if (keyAxis->scaleType() == QCPAxis::ScaleType::stLinear)
  9919. {
  9920. newRange.lower = center-keyAxis->range().size()/2.0;
  9921. newRange.upper = center+keyAxis->range().size()/2.0;
  9922. } else // scaleType() == stLogarithmic
  9923. {
  9924. newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower);
  9925. newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower);
  9926. }
  9927. }
  9928. keyAxis->setRange(newRange);
  9929. }
  9930. }
  9931. /*!
  9932. Rescales the value axis of the plottable so the whole plottable is visible. If \a inKeyRange is
  9933. set to true, only the data points which are in the currently visible key axis range are
  9934. considered.
  9935. Returns true if the axis was actually scaled. This might not be the case if this plottable has an
  9936. invalid range, e.g. because it has no data points.
  9937. See \ref rescaleAxes for detailed behaviour.
  9938. */
  9939. void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
  9940. {
  9941. QCPAxis *keyAxis = mKeyAxis.data();
  9942. QCPAxis *valueAxis = mValueAxis.data();
  9943. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  9944. QCP::SignDomain signDomain = QCP::SignDomain::sdBoth;
  9945. if (valueAxis->scaleType() == QCPAxis::ScaleType::stLogarithmic)
  9946. signDomain = (valueAxis->range().upper < 0 ? QCP::SignDomain::sdNegative : QCP::SignDomain::sdPositive);
  9947. bool foundRange;
  9948. QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
  9949. if (foundRange)
  9950. {
  9951. if (onlyEnlarge)
  9952. newRange.expand(valueAxis->range());
  9953. 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
  9954. {
  9955. 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
  9956. if (valueAxis->scaleType() == QCPAxis::ScaleType::stLinear)
  9957. {
  9958. newRange.lower = center-valueAxis->range().size()/2.0;
  9959. newRange.upper = center+valueAxis->range().size()/2.0;
  9960. } else // scaleType() == stLogarithmic
  9961. {
  9962. newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  9963. newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  9964. }
  9965. }
  9966. valueAxis->setRange(newRange);
  9967. }
  9968. }
  9969. /*! \overload
  9970. Adds this plottable to the specified \a legend.
  9971. Creates a QCPPlottableLegendItem which is inserted into the legend. Returns true on success, i.e.
  9972. when the legend exists and a legend item associated with this plottable isn't already in the
  9973. legend.
  9974. If the plottable needs a more specialized representation in the legend, you can create a
  9975. corresponding subclass of \ref QCPPlottableLegendItem and add it to the legend manually instead
  9976. of calling this method.
  9977. \see removeFromLegend, QCPLegend::addItem
  9978. */
  9979. bool QCPAbstractPlottable::addToLegend(QCPLegend *legend)
  9980. {
  9981. if (!legend)
  9982. {
  9983. qDebug() << Q_FUNC_INFO << "passed legend is null";
  9984. return false;
  9985. }
  9986. if (legend->parentPlot() != mParentPlot)
  9987. {
  9988. qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
  9989. return false;
  9990. }
  9991. if (!legend->hasItemWithPlottable(this))
  9992. {
  9993. legend->addItem(new QCPPlottableLegendItem(legend, this));
  9994. return true;
  9995. } else
  9996. return false;
  9997. }
  9998. /*! \overload
  9999. Adds this plottable to the legend of the parent QCustomPlot (\ref QCustomPlot::legend).
  10000. \see removeFromLegend
  10001. */
  10002. bool QCPAbstractPlottable::addToLegend()
  10003. {
  10004. if (!mParentPlot || !mParentPlot->legend)
  10005. return false;
  10006. else
  10007. return addToLegend(mParentPlot->legend);
  10008. }
  10009. /*! \overload
  10010. Removes the plottable from the specifed \a legend. This means the \ref QCPPlottableLegendItem
  10011. that is associated with this plottable is removed.
  10012. Returns true on success, i.e. if the legend exists and a legend item associated with this
  10013. plottable was found and removed.
  10014. \see addToLegend, QCPLegend::removeItem
  10015. */
  10016. bool QCPAbstractPlottable::removeFromLegend(QCPLegend *legend) const
  10017. {
  10018. if (!legend)
  10019. {
  10020. qDebug() << Q_FUNC_INFO << "passed legend is null";
  10021. return false;
  10022. }
  10023. if (QCPPlottableLegendItem *lip = legend->itemWithPlottable(this))
  10024. return legend->removeItem(lip);
  10025. else
  10026. return false;
  10027. }
  10028. /*! \overload
  10029. Removes the plottable from the legend of the parent QCustomPlot.
  10030. \see addToLegend
  10031. */
  10032. bool QCPAbstractPlottable::removeFromLegend() const
  10033. {
  10034. if (!mParentPlot || !mParentPlot->legend)
  10035. return false;
  10036. else
  10037. return removeFromLegend(mParentPlot->legend);
  10038. }
  10039. /* inherits documentation from base class */
  10040. QRect QCPAbstractPlottable::clipRect() const
  10041. {
  10042. if (mKeyAxis && mValueAxis)
  10043. return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect();
  10044. else
  10045. return {};
  10046. }
  10047. /* inherits documentation from base class */
  10048. QCP::Interaction QCPAbstractPlottable::selectionCategory() const
  10049. {
  10050. return QCP::iSelectPlottables;
  10051. }
  10052. /*! \internal
  10053. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  10054. before drawing plottable lines.
  10055. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  10056. This function takes into account the local setting of the antialiasing flag as well as the
  10057. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  10058. QCustomPlot::setNotAntialiasedElements.
  10059. \seebaseclassmethod
  10060. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint
  10061. */
  10062. void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const
  10063. {
  10064. applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
  10065. }
  10066. /*! \internal
  10067. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  10068. before drawing plottable fills.
  10069. This function takes into account the local setting of the antialiasing flag as well as the
  10070. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  10071. QCustomPlot::setNotAntialiasedElements.
  10072. \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint
  10073. */
  10074. void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const
  10075. {
  10076. applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
  10077. }
  10078. /*! \internal
  10079. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  10080. before drawing plottable scatter points.
  10081. This function takes into account the local setting of the antialiasing flag as well as the
  10082. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  10083. QCustomPlot::setNotAntialiasedElements.
  10084. \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint
  10085. */
  10086. void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const
  10087. {
  10088. applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
  10089. }
  10090. /* inherits documentation from base class */
  10091. void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  10092. {
  10093. Q_UNUSED(event)
  10094. if (mSelectable != QCP::stNone)
  10095. {
  10096. QCPDataSelection newSelection = details.value<QCPDataSelection>();
  10097. QCPDataSelection selectionBefore = mSelection;
  10098. if (additive)
  10099. {
  10100. if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
  10101. {
  10102. if (selected())
  10103. setSelection(QCPDataSelection());
  10104. else
  10105. setSelection(newSelection);
  10106. } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
  10107. {
  10108. if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
  10109. setSelection(mSelection-newSelection);
  10110. else
  10111. setSelection(mSelection+newSelection);
  10112. }
  10113. } else
  10114. setSelection(newSelection);
  10115. if (selectionStateChanged)
  10116. *selectionStateChanged = mSelection != selectionBefore;
  10117. }
  10118. }
  10119. /* inherits documentation from base class */
  10120. void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged)
  10121. {
  10122. if (mSelectable != QCP::stNone)
  10123. {
  10124. QCPDataSelection selectionBefore = mSelection;
  10125. setSelection(QCPDataSelection());
  10126. if (selectionStateChanged)
  10127. *selectionStateChanged = mSelection != selectionBefore;
  10128. }
  10129. }
  10130. /* end of 'src/plottable.cpp' */
  10131. /* including file 'src/item.cpp' */
  10132. /* modified 2021-03-29T02:30:44, size 49486 */
  10133. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10134. //////////////////// QCPItemAnchor
  10135. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10136. /*! \class QCPItemAnchor
  10137. \brief An anchor of an item to which positions can be attached to.
  10138. An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't
  10139. control anything on its item, but provides a way to tie other items via their positions to the
  10140. anchor.
  10141. For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight.
  10142. Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can
  10143. attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by
  10144. calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the
  10145. QCPItemRect. This way the start of the line will now always follow the respective anchor location
  10146. on the rect item.
  10147. Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an
  10148. anchor to other positions.
  10149. To learn how to provide anchors in your own item subclasses, see the subclassing section of the
  10150. QCPAbstractItem documentation.
  10151. */
  10152. /* start documentation of inline functions */
  10153. /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition()
  10154. Returns \c nullptr if this instance is merely a QCPItemAnchor, and a valid pointer of type
  10155. QCPItemPosition* if it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor).
  10156. This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids
  10157. dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with
  10158. gcc compiler).
  10159. */
  10160. /* end documentation of inline functions */
  10161. /*!
  10162. Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if
  10163. you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as
  10164. explained in the subclassing section of the QCPAbstractItem documentation.
  10165. */
  10166. QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name, int anchorId) :
  10167. mName(name),
  10168. mParentPlot(parentPlot),
  10169. mParentItem(parentItem),
  10170. mAnchorId(anchorId)
  10171. {
  10172. }
  10173. QCPItemAnchor::~QCPItemAnchor()
  10174. {
  10175. // unregister as parent at children:
  10176. foreach (QCPItemPosition *child, mChildrenX.values())
  10177. {
  10178. if (child->parentAnchorX() == this)
  10179. child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX
  10180. }
  10181. foreach (QCPItemPosition *child, mChildrenY.values())
  10182. {
  10183. if (child->parentAnchorY() == this)
  10184. child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY
  10185. }
  10186. }
  10187. /*!
  10188. Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface.
  10189. The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the
  10190. parent item, QCPItemAnchor is just an intermediary.
  10191. */
  10192. QPointF QCPItemAnchor::pixelPosition() const
  10193. {
  10194. if (mParentItem)
  10195. {
  10196. if (mAnchorId > -1)
  10197. {
  10198. return mParentItem->anchorPixelPosition(mAnchorId);
  10199. } else
  10200. {
  10201. qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId;
  10202. return {};
  10203. }
  10204. } else
  10205. {
  10206. qDebug() << Q_FUNC_INFO << "no parent item set";
  10207. return {};
  10208. }
  10209. }
  10210. /*! \internal
  10211. Adds \a pos to the childX list of this anchor, which keeps track of which children use this
  10212. anchor as parent anchor for the respective coordinate. This is necessary to notify the children
  10213. prior to destruction of the anchor.
  10214. Note that this function does not change the parent setting in \a pos.
  10215. */
  10216. void QCPItemAnchor::addChildX(QCPItemPosition *pos)
  10217. {
  10218. if (!mChildrenX.contains(pos))
  10219. mChildrenX.insert(pos);
  10220. else
  10221. qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
  10222. }
  10223. /*! \internal
  10224. Removes \a pos from the childX list of this anchor.
  10225. Note that this function does not change the parent setting in \a pos.
  10226. */
  10227. void QCPItemAnchor::removeChildX(QCPItemPosition *pos)
  10228. {
  10229. if (!mChildrenX.remove(pos))
  10230. qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
  10231. }
  10232. /*! \internal
  10233. Adds \a pos to the childY list of this anchor, which keeps track of which children use this
  10234. anchor as parent anchor for the respective coordinate. This is necessary to notify the children
  10235. prior to destruction of the anchor.
  10236. Note that this function does not change the parent setting in \a pos.
  10237. */
  10238. void QCPItemAnchor::addChildY(QCPItemPosition *pos)
  10239. {
  10240. if (!mChildrenY.contains(pos))
  10241. mChildrenY.insert(pos);
  10242. else
  10243. qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast<quintptr>(pos);
  10244. }
  10245. /*! \internal
  10246. Removes \a pos from the childY list of this anchor.
  10247. Note that this function does not change the parent setting in \a pos.
  10248. */
  10249. void QCPItemAnchor::removeChildY(QCPItemPosition *pos)
  10250. {
  10251. if (!mChildrenY.remove(pos))
  10252. qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast<quintptr>(pos);
  10253. }
  10254. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10255. //////////////////// QCPItemPosition
  10256. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10257. /*! \class QCPItemPosition
  10258. \brief Manages the position of an item.
  10259. Every item has at least one public QCPItemPosition member pointer which provides ways to position the
  10260. item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two:
  10261. \a topLeft and \a bottomRight.
  10262. QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type
  10263. defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel
  10264. coordinates, as plot coordinates of certain axes (\ref QCPItemPosition::setAxes), as fractions of
  10265. the axis rect (\ref QCPItemPosition::setAxisRect), etc. For more advanced plots it is also
  10266. possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref
  10267. setTypeY). This way an item could be positioned for example at a fixed pixel distance from the
  10268. top in the Y direction, while following a plot coordinate in the X direction.
  10269. A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie
  10270. multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords)
  10271. are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0)
  10272. means directly ontop of the parent anchor. For example, You could attach the \a start position of
  10273. a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line
  10274. always be centered under the text label, no matter where the text is moved to. For more advanced
  10275. plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see
  10276. \ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X
  10277. direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B
  10278. in Y.
  10279. Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent
  10280. anchor for other positions.
  10281. To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPosition. This
  10282. works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref
  10283. setPixelPosition transforms the coordinates appropriately, to make the position appear at the specified
  10284. pixel values.
  10285. */
  10286. /* start documentation of inline functions */
  10287. /*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const
  10288. Returns the current position type.
  10289. If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the
  10290. type of the X coordinate. In that case rather use \a typeX() and \a typeY().
  10291. \see setType
  10292. */
  10293. /*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const
  10294. Returns the current parent anchor.
  10295. If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY),
  10296. this method returns the parent anchor of the Y coordinate. In that case rather use \a
  10297. parentAnchorX() and \a parentAnchorY().
  10298. \see setParentAnchor
  10299. */
  10300. /* end documentation of inline functions */
  10301. /*!
  10302. Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if
  10303. you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as
  10304. explained in the subclassing section of the QCPAbstractItem documentation.
  10305. */
  10306. QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString &name) :
  10307. QCPItemAnchor(parentPlot, parentItem, name),
  10308. mPositionTypeX(QCPItemPosition::PositionType::ptAbsolute),
  10309. mPositionTypeY(QCPItemPosition::PositionType::ptAbsolute),
  10310. mKey(0),
  10311. mValue(0),
  10312. mParentAnchorX(nullptr),
  10313. mParentAnchorY(nullptr)
  10314. {
  10315. }
  10316. QCPItemPosition::~QCPItemPosition()
  10317. {
  10318. // unregister as parent at children:
  10319. // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then
  10320. // the setParentAnchor(0) call the correct QCPItemPosition::pixelPosition function instead of QCPItemAnchor::pixelPosition
  10321. foreach (QCPItemPosition *child, mChildrenX.values())
  10322. {
  10323. if (child->parentAnchorX() == this)
  10324. child->setParentAnchorX(nullptr); // this acts back on this anchor and child removes itself from mChildrenX
  10325. }
  10326. foreach (QCPItemPosition *child, mChildrenY.values())
  10327. {
  10328. if (child->parentAnchorY() == this)
  10329. child->setParentAnchorY(nullptr); // this acts back on this anchor and child removes itself from mChildrenY
  10330. }
  10331. // unregister as child in parent:
  10332. if (mParentAnchorX)
  10333. mParentAnchorX->removeChildX(this);
  10334. if (mParentAnchorY)
  10335. mParentAnchorY->removeChildY(this);
  10336. }
  10337. /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
  10338. QCPAxisRect *QCPItemPosition::axisRect() const
  10339. {
  10340. return mAxisRect.data();
  10341. }
  10342. /*!
  10343. Sets the type of the position. The type defines how the coordinates passed to \ref setCoords
  10344. should be handled and how the QCPItemPosition should behave in the plot.
  10345. The possible values for \a type can be separated in two main categories:
  10346. \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords
  10347. and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes.
  10348. By default, the QCustomPlot's x- and yAxis are used.
  10349. \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This
  10350. corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref
  10351. ptAxisRectRatio. They differ only in the way the absolute position is described, see the
  10352. documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify
  10353. the axis rect with \ref setAxisRect. By default this is set to the main axis rect.
  10354. Note that the position type \ref ptPlotCoords is only available (and sensible) when the position
  10355. has no parent anchor (\ref setParentAnchor).
  10356. If the type is changed, the apparent pixel position on the plot is preserved. This means
  10357. the coordinates as retrieved with coords() and set with \ref setCoords may change in the process.
  10358. This method sets the type for both X and Y directions. It is also possible to set different types
  10359. for X and Y, see \ref setTypeX, \ref setTypeY.
  10360. */
  10361. void QCPItemPosition::setType(QCPItemPosition::PositionType type)
  10362. {
  10363. setTypeX(type);
  10364. setTypeY(type);
  10365. }
  10366. /*!
  10367. This method sets the position type of the X coordinate to \a type.
  10368. For a detailed description of what a position type is, see the documentation of \ref setType.
  10369. \see setType, setTypeY
  10370. */
  10371. void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type)
  10372. {
  10373. if (mPositionTypeX != type)
  10374. {
  10375. // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
  10376. // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
  10377. bool retainPixelPosition = true;
  10378. if ((mPositionTypeX == QCPItemPosition::PositionType::ptPlotCoords || type == QCPItemPosition::PositionType::ptPlotCoords) && (!mKeyAxis || !mValueAxis))
  10379. retainPixelPosition = false;
  10380. if ((mPositionTypeX == QCPItemPosition::PositionType::ptAxisRectRatio || type == QCPItemPosition::PositionType::ptAxisRectRatio) && (!mAxisRect))
  10381. retainPixelPosition = false;
  10382. QPointF pixel;
  10383. if (retainPixelPosition)
  10384. pixel = pixelPosition();
  10385. mPositionTypeX = type;
  10386. if (retainPixelPosition)
  10387. setPixelPosition(pixel);
  10388. }
  10389. }
  10390. /*!
  10391. This method sets the position type of the Y coordinate to \a type.
  10392. For a detailed description of what a position type is, see the documentation of \ref setType.
  10393. \see setType, setTypeX
  10394. */
  10395. void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type)
  10396. {
  10397. if (mPositionTypeY != type)
  10398. {
  10399. // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect
  10400. // were deleted), don't try to recover the pixelPosition() because it would output a qDebug warning.
  10401. bool retainPixelPosition = true;
  10402. if ((mPositionTypeY == QCPItemPosition::PositionType::ptPlotCoords || type == QCPItemPosition::PositionType::ptPlotCoords) && (!mKeyAxis || !mValueAxis))
  10403. retainPixelPosition = false;
  10404. if ((mPositionTypeY == QCPItemPosition::PositionType::ptAxisRectRatio || type == QCPItemPosition::PositionType::ptAxisRectRatio) && (!mAxisRect))
  10405. retainPixelPosition = false;
  10406. QPointF pixel;
  10407. if (retainPixelPosition)
  10408. pixel = pixelPosition();
  10409. mPositionTypeY = type;
  10410. if (retainPixelPosition)
  10411. setPixelPosition(pixel);
  10412. }
  10413. }
  10414. /*!
  10415. Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now
  10416. follow any position changes of the anchor. The local coordinate system of positions with a parent
  10417. anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence
  10418. the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.)
  10419. if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved
  10420. during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position
  10421. will be exactly on top of the parent anchor.
  10422. To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to \c nullptr.
  10423. If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is
  10424. set to \ref ptAbsolute, to keep the position in a valid state.
  10425. This method sets the parent anchor for both X and Y directions. It is also possible to set
  10426. different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY.
  10427. */
  10428. bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  10429. {
  10430. bool successX = setParentAnchorX(parentAnchor, keepPixelPosition);
  10431. bool successY = setParentAnchorY(parentAnchor, keepPixelPosition);
  10432. return successX && successY;
  10433. }
  10434. /*!
  10435. This method sets the parent anchor of the X coordinate to \a parentAnchor.
  10436. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
  10437. \see setParentAnchor, setParentAnchorY
  10438. */
  10439. bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  10440. {
  10441. // make sure self is not assigned as parent:
  10442. if (parentAnchor == this)
  10443. {
  10444. qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
  10445. return false;
  10446. }
  10447. // make sure no recursive parent-child-relationships are created:
  10448. QCPItemAnchor *currentParent = parentAnchor;
  10449. while (currentParent)
  10450. {
  10451. if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
  10452. {
  10453. // is a QCPItemPosition, might have further parent, so keep iterating
  10454. if (currentParentPos == this)
  10455. {
  10456. qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
  10457. return false;
  10458. }
  10459. currentParent = currentParentPos->parentAnchorX();
  10460. } else
  10461. {
  10462. // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
  10463. // same, to prevent a position being child of an anchor which itself depends on the position,
  10464. // because they're both on the same item:
  10465. if (currentParent->mParentItem == mParentItem)
  10466. {
  10467. qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
  10468. return false;
  10469. }
  10470. break;
  10471. }
  10472. }
  10473. // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
  10474. if (!mParentAnchorX && mPositionTypeX == QCPItemPosition::PositionType::ptPlotCoords)
  10475. setTypeX(QCPItemPosition::PositionType::ptAbsolute);
  10476. // save pixel position:
  10477. QPointF pixelP;
  10478. if (keepPixelPosition)
  10479. pixelP = pixelPosition();
  10480. // unregister at current parent anchor:
  10481. if (mParentAnchorX)
  10482. mParentAnchorX->removeChildX(this);
  10483. // register at new parent anchor:
  10484. if (parentAnchor)
  10485. parentAnchor->addChildX(this);
  10486. mParentAnchorX = parentAnchor;
  10487. // restore pixel position under new parent:
  10488. if (keepPixelPosition)
  10489. setPixelPosition(pixelP);
  10490. else
  10491. setCoords(0, coords().y());
  10492. return true;
  10493. }
  10494. /*!
  10495. This method sets the parent anchor of the Y coordinate to \a parentAnchor.
  10496. For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor.
  10497. \see setParentAnchor, setParentAnchorX
  10498. */
  10499. bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition)
  10500. {
  10501. // make sure self is not assigned as parent:
  10502. if (parentAnchor == this)
  10503. {
  10504. qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast<quintptr>(parentAnchor);
  10505. return false;
  10506. }
  10507. // make sure no recursive parent-child-relationships are created:
  10508. QCPItemAnchor *currentParent = parentAnchor;
  10509. while (currentParent)
  10510. {
  10511. if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition())
  10512. {
  10513. // is a QCPItemPosition, might have further parent, so keep iterating
  10514. if (currentParentPos == this)
  10515. {
  10516. qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast<quintptr>(parentAnchor);
  10517. return false;
  10518. }
  10519. currentParent = currentParentPos->parentAnchorY();
  10520. } else
  10521. {
  10522. // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the
  10523. // same, to prevent a position being child of an anchor which itself depends on the position,
  10524. // because they're both on the same item:
  10525. if (currentParent->mParentItem == mParentItem)
  10526. {
  10527. qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast<quintptr>(parentAnchor);
  10528. return false;
  10529. }
  10530. break;
  10531. }
  10532. }
  10533. // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute:
  10534. if (!mParentAnchorY && mPositionTypeY == QCPItemPosition::PositionType::ptPlotCoords)
  10535. setTypeY(QCPItemPosition::PositionType::ptAbsolute);
  10536. // save pixel position:
  10537. QPointF pixelP;
  10538. if (keepPixelPosition)
  10539. pixelP = pixelPosition();
  10540. // unregister at current parent anchor:
  10541. if (mParentAnchorY)
  10542. mParentAnchorY->removeChildY(this);
  10543. // register at new parent anchor:
  10544. if (parentAnchor)
  10545. parentAnchor->addChildY(this);
  10546. mParentAnchorY = parentAnchor;
  10547. // restore pixel position under new parent:
  10548. if (keepPixelPosition)
  10549. setPixelPosition(pixelP);
  10550. else
  10551. setCoords(coords().x(), 0);
  10552. return true;
  10553. }
  10554. /*!
  10555. Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type
  10556. (\ref setType, \ref setTypeX, \ref setTypeY).
  10557. For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position
  10558. on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the
  10559. QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the
  10560. plot coordinate system defined by the axes set by \ref setAxes. By default those are the
  10561. QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available
  10562. coordinate types and their meaning.
  10563. If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a
  10564. value must also be provided in the different coordinate systems. Here, the X type refers to \a
  10565. key, and the Y type refers to \a value.
  10566. \see setPixelPosition
  10567. */
  10568. void QCPItemPosition::setCoords(double key, double value)
  10569. {
  10570. mKey = key;
  10571. mValue = value;
  10572. }
  10573. /*! \overload
  10574. Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the
  10575. meaning of \a value of the \ref setCoords(double key, double value) method.
  10576. */
  10577. void QCPItemPosition::setCoords(const QPointF &pos)
  10578. {
  10579. setCoords(pos.x(), pos.y());
  10580. }
  10581. /*!
  10582. Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It
  10583. includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor).
  10584. \see setPixelPosition
  10585. */
  10586. QPointF QCPItemPosition::pixelPosition() const
  10587. {
  10588. QPointF result;
  10589. // determine X:
  10590. switch (mPositionTypeX)
  10591. {
  10592. case QCPItemPosition::PositionType::ptAbsolute:
  10593. {
  10594. result.rx() = mKey;
  10595. if (mParentAnchorX)
  10596. result.rx() += mParentAnchorX->pixelPosition().x();
  10597. break;
  10598. }
  10599. case QCPItemPosition::PositionType::ptViewportRatio:
  10600. {
  10601. result.rx() = mKey*mParentPlot->viewport().width();
  10602. if (mParentAnchorX)
  10603. result.rx() += mParentAnchorX->pixelPosition().x();
  10604. else
  10605. result.rx() += mParentPlot->viewport().left();
  10606. break;
  10607. }
  10608. case QCPItemPosition::PositionType::ptAxisRectRatio:
  10609. {
  10610. if (mAxisRect)
  10611. {
  10612. result.rx() = mKey*mAxisRect.data()->width();
  10613. if (mParentAnchorX)
  10614. result.rx() += mParentAnchorX->pixelPosition().x();
  10615. else
  10616. result.rx() += mAxisRect.data()->left();
  10617. } else
  10618. qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
  10619. break;
  10620. }
  10621. case QCPItemPosition::PositionType::ptPlotCoords:
  10622. {
  10623. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
  10624. result.rx() = mKeyAxis.data()->coordToPixel(mKey);
  10625. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
  10626. result.rx() = mValueAxis.data()->coordToPixel(mValue);
  10627. else
  10628. qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
  10629. break;
  10630. }
  10631. }
  10632. // determine Y:
  10633. switch (mPositionTypeY)
  10634. {
  10635. case QCPItemPosition::PositionType::ptAbsolute:
  10636. {
  10637. result.ry() = mValue;
  10638. if (mParentAnchorY)
  10639. result.ry() += mParentAnchorY->pixelPosition().y();
  10640. break;
  10641. }
  10642. case QCPItemPosition::PositionType::ptViewportRatio:
  10643. {
  10644. result.ry() = mValue*mParentPlot->viewport().height();
  10645. if (mParentAnchorY)
  10646. result.ry() += mParentAnchorY->pixelPosition().y();
  10647. else
  10648. result.ry() += mParentPlot->viewport().top();
  10649. break;
  10650. }
  10651. case QCPItemPosition::PositionType::ptAxisRectRatio:
  10652. {
  10653. if (mAxisRect)
  10654. {
  10655. result.ry() = mValue*mAxisRect.data()->height();
  10656. if (mParentAnchorY)
  10657. result.ry() += mParentAnchorY->pixelPosition().y();
  10658. else
  10659. result.ry() += mAxisRect.data()->top();
  10660. } else
  10661. qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
  10662. break;
  10663. }
  10664. case QCPItemPosition::PositionType::ptPlotCoords:
  10665. {
  10666. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
  10667. result.ry() = mKeyAxis.data()->coordToPixel(mKey);
  10668. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
  10669. result.ry() = mValueAxis.data()->coordToPixel(mValue);
  10670. else
  10671. qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
  10672. break;
  10673. }
  10674. }
  10675. return result;
  10676. }
  10677. /*!
  10678. When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the
  10679. coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and
  10680. yAxis of the QCustomPlot.
  10681. */
  10682. void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis)
  10683. {
  10684. mKeyAxis = keyAxis;
  10685. mValueAxis = valueAxis;
  10686. }
  10687. /*!
  10688. When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the
  10689. coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of
  10690. the QCustomPlot.
  10691. */
  10692. void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect)
  10693. {
  10694. mAxisRect = axisRect;
  10695. }
  10696. /*!
  10697. Sets the apparent pixel position. This works no matter what type (\ref setType) this
  10698. QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed
  10699. appropriately, to make the position finally appear at the specified pixel values.
  10700. Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is
  10701. identical to that of \ref setCoords.
  10702. \see pixelPosition, setCoords
  10703. */
  10704. void QCPItemPosition::setPixelPosition(const QPointF &pixelPosition)
  10705. {
  10706. double x = pixelPosition.x();
  10707. double y = pixelPosition.y();
  10708. switch (mPositionTypeX)
  10709. {
  10710. case QCPItemPosition::PositionType::ptAbsolute:
  10711. {
  10712. if (mParentAnchorX)
  10713. x -= mParentAnchorX->pixelPosition().x();
  10714. break;
  10715. }
  10716. case QCPItemPosition::PositionType::ptViewportRatio:
  10717. {
  10718. if (mParentAnchorX)
  10719. x -= mParentAnchorX->pixelPosition().x();
  10720. else
  10721. x -= mParentPlot->viewport().left();
  10722. x /= double(mParentPlot->viewport().width());
  10723. break;
  10724. }
  10725. case QCPItemPosition::PositionType::ptAxisRectRatio:
  10726. {
  10727. if (mAxisRect)
  10728. {
  10729. if (mParentAnchorX)
  10730. x -= mParentAnchorX->pixelPosition().x();
  10731. else
  10732. x -= mAxisRect.data()->left();
  10733. x /= double(mAxisRect.data()->width());
  10734. } else
  10735. qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined";
  10736. break;
  10737. }
  10738. case QCPItemPosition::PositionType::ptPlotCoords:
  10739. {
  10740. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal)
  10741. x = mKeyAxis.data()->pixelToCoord(x);
  10742. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal)
  10743. y = mValueAxis.data()->pixelToCoord(x);
  10744. else
  10745. qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined";
  10746. break;
  10747. }
  10748. }
  10749. switch (mPositionTypeY)
  10750. {
  10751. case QCPItemPosition::PositionType::ptAbsolute:
  10752. {
  10753. if (mParentAnchorY)
  10754. y -= mParentAnchorY->pixelPosition().y();
  10755. break;
  10756. }
  10757. case QCPItemPosition::PositionType::ptViewportRatio:
  10758. {
  10759. if (mParentAnchorY)
  10760. y -= mParentAnchorY->pixelPosition().y();
  10761. else
  10762. y -= mParentPlot->viewport().top();
  10763. y /= double(mParentPlot->viewport().height());
  10764. break;
  10765. }
  10766. case QCPItemPosition::PositionType::ptAxisRectRatio:
  10767. {
  10768. if (mAxisRect)
  10769. {
  10770. if (mParentAnchorY)
  10771. y -= mParentAnchorY->pixelPosition().y();
  10772. else
  10773. y -= mAxisRect.data()->top();
  10774. y /= double(mAxisRect.data()->height());
  10775. } else
  10776. qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined";
  10777. break;
  10778. }
  10779. case QCPItemPosition::PositionType::ptPlotCoords:
  10780. {
  10781. if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical)
  10782. x = mKeyAxis.data()->pixelToCoord(y);
  10783. else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical)
  10784. y = mValueAxis.data()->pixelToCoord(y);
  10785. else
  10786. qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined";
  10787. break;
  10788. }
  10789. }
  10790. setCoords(x, y);
  10791. }
  10792. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10793. //////////////////// QCPAbstractItem
  10794. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10795. /*! \class QCPAbstractItem
  10796. \brief The abstract base class for all items in a plot.
  10797. In QCustomPlot, items are supplemental graphical elements that are neither plottables
  10798. (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus
  10799. plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each
  10800. specific item has at least one QCPItemPosition member which controls the positioning. Some items
  10801. are defined by more than one coordinate and thus have two or more QCPItemPosition members (For
  10802. example, QCPItemRect has \a topLeft and \a bottomRight).
  10803. This abstract base class defines a very basic interface like visibility and clipping. Since this
  10804. class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass
  10805. yourself to create new items.
  10806. The built-in items are:
  10807. <table>
  10808. <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>
  10809. <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>
  10810. <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>
  10811. <tr><td>QCPItemRect</td><td>A rectangle</td></tr>
  10812. <tr><td>QCPItemEllipse</td><td>An ellipse</td></tr>
  10813. <tr><td>QCPItemPixmap</td><td>An arbitrary pixmap</td></tr>
  10814. <tr><td>QCPItemText</td><td>A text label</td></tr>
  10815. <tr><td>QCPItemBracket</td><td>A bracket which may be used to reference/highlight certain parts in the plot.</td></tr>
  10816. <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>
  10817. </table>
  10818. \section items-clipping Clipping
  10819. Items are by default clipped to the main axis rect (they are only visible inside the axis rect).
  10820. To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect
  10821. "setClipToAxisRect(false)".
  10822. On the other hand if you want the item to be clipped to a different axis rect, specify it via
  10823. \ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour, and
  10824. in principle is independent of the coordinate axes the item might be tied to via its position
  10825. members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping
  10826. also contains the axes used for the item positions.
  10827. \section items-using Using items
  10828. First you instantiate the item you want to use and add it to the plot:
  10829. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-1
  10830. by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just
  10831. set the plot coordinates where the line should start/end:
  10832. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-2
  10833. If we don't want the line to be positioned in plot coordinates but a different coordinate system,
  10834. e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this:
  10835. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-3
  10836. Then we can set the coordinates, this time in pixels:
  10837. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-4
  10838. and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect:
  10839. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpitemline-creation-5
  10840. For more advanced plots, it is even possible to set different types and parent anchors per X/Y
  10841. coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref
  10842. QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition.
  10843. \section items-subclassing Creating own items
  10844. To create an own item, you implement a subclass of QCPAbstractItem. These are the pure
  10845. virtual functions, you must implement:
  10846. \li \ref selectTest
  10847. \li \ref draw
  10848. See the documentation of those functions for what they need to do.
  10849. \subsection items-positioning Allowing the item to be positioned
  10850. As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall
  10851. have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add
  10852. a public member of type QCPItemPosition like so:
  10853. \code QCPItemPosition * const myPosition;\endcode
  10854. the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition
  10855. instance it points to, can be modified, of course).
  10856. The initialization of this pointer is made easy with the \ref createPosition function. Just assign
  10857. the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition
  10858. takes a string which is the name of the position, typically this is identical to the variable name.
  10859. For example, the constructor of QCPItemExample could look like this:
  10860. \code
  10861. QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) :
  10862. QCPAbstractItem(parentPlot),
  10863. myPosition(createPosition("myPosition"))
  10864. {
  10865. // other constructor code
  10866. }
  10867. \endcode
  10868. \subsection items-drawing The draw function
  10869. To give your item a visual representation, reimplement the \ref draw function and use the passed
  10870. QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the
  10871. position member(s) via \ref QCPItemPosition::pixelPosition.
  10872. To optimize performance you should calculate a bounding rect first (don't forget to take the pen
  10873. width into account), check whether it intersects the \ref clipRect, and only draw the item at all
  10874. if this is the case.
  10875. \subsection items-selection The selectTest function
  10876. Your implementation of the \ref selectTest function may use the helpers \ref
  10877. QCPVector2D::distanceSquaredToLine and \ref rectDistance. With these, the implementation of the
  10878. selection test becomes significantly simpler for most items. See the documentation of \ref
  10879. selectTest for what the function parameters mean and what the function should return.
  10880. \subsection anchors Providing anchors
  10881. Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public
  10882. member, e.g.
  10883. \code QCPItemAnchor * const bottom;\endcode
  10884. and create it in the constructor with the \ref createAnchor function, assigning it a name and an
  10885. anchor id (an integer enumerating all anchors on the item, you may create an own enum for this).
  10886. Since anchors can be placed anywhere, relative to the item's position(s), your item needs to
  10887. provide the position of every anchor with the reimplementation of the \ref anchorPixelPosition(int
  10888. anchorId) function.
  10889. In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel
  10890. position when anything attached to the anchor needs to know the coordinates.
  10891. */
  10892. /* start of documentation of inline functions */
  10893. /*! \fn QList<QCPItemPosition*> QCPAbstractItem::positions() const
  10894. Returns all positions of the item in a list.
  10895. \see anchors, position
  10896. */
  10897. /*! \fn QList<QCPItemAnchor*> QCPAbstractItem::anchors() const
  10898. Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always
  10899. also an anchor, the list will also contain the positions of this item.
  10900. \see positions, anchor
  10901. */
  10902. /* end of documentation of inline functions */
  10903. /* start documentation of pure virtual functions */
  10904. /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0
  10905. \internal
  10906. Draws this item with the provided \a painter.
  10907. The cliprect of the provided painter is set to the rect returned by \ref clipRect before this
  10908. function is called. The clipRect depends on the clipping settings defined by \ref
  10909. setClipToAxisRect and \ref setClipAxisRect.
  10910. */
  10911. /* end documentation of pure virtual functions */
  10912. /* start documentation of signals */
  10913. /*! \fn void QCPAbstractItem::selectionChanged(bool selected)
  10914. This signal is emitted when the selection state of this item has changed, either by user interaction
  10915. or by a direct call to \ref setSelected.
  10916. */
  10917. /* end documentation of signals */
  10918. /*!
  10919. Base class constructor which initializes base class members.
  10920. */
  10921. QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) :
  10922. QCPLayerable(parentPlot),
  10923. mClipToAxisRect(false),
  10924. mSelectable(true),
  10925. mSelected(false)
  10926. {
  10927. parentPlot->registerItem(this);
  10928. QList<QCPAxisRect*> rects = parentPlot->axisRects();
  10929. if (!rects.isEmpty())
  10930. {
  10931. setClipToAxisRect(true);
  10932. setClipAxisRect(rects.first());
  10933. }
  10934. }
  10935. QCPAbstractItem::~QCPAbstractItem()
  10936. {
  10937. // don't delete mPositions because every position is also an anchor and thus in mAnchors
  10938. qDeleteAll(mAnchors);
  10939. }
  10940. /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */
  10941. QCPAxisRect *QCPAbstractItem::clipAxisRect() const
  10942. {
  10943. return mClipAxisRect.data();
  10944. }
  10945. /*!
  10946. Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the
  10947. entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect.
  10948. \see setClipAxisRect
  10949. */
  10950. void QCPAbstractItem::setClipToAxisRect(bool clip)
  10951. {
  10952. mClipToAxisRect = clip;
  10953. if (mClipToAxisRect)
  10954. setParentLayerable(mClipAxisRect.data());
  10955. }
  10956. /*!
  10957. Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref
  10958. setClipToAxisRect is set to true.
  10959. \see setClipToAxisRect
  10960. */
  10961. void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect)
  10962. {
  10963. mClipAxisRect = rect;
  10964. if (mClipToAxisRect)
  10965. setParentLayerable(mClipAxisRect.data());
  10966. }
  10967. /*!
  10968. Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface.
  10969. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.)
  10970. However, even when \a selectable was set to false, it is possible to set the selection manually,
  10971. by calling \ref setSelected.
  10972. \see QCustomPlot::setInteractions, setSelected
  10973. */
  10974. void QCPAbstractItem::setSelectable(bool selectable)
  10975. {
  10976. if (mSelectable != selectable)
  10977. {
  10978. mSelectable = selectable;
  10979. emit selectableChanged(mSelectable);
  10980. }
  10981. }
  10982. /*!
  10983. Sets whether this item is selected or not. When selected, it might use a different visual
  10984. appearance (e.g. pen and brush), this depends on the specific item though.
  10985. The entire selection mechanism for items is handled automatically when \ref
  10986. QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this
  10987. function when you wish to change the selection state manually.
  10988. This function can change the selection state even when \ref setSelectable was set to false.
  10989. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  10990. \see setSelectable, selectTest
  10991. */
  10992. void QCPAbstractItem::setSelected(bool selected)
  10993. {
  10994. if (mSelected != selected)
  10995. {
  10996. mSelected = selected;
  10997. emit selectionChanged(mSelected);
  10998. }
  10999. }
  11000. /*!
  11001. Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by
  11002. that name, returns \c nullptr.
  11003. This function provides an alternative way to access item positions. Normally, you access
  11004. positions direcly by their member pointers (which typically have the same variable name as \a
  11005. name).
  11006. \see positions, anchor
  11007. */
  11008. QCPItemPosition *QCPAbstractItem::position(const QString &name) const
  11009. {
  11010. foreach (QCPItemPosition *position, mPositions)
  11011. {
  11012. if (position->name() == name)
  11013. return position;
  11014. }
  11015. qDebug() << Q_FUNC_INFO << "position with name not found:" << name;
  11016. return nullptr;
  11017. }
  11018. /*!
  11019. Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by
  11020. that name, returns \c nullptr.
  11021. This function provides an alternative way to access item anchors. Normally, you access
  11022. anchors direcly by their member pointers (which typically have the same variable name as \a
  11023. name).
  11024. \see anchors, position
  11025. */
  11026. QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const
  11027. {
  11028. foreach (QCPItemAnchor *anchor, mAnchors)
  11029. {
  11030. if (anchor->name() == name)
  11031. return anchor;
  11032. }
  11033. qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name;
  11034. return nullptr;
  11035. }
  11036. /*!
  11037. Returns whether this item has an anchor with the specified \a name.
  11038. Note that you can check for positions with this function, too. This is because every position is
  11039. also an anchor (QCPItemPosition inherits from QCPItemAnchor).
  11040. \see anchor, position
  11041. */
  11042. bool QCPAbstractItem::hasAnchor(const QString &name) const
  11043. {
  11044. foreach (QCPItemAnchor *anchor, mAnchors)
  11045. {
  11046. if (anchor->name() == name)
  11047. return true;
  11048. }
  11049. return false;
  11050. }
  11051. /*! \internal
  11052. Returns the rect the visual representation of this item is clipped to. This depends on the
  11053. current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect.
  11054. If the item is not clipped to an axis rect, QCustomPlot's viewport rect is returned.
  11055. \see draw
  11056. */
  11057. QRect QCPAbstractItem::clipRect() const
  11058. {
  11059. if (mClipToAxisRect && mClipAxisRect)
  11060. return mClipAxisRect.data()->rect();
  11061. else
  11062. return mParentPlot->viewport();
  11063. }
  11064. /*! \internal
  11065. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  11066. before drawing item lines.
  11067. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  11068. This function takes into account the local setting of the antialiasing flag as well as the
  11069. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  11070. QCustomPlot::setNotAntialiasedElements.
  11071. \see setAntialiased
  11072. */
  11073. void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
  11074. {
  11075. applyAntialiasingHint(painter, mAntialiased, QCP::aeItems);
  11076. }
  11077. /*! \internal
  11078. A convenience function which returns the selectTest value for a specified \a rect and a specified
  11079. click position \a pos. \a filledRect defines whether a click inside the rect should also be
  11080. considered a hit or whether only the rect border is sensitive to hits.
  11081. This function may be used to help with the implementation of the \ref selectTest function for
  11082. specific items.
  11083. For example, if your item consists of four rects, call this function four times, once for each
  11084. rect, in your \ref selectTest reimplementation. Finally, return the minimum (non -1) of all four
  11085. returned values.
  11086. */
  11087. double QCPAbstractItem::rectDistance(const QRectF &rect, const QPointF &pos, bool filledRect) const
  11088. {
  11089. double result = -1;
  11090. // distance to border:
  11091. const QList<QLineF> lines = QList<QLineF>() << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight())
  11092. << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight());
  11093. const QCPVector2D posVec(pos);
  11094. double minDistSqr = (std::numeric_limits<double>::max)();
  11095. foreach (const QLineF &line, lines)
  11096. {
  11097. double distSqr = posVec.distanceSquaredToLine(line.p1(), line.p2());
  11098. if (distSqr < minDistSqr)
  11099. minDistSqr = distSqr;
  11100. }
  11101. result = qSqrt(minDistSqr);
  11102. // filled rect, allow click inside to count as hit:
  11103. if (filledRect && result > mParentPlot->selectionTolerance()*0.99)
  11104. {
  11105. if (rect.contains(pos))
  11106. result = mParentPlot->selectionTolerance()*0.99;
  11107. }
  11108. return result;
  11109. }
  11110. /*! \internal
  11111. Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in
  11112. item subclasses if they want to provide anchors (QCPItemAnchor).
  11113. For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor
  11114. ids and returns the respective pixel points of the specified anchor.
  11115. \see createAnchor
  11116. */
  11117. QPointF QCPAbstractItem::anchorPixelPosition(int anchorId) const
  11118. {
  11119. qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId;
  11120. return {};
  11121. }
  11122. /*! \internal
  11123. Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified
  11124. \a name must be a unique string that is usually identical to the variable name of the position
  11125. member (This is needed to provide the name-based \ref position access to positions).
  11126. Don't delete positions created by this function manually, as the item will take care of it.
  11127. Use this function in the constructor (initialization list) of the specific item subclass to
  11128. create each position member. Don't create QCPItemPositions with \b new yourself, because they
  11129. won't be registered with the item properly.
  11130. \see createAnchor
  11131. */
  11132. QCPItemPosition *QCPAbstractItem::createPosition(const QString &name)
  11133. {
  11134. if (hasAnchor(name))
  11135. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  11136. QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name);
  11137. mPositions.append(newPosition);
  11138. mAnchors.append(newPosition); // every position is also an anchor
  11139. newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis);
  11140. newPosition->setType(QCPItemPosition::PositionType::ptPlotCoords);
  11141. if (mParentPlot->axisRect())
  11142. newPosition->setAxisRect(mParentPlot->axisRect());
  11143. newPosition->setCoords(0, 0);
  11144. return newPosition;
  11145. }
  11146. /*! \internal
  11147. Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified
  11148. \a name must be a unique string that is usually identical to the variable name of the anchor
  11149. member (This is needed to provide the name based \ref anchor access to anchors).
  11150. The \a anchorId must be a number identifying the created anchor. It is recommended to create an
  11151. enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor
  11152. to identify itself when it calls QCPAbstractItem::anchorPixelPosition. That function then returns
  11153. the correct pixel coordinates for the passed anchor id.
  11154. Don't delete anchors created by this function manually, as the item will take care of it.
  11155. Use this function in the constructor (initialization list) of the specific item subclass to
  11156. create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they
  11157. won't be registered with the item properly.
  11158. \see createPosition
  11159. */
  11160. QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId)
  11161. {
  11162. if (hasAnchor(name))
  11163. qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name;
  11164. QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId);
  11165. mAnchors.append(newAnchor);
  11166. return newAnchor;
  11167. }
  11168. /* inherits documentation from base class */
  11169. void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  11170. {
  11171. Q_UNUSED(event)
  11172. Q_UNUSED(details)
  11173. if (mSelectable)
  11174. {
  11175. bool selBefore = mSelected;
  11176. setSelected(additive ? !mSelected : true);
  11177. if (selectionStateChanged)
  11178. *selectionStateChanged = mSelected != selBefore;
  11179. }
  11180. }
  11181. /* inherits documentation from base class */
  11182. void QCPAbstractItem::deselectEvent(bool *selectionStateChanged)
  11183. {
  11184. if (mSelectable)
  11185. {
  11186. bool selBefore = mSelected;
  11187. setSelected(false);
  11188. if (selectionStateChanged)
  11189. *selectionStateChanged = mSelected != selBefore;
  11190. }
  11191. }
  11192. /* inherits documentation from base class */
  11193. QCP::Interaction QCPAbstractItem::selectionCategory() const
  11194. {
  11195. return QCP::iSelectItems;
  11196. }
  11197. /* end of 'src/item.cpp' */
  11198. /* including file 'src/core.cpp' */
  11199. /* modified 2021-03-29T02:30:44, size 127198 */
  11200. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11201. //////////////////// QCustomPlot
  11202. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11203. /*! \class QCustomPlot
  11204. \brief The central class of the library. This is the QWidget which displays the plot and
  11205. interacts with the user.
  11206. For tutorials on how to use QCustomPlot, see the website\n
  11207. http://www.qcustomplot.com/
  11208. */
  11209. /* start of documentation of inline functions */
  11210. /*! \fn QCPSelectionRect *QCustomPlot::selectionRect() const
  11211. Allows access to the currently used QCPSelectionRect instance (or subclass thereof), that is used
  11212. to handle and draw selection rect interactions (see \ref setSelectionRectMode).
  11213. \see setSelectionRect
  11214. */
  11215. /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const
  11216. Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just
  11217. one cell with the main QCPAxisRect inside.
  11218. */
  11219. /* end of documentation of inline functions */
  11220. /* start of documentation of signals */
  11221. /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event)
  11222. This signal is emitted when the QCustomPlot receives a mouse double click event.
  11223. */
  11224. /*! \fn void QCustomPlot::mousePress(QMouseEvent *event)
  11225. This signal is emitted when the QCustomPlot receives a mouse press event.
  11226. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  11227. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
  11228. QCPAxisRect::setRangeDragAxes.
  11229. */
  11230. /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event)
  11231. This signal is emitted when the QCustomPlot receives a mouse move event.
  11232. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot
  11233. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref
  11234. QCPAxisRect::setRangeDragAxes.
  11235. \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here,
  11236. because the dragging starting point was saved the moment the mouse was pressed. Thus it only has
  11237. a meaning for the range drag axes that were set at that moment. If you want to change the drag
  11238. axes, consider doing this in the \ref mousePress signal instead.
  11239. */
  11240. /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event)
  11241. This signal is emitted when the QCustomPlot receives a mouse release event.
  11242. It is emitted before QCustomPlot handles any other mechanisms like object selection. So a
  11243. slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or
  11244. \ref QCPAbstractPlottable::setSelectable.
  11245. */
  11246. /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event)
  11247. This signal is emitted when the QCustomPlot receives a mouse wheel event.
  11248. It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot
  11249. connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref
  11250. QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor.
  11251. */
  11252. /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
  11253. This signal is emitted when a plottable is clicked.
  11254. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  11255. the click. The parameter \a dataIndex indicates the data point that was closest to the click
  11256. position.
  11257. \see plottableDoubleClick
  11258. */
  11259. /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, int dataIndex, QMouseEvent *event)
  11260. This signal is emitted when a plottable is double clicked.
  11261. \a event is the mouse event that caused the click and \a plottable is the plottable that received
  11262. the click. The parameter \a dataIndex indicates the data point that was closest to the click
  11263. position.
  11264. \see plottableClick
  11265. */
  11266. /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event)
  11267. This signal is emitted when an item is clicked.
  11268. \a event is the mouse event that caused the click and \a item is the item that received the
  11269. click.
  11270. \see itemDoubleClick
  11271. */
  11272. /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event)
  11273. This signal is emitted when an item is double clicked.
  11274. \a event is the mouse event that caused the click and \a item is the item that received the
  11275. click.
  11276. \see itemClick
  11277. */
  11278. /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  11279. This signal is emitted when an axis is clicked.
  11280. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  11281. \a part indicates the part of the axis that was clicked.
  11282. \see axisDoubleClick
  11283. */
  11284. /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event)
  11285. This signal is emitted when an axis is double clicked.
  11286. \a event is the mouse event that caused the click, \a axis is the axis that received the click and
  11287. \a part indicates the part of the axis that was clicked.
  11288. \see axisClick
  11289. */
  11290. /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
  11291. This signal is emitted when a legend (item) is clicked.
  11292. \a event is the mouse event that caused the click, \a legend is the legend that received the
  11293. click and \a item is the legend item that received the click. If only the legend and no item is
  11294. clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space
  11295. between two items.
  11296. \see legendDoubleClick
  11297. */
  11298. /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event)
  11299. This signal is emitted when a legend (item) is double clicked.
  11300. \a event is the mouse event that caused the click, \a legend is the legend that received the
  11301. click and \a item is the legend item that received the click. If only the legend and no item is
  11302. clicked, \a item is \c nullptr. This happens for a click inside the legend padding or the space
  11303. between two items.
  11304. \see legendClick
  11305. */
  11306. /*! \fn void QCustomPlot::selectionChangedByUser()
  11307. This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by
  11308. clicking. It is not emitted when the selection state of an object has changed programmatically by
  11309. a direct call to <tt>setSelected()</tt>/<tt>setSelection()</tt> on an object or by calling \ref
  11310. deselectAll.
  11311. In addition to this signal, selectable objects also provide individual signals, for example \ref
  11312. QCPAxis::selectionChanged or \ref QCPAbstractPlottable::selectionChanged. Note that those signals
  11313. are emitted even if the selection state is changed programmatically.
  11314. See the documentation of \ref setInteractions for details about the selection mechanism.
  11315. \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends
  11316. */
  11317. /*! \fn void QCustomPlot::beforeReplot()
  11318. This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref
  11319. replot).
  11320. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  11321. replot synchronously, it won't cause an infinite recursion.
  11322. \see replot, afterReplot, afterLayout
  11323. */
  11324. /*! \fn void QCustomPlot::afterLayout()
  11325. This signal is emitted immediately after the layout step has been completed, which occurs right
  11326. before drawing the plot. This is typically during a call to \ref replot, and in such cases this
  11327. signal is emitted in between the signals \ref beforeReplot and \ref afterReplot. Unlike those
  11328. signals however, this signal is also emitted during off-screen painting, such as when calling
  11329. \ref toPixmap or \ref savePdf.
  11330. The layout step queries all layouts and layout elements in the plot for their proposed size and
  11331. arranges the objects accordingly as preparation for the subsequent drawing step. Through this
  11332. signal, you have the opportunity to update certain things in your plot that depend crucially on
  11333. the exact dimensions/positioning of layout elements such as axes and axis rects.
  11334. \warning However, changing any parameters of this QCustomPlot instance which would normally
  11335. affect the layouting (e.g. axis range order of magnitudes, tick label sizes, etc.) will not issue
  11336. a second run of the layout step. It will propagate directly to the draw step and may cause
  11337. graphical inconsistencies such as overlapping objects, if sizes or positions have changed.
  11338. \see updateLayout, beforeReplot, afterReplot
  11339. */
  11340. /*! \fn void QCustomPlot::afterReplot()
  11341. This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref
  11342. replot).
  11343. It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them
  11344. replot synchronously, it won't cause an infinite recursion.
  11345. \see replot, beforeReplot, afterLayout
  11346. */
  11347. /* end of documentation of signals */
  11348. /* start of documentation of public members */
  11349. /*! \var QCPAxis *QCustomPlot::xAxis
  11350. A pointer to the primary x Axis (bottom) of the main axis rect of the plot.
  11351. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11352. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11353. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11354. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11355. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11356. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11357. axis rect), the corresponding pointers become \c nullptr.
  11358. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11359. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11360. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11361. is added after the main legend was removed before.
  11362. */
  11363. /*! \var QCPAxis *QCustomPlot::yAxis
  11364. A pointer to the primary y Axis (left) of the main axis rect of the plot.
  11365. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11366. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11367. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11368. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11369. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11370. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11371. axis rect), the corresponding pointers become \c nullptr.
  11372. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11373. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11374. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11375. is added after the main legend was removed before.
  11376. */
  11377. /*! \var QCPAxis *QCustomPlot::xAxis2
  11378. A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are
  11379. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  11380. QCPAxisRect::setupFullAxesBox).
  11381. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11382. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11383. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11384. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11385. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11386. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11387. axis rect), the corresponding pointers become \c nullptr.
  11388. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11389. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11390. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11391. is added after the main legend was removed before.
  11392. */
  11393. /*! \var QCPAxis *QCustomPlot::yAxis2
  11394. A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are
  11395. invisible by default. Use QCPAxis::setVisible to change this (or use \ref
  11396. QCPAxisRect::setupFullAxesBox).
  11397. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11398. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11399. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11400. layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref
  11401. QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the
  11402. default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11403. axis rect), the corresponding pointers become \c nullptr.
  11404. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11405. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11406. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11407. is added after the main legend was removed before.
  11408. */
  11409. /*! \var QCPLegend *QCustomPlot::legend
  11410. A pointer to the default legend of the main axis rect. The legend is invisible by default. Use
  11411. QCPLegend::setVisible to change this.
  11412. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref
  11413. yAxis2) and the \ref legend. They make it very easy working with plots that only have a single
  11414. axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the
  11415. layout system\endlink to add multiple legends to the plot, use the layout system interface to
  11416. access the new legend. For example, legends can be placed inside an axis rect's \ref
  11417. QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If
  11418. the default legend is removed due to manipulation of the layout system (e.g. by removing the main
  11419. axis rect), the corresponding pointer becomes \c nullptr.
  11420. If an axis convenience pointer is currently \c nullptr and a new axis rect or a corresponding
  11421. axis is added in the place of the main axis rect, QCustomPlot resets the convenience pointers to
  11422. the according new axes. Similarly the \ref legend convenience pointer will be reset if a legend
  11423. is added after the main legend was removed before.
  11424. */
  11425. /* end of documentation of public members */
  11426. /*!
  11427. Constructs a QCustomPlot and sets reasonable default values.
  11428. */
  11429. QCustomPlot::QCustomPlot(QWidget *parent) :
  11430. QWidget(parent),
  11431. xAxis(nullptr),
  11432. yAxis(nullptr),
  11433. xAxis2(nullptr),
  11434. yAxis2(nullptr),
  11435. legend(nullptr),
  11436. mBufferDevicePixelRatio(1.0), // will be adapted to primary screen below
  11437. mPlotLayout(nullptr),
  11438. mAutoAddPlottableToLegend(true),
  11439. mAntialiasedElements(QCP::aeNone),
  11440. mNotAntialiasedElements(QCP::aeNone),
  11441. mInteractions(QCP::iNone),
  11442. mSelectionTolerance(8),
  11443. mNoAntialiasingOnDrag(false),
  11444. mBackgroundBrush(Qt::white, Qt::SolidPattern),
  11445. mBackgroundScaled(true),
  11446. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  11447. mCurrentLayer(nullptr),
  11448. mPlottingHints(QCP::phCacheLabels|QCP::phImmediateRefresh),
  11449. mMultiSelectModifier(Qt::ControlModifier),
  11450. mSelectionRectMode(QCP::srmNone),
  11451. mSelectionRect(nullptr),
  11452. mOpenGl(false),
  11453. mMouseHasMoved(false),
  11454. mMouseEventLayerable(nullptr),
  11455. mMouseSignalLayerable(nullptr),
  11456. mReplotting(false),
  11457. mReplotQueued(false),
  11458. mReplotTime(0),
  11459. mReplotTimeAverage(0),
  11460. mOpenGlMultisamples(16),
  11461. mOpenGlAntialiasedElementsBackup(QCP::aeNone),
  11462. mOpenGlCacheLabelsBackup(true)
  11463. {
  11464. setAttribute(Qt::WA_NoMousePropagation);
  11465. setAttribute(Qt::WA_OpaquePaintEvent);
  11466. setFocusPolicy(Qt::ClickFocus);
  11467. setMouseTracking(true);
  11468. QLocale currentLocale = locale();
  11469. currentLocale.setNumberOptions(QLocale::OmitGroupSeparator);
  11470. setLocale(currentLocale);
  11471. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  11472. # ifdef QCP_DEVICEPIXELRATIO_FLOAT
  11473. setBufferDevicePixelRatio(QWidget::devicePixelRatioF());
  11474. # else
  11475. setBufferDevicePixelRatio(QWidget::devicePixelRatio());
  11476. # endif
  11477. #endif
  11478. mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
  11479. mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
  11480. // create initial layers:
  11481. mLayers.append(new QCPLayer(this, QLatin1String("background")));
  11482. mLayers.append(new QCPLayer(this, QLatin1String("grid")));
  11483. mLayers.append(new QCPLayer(this, QLatin1String("main")));
  11484. mLayers.append(new QCPLayer(this, QLatin1String("axes")));
  11485. mLayers.append(new QCPLayer(this, QLatin1String("legend")));
  11486. mLayers.append(new QCPLayer(this, QLatin1String("overlay")));
  11487. updateLayerIndices();
  11488. setCurrentLayer(QLatin1String("main"));
  11489. layer(QLatin1String("overlay"))->setMode(QCPLayer::lmBuffered);
  11490. // create initial layout, axis rect and legend:
  11491. mPlotLayout = new QCPLayoutGrid;
  11492. mPlotLayout->initializeParentPlot(this);
  11493. mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry
  11494. mPlotLayout->setLayer(QLatin1String("main"));
  11495. QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true);
  11496. mPlotLayout->addElement(0, 0, defaultAxisRect);
  11497. xAxis = defaultAxisRect->axis(QCPAxis::AxisType::atBottom);
  11498. yAxis = defaultAxisRect->axis(QCPAxis::AxisType::atLeft);
  11499. xAxis2 = defaultAxisRect->axis(QCPAxis::AxisType::atTop);
  11500. yAxis2 = defaultAxisRect->axis(QCPAxis::AxisType::atRight);
  11501. legend = new QCPLegend;
  11502. legend->setVisible(false);
  11503. defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop);
  11504. defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12));
  11505. defaultAxisRect->setLayer(QLatin1String("background"));
  11506. xAxis->setLayer(QLatin1String("axes"));
  11507. yAxis->setLayer(QLatin1String("axes"));
  11508. xAxis2->setLayer(QLatin1String("axes"));
  11509. yAxis2->setLayer(QLatin1String("axes"));
  11510. xAxis->grid()->setLayer(QLatin1String("grid"));
  11511. yAxis->grid()->setLayer(QLatin1String("grid"));
  11512. xAxis2->grid()->setLayer(QLatin1String("grid"));
  11513. yAxis2->grid()->setLayer(QLatin1String("grid"));
  11514. legend->setLayer(QLatin1String("legend"));
  11515. // create selection rect instance:
  11516. mSelectionRect = new QCPSelectionRect(this);
  11517. mSelectionRect->setLayer(QLatin1String("overlay"));
  11518. setViewport(rect()); // needs to be called after mPlotLayout has been created
  11519. replot(rpQueuedReplot);
  11520. }
  11521. QCustomPlot::~QCustomPlot()
  11522. {
  11523. clearPlottables();
  11524. clearItems();
  11525. if (mPlotLayout)
  11526. {
  11527. delete mPlotLayout;
  11528. mPlotLayout = nullptr;
  11529. }
  11530. mCurrentLayer = nullptr;
  11531. qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed
  11532. mLayers.clear();
  11533. }
  11534. /*!
  11535. Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement.
  11536. This overrides the antialiasing settings for whole element groups, normally controlled with the
  11537. \a setAntialiasing function on the individual elements. If an element is neither specified in
  11538. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  11539. each individual element instance is used.
  11540. For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be
  11541. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  11542. to.
  11543. if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is
  11544. removed from there.
  11545. \see setNotAntialiasedElements
  11546. */
  11547. void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements)
  11548. {
  11549. mAntialiasedElements = antialiasedElements;
  11550. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11551. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11552. mNotAntialiasedElements |= ~mAntialiasedElements;
  11553. }
  11554. /*!
  11555. Sets whether the specified \a antialiasedElement is forcibly drawn antialiased.
  11556. See \ref setAntialiasedElements for details.
  11557. \see setNotAntialiasedElement
  11558. */
  11559. void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled)
  11560. {
  11561. if (!enabled && mAntialiasedElements.testFlag(antialiasedElement))
  11562. mAntialiasedElements &= ~antialiasedElement;
  11563. else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement))
  11564. mAntialiasedElements |= antialiasedElement;
  11565. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11566. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11567. mNotAntialiasedElements |= ~mAntialiasedElements;
  11568. }
  11569. /*!
  11570. Sets which elements are forcibly drawn not antialiased as an \a or combination of
  11571. QCP::AntialiasedElement.
  11572. This overrides the antialiasing settings for whole element groups, normally controlled with the
  11573. \a setAntialiasing function on the individual elements. If an element is neither specified in
  11574. \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on
  11575. each individual element instance is used.
  11576. For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be
  11577. drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set
  11578. to.
  11579. if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is
  11580. removed from there.
  11581. \see setAntialiasedElements
  11582. */
  11583. void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements &notAntialiasedElements)
  11584. {
  11585. mNotAntialiasedElements = notAntialiasedElements;
  11586. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11587. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11588. mAntialiasedElements |= ~mNotAntialiasedElements;
  11589. }
  11590. /*!
  11591. Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased.
  11592. See \ref setNotAntialiasedElements for details.
  11593. \see setAntialiasedElement
  11594. */
  11595. void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled)
  11596. {
  11597. if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement))
  11598. mNotAntialiasedElements &= ~notAntialiasedElement;
  11599. else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement))
  11600. mNotAntialiasedElements |= notAntialiasedElement;
  11601. // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously:
  11602. if ((mNotAntialiasedElements & mAntialiasedElements) != 0)
  11603. mAntialiasedElements |= ~mNotAntialiasedElements;
  11604. }
  11605. /*!
  11606. If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the
  11607. plottable to the legend (QCustomPlot::legend).
  11608. \see addGraph, QCPLegend::addItem
  11609. */
  11610. void QCustomPlot::setAutoAddPlottableToLegend(bool on)
  11611. {
  11612. mAutoAddPlottableToLegend = on;
  11613. }
  11614. /*!
  11615. Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction
  11616. enums. There are the following types of interactions:
  11617. <b>Axis range manipulation</b> is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the
  11618. respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel.
  11619. For details how to control which axes the user may drag/zoom and in what orientations, see \ref
  11620. QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes,
  11621. \ref QCPAxisRect::setRangeZoomAxes.
  11622. <b>Plottable data selection</b> is controlled by \ref QCP::iSelectPlottables. If \ref
  11623. QCP::iSelectPlottables is set, the user may select plottables (graphs, curves, bars,...) and
  11624. their data by clicking on them or in their vicinity (\ref setSelectionTolerance). Whether the
  11625. user can actually select a plottable and its data can further be restricted with the \ref
  11626. QCPAbstractPlottable::setSelectable method on the specific plottable. For details, see the
  11627. special page about the \ref dataselection "data selection mechanism". To retrieve a list of all
  11628. currently selected plottables, call \ref selectedPlottables. If you're only interested in
  11629. QCPGraphs, you may use the convenience function \ref selectedGraphs.
  11630. <b>Item selection</b> is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user
  11631. may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find
  11632. out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of
  11633. all currently selected items, call \ref selectedItems.
  11634. <b>Axis selection</b> is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user
  11635. may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick
  11636. labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for
  11637. each axis. To retrieve a list of all axes that currently contain selected parts, call \ref
  11638. selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts().
  11639. <b>Legend selection</b> is controlled with \ref QCP::iSelectLegend. If this is set, the user may
  11640. select the legend itself or individual items by clicking on them. What parts exactly are
  11641. selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the
  11642. legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To
  11643. find out which child items are selected, call \ref QCPLegend::selectedItems.
  11644. <b>All other selectable elements</b> The selection of all other selectable objects (e.g.
  11645. QCPTextElement, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the
  11646. user may select those objects by clicking on them. To find out which are currently selected, you
  11647. need to check their selected state explicitly.
  11648. If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is
  11649. emitted. Each selectable object additionally emits an individual selectionChanged signal whenever
  11650. their selection state has changed, i.e. not only by user interaction.
  11651. To allow multiple objects to be selected by holding the selection modifier (\ref
  11652. setMultiSelectModifier), set the flag \ref QCP::iMultiSelect.
  11653. \note In addition to the selection mechanism presented here, QCustomPlot always emits
  11654. corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and
  11655. \ref plottableDoubleClick for example.
  11656. \see setInteraction, setSelectionTolerance
  11657. */
  11658. void QCustomPlot::setInteractions(const QCP::Interactions &interactions)
  11659. {
  11660. mInteractions = interactions;
  11661. }
  11662. /*!
  11663. Sets the single \a interaction of this QCustomPlot to \a enabled.
  11664. For details about the interaction system, see \ref setInteractions.
  11665. \see setInteractions
  11666. */
  11667. void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled)
  11668. {
  11669. if (!enabled && mInteractions.testFlag(interaction))
  11670. mInteractions &= ~interaction;
  11671. else if (enabled && !mInteractions.testFlag(interaction))
  11672. mInteractions |= interaction;
  11673. }
  11674. /*!
  11675. Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or
  11676. not.
  11677. If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a
  11678. potential selection when the minimum distance between the click position and the graph line is
  11679. smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks
  11680. directly inside the area and ignore this selection tolerance. In other words, it only has meaning
  11681. for parts of objects that are too thin to exactly hit with a click and thus need such a
  11682. tolerance.
  11683. \see setInteractions, QCPLayerable::selectTest
  11684. */
  11685. void QCustomPlot::setSelectionTolerance(int pixels)
  11686. {
  11687. mSelectionTolerance = pixels;
  11688. }
  11689. /*!
  11690. Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes
  11691. ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves
  11692. performance during dragging. Thus it creates a more responsive user experience. As soon as the
  11693. user stops dragging, the last replot is done with normal antialiasing, to restore high image
  11694. quality.
  11695. \see setAntialiasedElements, setNotAntialiasedElements
  11696. */
  11697. void QCustomPlot::setNoAntialiasingOnDrag(bool enabled)
  11698. {
  11699. mNoAntialiasingOnDrag = enabled;
  11700. }
  11701. /*!
  11702. Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint.
  11703. \see setPlottingHint
  11704. */
  11705. void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints)
  11706. {
  11707. mPlottingHints = hints;
  11708. }
  11709. /*!
  11710. Sets the specified plotting \a hint to \a enabled.
  11711. \see setPlottingHints
  11712. */
  11713. void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled)
  11714. {
  11715. QCP::PlottingHints newHints = mPlottingHints;
  11716. if (!enabled)
  11717. newHints &= ~hint;
  11718. else
  11719. newHints |= hint;
  11720. if (newHints != mPlottingHints)
  11721. setPlottingHints(newHints);
  11722. }
  11723. /*!
  11724. Sets the keyboard modifier that will be recognized as multi-select-modifier.
  11725. If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple
  11726. objects (or data points) by clicking on them one after the other while holding down \a modifier.
  11727. By default the multi-select-modifier is set to Qt::ControlModifier.
  11728. \see setInteractions
  11729. */
  11730. void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier)
  11731. {
  11732. mMultiSelectModifier = modifier;
  11733. }
  11734. /*!
  11735. Sets how QCustomPlot processes mouse click-and-drag interactions by the user.
  11736. If \a mode is \ref QCP::srmNone, the mouse drag is forwarded to the underlying objects. For
  11737. example, QCPAxisRect may process a mouse drag by dragging axis ranges, see \ref
  11738. QCPAxisRect::setRangeDrag. If \a mode is not \ref QCP::srmNone, the current selection rect (\ref
  11739. selectionRect) becomes activated and allows e.g. rect zooming and data point selection.
  11740. If you wish to provide your user both with axis range dragging and data selection/range zooming,
  11741. use this method to switch between the modes just before the interaction is processed, e.g. in
  11742. reaction to the \ref mousePress or \ref mouseMove signals. For example you could check whether
  11743. the user is holding a certain keyboard modifier, and then decide which \a mode shall be set.
  11744. If a selection rect interaction is currently active, and \a mode is set to \ref QCP::srmNone, the
  11745. interaction is canceled (\ref QCPSelectionRect::cancel). Switching between any of the other modes
  11746. will keep the selection rect active. Upon completion of the interaction, the behaviour is as
  11747. defined by the currently set \a mode, not the mode that was set when the interaction started.
  11748. \see setInteractions, setSelectionRect, QCPSelectionRect
  11749. */
  11750. void QCustomPlot::setSelectionRectMode(QCP::SelectionRectMode mode)
  11751. {
  11752. if (mSelectionRect)
  11753. {
  11754. if (mode == QCP::srmNone)
  11755. mSelectionRect->cancel(); // when switching to none, we immediately want to abort a potentially active selection rect
  11756. // disconnect old connections:
  11757. if (mSelectionRectMode == QCP::srmSelect)
  11758. disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11759. else if (mSelectionRectMode == QCP::srmZoom)
  11760. disconnect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11761. // establish new ones:
  11762. if (mode == QCP::srmSelect)
  11763. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11764. else if (mode == QCP::srmZoom)
  11765. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11766. }
  11767. mSelectionRectMode = mode;
  11768. }
  11769. /*!
  11770. Sets the \ref QCPSelectionRect instance that QCustomPlot will use if \a mode is not \ref
  11771. QCP::srmNone and the user performs a click-and-drag interaction. QCustomPlot takes ownership of
  11772. the passed \a selectionRect. It can be accessed later via \ref selectionRect.
  11773. This method is useful if you wish to replace the default QCPSelectionRect instance with an
  11774. instance of a QCPSelectionRect subclass, to introduce custom behaviour of the selection rect.
  11775. \see setSelectionRectMode
  11776. */
  11777. void QCustomPlot::setSelectionRect(QCPSelectionRect *selectionRect)
  11778. {
  11779. delete mSelectionRect;
  11780. mSelectionRect = selectionRect;
  11781. if (mSelectionRect)
  11782. {
  11783. // establish connections with new selection rect:
  11784. if (mSelectionRectMode == QCP::srmSelect)
  11785. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectSelection(QRect,QMouseEvent*)));
  11786. else if (mSelectionRectMode == QCP::srmZoom)
  11787. connect(mSelectionRect, SIGNAL(accepted(QRect,QMouseEvent*)), this, SLOT(processRectZoom(QRect,QMouseEvent*)));
  11788. }
  11789. }
  11790. /*!
  11791. \warning This is still an experimental feature and its performance depends on the system that it
  11792. runs on. Having multiple QCustomPlot widgets in one application with enabled OpenGL rendering
  11793. might cause context conflicts on some systems.
  11794. This method allows to enable OpenGL plot rendering, for increased plotting performance of
  11795. graphically demanding plots (thick lines, translucent fills, etc.).
  11796. If \a enabled is set to true, QCustomPlot will try to initialize OpenGL and, if successful,
  11797. continue plotting with hardware acceleration. The parameter \a multisampling controls how many
  11798. samples will be used per pixel, it essentially controls the antialiasing quality. If \a
  11799. multisampling is set too high for the current graphics hardware, the maximum allowed value will
  11800. be used.
  11801. You can test whether switching to OpenGL rendering was successful by checking whether the
  11802. according getter \a QCustomPlot::openGl() returns true. If the OpenGL initialization fails,
  11803. rendering continues with the regular software rasterizer, and an according qDebug output is
  11804. generated.
  11805. If switching to OpenGL was successful, this method disables label caching (\ref setPlottingHint
  11806. "setPlottingHint(QCP::phCacheLabels, false)") and turns on QCustomPlot's antialiasing override
  11807. for all elements (\ref setAntialiasedElements "setAntialiasedElements(QCP::aeAll)"), leading to a
  11808. higher quality output. The antialiasing override allows for pixel-grid aligned drawing in the
  11809. OpenGL paint device. As stated before, in OpenGL rendering the actual antialiasing of the plot is
  11810. controlled with \a multisampling. If \a enabled is set to false, the antialiasing/label caching
  11811. settings are restored to what they were before OpenGL was enabled, if they weren't altered in the
  11812. meantime.
  11813. \note OpenGL support is only enabled if QCustomPlot is compiled with the macro \c QCUSTOMPLOT_USE_OPENGL
  11814. defined. This define must be set before including the QCustomPlot header both during compilation
  11815. of the QCustomPlot library as well as when compiling your application. It is best to just include
  11816. the line <tt>DEFINES += QCUSTOMPLOT_USE_OPENGL</tt> in the respective qmake project files.
  11817. \note If you are using a Qt version before 5.0, you must also add the module "opengl" to your \c
  11818. QT variable in the qmake project files. For Qt versions 5.0 and higher, QCustomPlot switches to a
  11819. newer OpenGL interface which is already in the "gui" module.
  11820. */
  11821. void QCustomPlot::setOpenGl(bool enabled, int multisampling)
  11822. {
  11823. mOpenGlMultisamples = qMax(0, multisampling);
  11824. #ifdef QCUSTOMPLOT_USE_OPENGL
  11825. mOpenGl = enabled;
  11826. if (mOpenGl)
  11827. {
  11828. if (setupOpenGl())
  11829. {
  11830. // backup antialiasing override and labelcaching setting so we can restore upon disabling OpenGL
  11831. mOpenGlAntialiasedElementsBackup = mAntialiasedElements;
  11832. mOpenGlCacheLabelsBackup = mPlottingHints.testFlag(QCP::phCacheLabels);
  11833. // set antialiasing override to antialias all (aligns gl pixel grid properly), and disable label caching (would use software rasterizer for pixmap caches):
  11834. setAntialiasedElements(QCP::aeAll);
  11835. setPlottingHint(QCP::phCacheLabels, false);
  11836. } else
  11837. {
  11838. qDebug() << Q_FUNC_INFO << "Failed to enable OpenGL, continuing plotting without hardware acceleration.";
  11839. mOpenGl = false;
  11840. }
  11841. } else
  11842. {
  11843. // restore antialiasing override and labelcaching to what it was before enabling OpenGL, if nobody changed it in the meantime:
  11844. if (mAntialiasedElements == QCP::aeAll)
  11845. setAntialiasedElements(mOpenGlAntialiasedElementsBackup);
  11846. if (!mPlottingHints.testFlag(QCP::phCacheLabels))
  11847. setPlottingHint(QCP::phCacheLabels, mOpenGlCacheLabelsBackup);
  11848. freeOpenGl();
  11849. }
  11850. // recreate all paint buffers:
  11851. mPaintBuffers.clear();
  11852. setupPaintBuffers();
  11853. #else
  11854. Q_UNUSED(enabled)
  11855. 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)";
  11856. #endif
  11857. }
  11858. /*!
  11859. Sets the viewport of this QCustomPlot. Usually users of QCustomPlot don't need to change the
  11860. viewport manually.
  11861. The viewport is the area in which the plot is drawn. All mechanisms, e.g. margin calculation take
  11862. the viewport to be the outer border of the plot. The viewport normally is the rect() of the
  11863. QCustomPlot widget, i.e. a rect with top left (0, 0) and size of the QCustomPlot widget.
  11864. Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically
  11865. an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger
  11866. and contains also the axes themselves, their tick numbers, their labels, or even additional axis
  11867. rects, color scales and other layout elements.
  11868. This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref
  11869. savePdf, etc. by temporarily changing the viewport size.
  11870. */
  11871. void QCustomPlot::setViewport(const QRect &rect)
  11872. {
  11873. mViewport = rect;
  11874. if (mPlotLayout)
  11875. mPlotLayout->setOuterRect(mViewport);
  11876. }
  11877. /*!
  11878. Sets the device pixel ratio used by the paint buffers of this QCustomPlot instance.
  11879. Normally, this doesn't need to be set manually, because it is initialized with the regular \a
  11880. QWidget::devicePixelRatio which is configured by Qt to fit the display device (e.g. 1 for normal
  11881. displays, 2 for High-DPI displays).
  11882. Device pixel ratios are supported by Qt only for Qt versions since 5.4. If this method is called
  11883. when QCustomPlot is being used with older Qt versions, outputs an according qDebug message and
  11884. leaves the internal buffer device pixel ratio at 1.0.
  11885. */
  11886. void QCustomPlot::setBufferDevicePixelRatio(double ratio)
  11887. {
  11888. if (!qFuzzyCompare(ratio, mBufferDevicePixelRatio))
  11889. {
  11890. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  11891. mBufferDevicePixelRatio = ratio;
  11892. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  11893. buffer->setDevicePixelRatio(mBufferDevicePixelRatio);
  11894. // Note: axis label cache has devicePixelRatio as part of cache hash, so no need to manually clear cache here
  11895. #else
  11896. qDebug() << Q_FUNC_INFO << "Device pixel ratios not supported for Qt versions before 5.4";
  11897. mBufferDevicePixelRatio = 1.0;
  11898. #endif
  11899. }
  11900. }
  11901. /*!
  11902. Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn
  11903. below all other objects in the plot.
  11904. For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be
  11905. enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is
  11906. preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  11907. consider using the overloaded version of this function.
  11908. If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will
  11909. first be filled with that brush, before drawing the background pixmap. This can be useful for
  11910. background pixmaps with translucent areas.
  11911. \see setBackgroundScaled, setBackgroundScaledMode
  11912. */
  11913. void QCustomPlot::setBackground(const QPixmap &pm)
  11914. {
  11915. mBackgroundPixmap = pm;
  11916. mScaledBackgroundPixmap = QPixmap();
  11917. }
  11918. /*!
  11919. Sets the background brush of the viewport (see \ref setViewport).
  11920. Before drawing everything else, the background is filled with \a brush. If a background pixmap
  11921. was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport
  11922. before the background pixmap is drawn. This can be useful for background pixmaps with translucent
  11923. areas.
  11924. Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be
  11925. useful for exporting to image formats which support transparency, e.g. \ref savePng.
  11926. \see setBackgroundScaled, setBackgroundScaledMode
  11927. */
  11928. void QCustomPlot::setBackground(const QBrush &brush)
  11929. {
  11930. mBackgroundBrush = brush;
  11931. }
  11932. /*! \overload
  11933. Allows setting the background pixmap of the viewport, whether it shall be scaled and how it
  11934. shall be scaled in one call.
  11935. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  11936. */
  11937. void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  11938. {
  11939. mBackgroundPixmap = pm;
  11940. mScaledBackgroundPixmap = QPixmap();
  11941. mBackgroundScaled = scaled;
  11942. mBackgroundScaledMode = mode;
  11943. }
  11944. /*!
  11945. Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is
  11946. set to true, control whether and how the aspect ratio of the original pixmap is preserved with
  11947. \ref setBackgroundScaledMode.
  11948. Note that the scaled version of the original pixmap is buffered, so there is no performance
  11949. penalty on replots. (Except when the viewport dimensions are changed continuously.)
  11950. \see setBackground, setBackgroundScaledMode
  11951. */
  11952. void QCustomPlot::setBackgroundScaled(bool scaled)
  11953. {
  11954. mBackgroundScaled = scaled;
  11955. }
  11956. /*!
  11957. If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this
  11958. function to define whether and how the aspect ratio of the original pixmap is preserved.
  11959. \see setBackground, setBackgroundScaled
  11960. */
  11961. void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  11962. {
  11963. mBackgroundScaledMode = mode;
  11964. }
  11965. /*!
  11966. Returns the plottable with \a index. If the index is invalid, returns \c nullptr.
  11967. There is an overloaded version of this function with no parameter which returns the last added
  11968. plottable, see QCustomPlot::plottable()
  11969. \see plottableCount
  11970. */
  11971. QCPAbstractPlottable *QCustomPlot::plottable(int index)
  11972. {
  11973. if (index >= 0 && index < mPlottables.size())
  11974. {
  11975. return mPlottables.at(index);
  11976. } else
  11977. {
  11978. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  11979. return nullptr;
  11980. }
  11981. }
  11982. /*! \overload
  11983. Returns the last plottable that was added to the plot. If there are no plottables in the plot,
  11984. returns \c nullptr.
  11985. \see plottableCount
  11986. */
  11987. QCPAbstractPlottable *QCustomPlot::plottable()
  11988. {
  11989. if (!mPlottables.isEmpty())
  11990. {
  11991. return mPlottables.last();
  11992. } else
  11993. return nullptr;
  11994. }
  11995. /*!
  11996. Removes the specified plottable from the plot and deletes it. If necessary, the corresponding
  11997. legend item is also removed from the default legend (QCustomPlot::legend).
  11998. Returns true on success.
  11999. \see clearPlottables
  12000. */
  12001. bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable)
  12002. {
  12003. if (!mPlottables.contains(plottable))
  12004. {
  12005. qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast<quintptr>(plottable);
  12006. return false;
  12007. }
  12008. // remove plottable from legend:
  12009. plottable->removeFromLegend();
  12010. // special handling for QCPGraphs to maintain the simple graph interface:
  12011. if (QCPGraph *graph = qobject_cast<QCPGraph*>(plottable))
  12012. mGraphs.removeOne(graph);
  12013. // remove plottable:
  12014. delete plottable;
  12015. mPlottables.removeOne(plottable);
  12016. return true;
  12017. }
  12018. /*! \overload
  12019. Removes and deletes the plottable by its \a index.
  12020. */
  12021. bool QCustomPlot::removePlottable(int index)
  12022. {
  12023. if (index >= 0 && index < mPlottables.size())
  12024. return removePlottable(mPlottables[index]);
  12025. else
  12026. {
  12027. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12028. return false;
  12029. }
  12030. }
  12031. /*!
  12032. Removes all plottables from the plot and deletes them. Corresponding legend items are also
  12033. removed from the default legend (QCustomPlot::legend).
  12034. Returns the number of plottables removed.
  12035. \see removePlottable
  12036. */
  12037. int QCustomPlot::clearPlottables()
  12038. {
  12039. int c = mPlottables.size();
  12040. for (int i=c-1; i >= 0; --i)
  12041. removePlottable(mPlottables[i]);
  12042. return c;
  12043. }
  12044. /*!
  12045. Returns the number of currently existing plottables in the plot
  12046. \see plottable
  12047. */
  12048. int QCustomPlot::plottableCount() const
  12049. {
  12050. return mPlottables.size();
  12051. }
  12052. /*!
  12053. Returns a list of the selected plottables. If no plottables are currently selected, the list is empty.
  12054. There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs.
  12055. \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
  12056. */
  12057. QList<QCPAbstractPlottable*> QCustomPlot::selectedPlottables() const
  12058. {
  12059. QList<QCPAbstractPlottable*> result;
  12060. foreach (QCPAbstractPlottable *plottable, mPlottables)
  12061. {
  12062. if (plottable->selected())
  12063. result.append(plottable);
  12064. }
  12065. return result;
  12066. }
  12067. /*!
  12068. Returns any plottable at the pixel position \a pos. Since it can capture all plottables, the
  12069. return type is the abstract base class of all plottables, QCPAbstractPlottable.
  12070. For details, and if you wish to specify a certain plottable type (e.g. QCPGraph), see the
  12071. template method plottableAt<PlottableType>()
  12072. \see plottableAt<PlottableType>(), itemAt, layoutElementAt
  12073. */
  12074. QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable, int *dataIndex) const
  12075. {
  12076. return plottableAt<QCPAbstractPlottable>(pos, onlySelectable, dataIndex);
  12077. }
  12078. /*!
  12079. Returns whether this QCustomPlot instance contains the \a plottable.
  12080. */
  12081. bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const
  12082. {
  12083. return mPlottables.contains(plottable);
  12084. }
  12085. /*!
  12086. Returns the graph with \a index. If the index is invalid, returns \c nullptr.
  12087. There is an overloaded version of this function with no parameter which returns the last created
  12088. graph, see QCustomPlot::graph()
  12089. \see graphCount, addGraph
  12090. */
  12091. QCPGraph *QCustomPlot::graph(int index) const
  12092. {
  12093. if (index >= 0 && index < mGraphs.size())
  12094. {
  12095. return mGraphs.at(index);
  12096. } else
  12097. {
  12098. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12099. return nullptr;
  12100. }
  12101. }
  12102. /*! \overload
  12103. Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot,
  12104. returns \c nullptr.
  12105. \see graphCount, addGraph
  12106. */
  12107. QCPGraph *QCustomPlot::graph() const
  12108. {
  12109. if (!mGraphs.isEmpty())
  12110. {
  12111. return mGraphs.last();
  12112. } else
  12113. return nullptr;
  12114. }
  12115. /*!
  12116. Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the
  12117. bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a
  12118. keyAxis and \a valueAxis must reside in this QCustomPlot.
  12119. \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically
  12120. "y") for the graph.
  12121. Returns a pointer to the newly created graph, or \c nullptr if adding the graph failed.
  12122. \see graph, graphCount, removeGraph, clearGraphs
  12123. */
  12124. QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis)
  12125. {
  12126. if (!keyAxis) keyAxis = xAxis;
  12127. if (!valueAxis) valueAxis = yAxis;
  12128. if (!keyAxis || !valueAxis)
  12129. {
  12130. qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)";
  12131. return nullptr;
  12132. }
  12133. if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this)
  12134. {
  12135. qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent";
  12136. return nullptr;
  12137. }
  12138. QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis);
  12139. newGraph->setName(QLatin1String("Graph ")+QString::number(mGraphs.size()));
  12140. return newGraph;
  12141. }
  12142. /*!
  12143. Removes the specified \a graph from the plot and deletes it. If necessary, the corresponding
  12144. legend item is also removed from the default legend (QCustomPlot::legend). If any other graphs in
  12145. the plot have a channel fill set towards the removed graph, the channel fill property of those
  12146. graphs is reset to \c nullptr (no channel fill).
  12147. Returns true on success.
  12148. \see clearGraphs
  12149. */
  12150. bool QCustomPlot::removeGraph(QCPGraph *graph)
  12151. {
  12152. return removePlottable(graph);
  12153. }
  12154. /*! \overload
  12155. Removes and deletes the graph by its \a index.
  12156. */
  12157. bool QCustomPlot::removeGraph(int index)
  12158. {
  12159. if (index >= 0 && index < mGraphs.size())
  12160. return removeGraph(mGraphs[index]);
  12161. else
  12162. return false;
  12163. }
  12164. /*!
  12165. Removes all graphs from the plot and deletes them. Corresponding legend items are also removed
  12166. from the default legend (QCustomPlot::legend).
  12167. Returns the number of graphs removed.
  12168. \see removeGraph
  12169. */
  12170. int QCustomPlot::clearGraphs()
  12171. {
  12172. int c = mGraphs.size();
  12173. for (int i=c-1; i >= 0; --i)
  12174. removeGraph(mGraphs[i]);
  12175. return c;
  12176. }
  12177. /*!
  12178. Returns the number of currently existing graphs in the plot
  12179. \see graph, addGraph
  12180. */
  12181. int QCustomPlot::graphCount() const
  12182. {
  12183. return mGraphs.size();
  12184. }
  12185. /*!
  12186. Returns a list of the selected graphs. If no graphs are currently selected, the list is empty.
  12187. If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars,
  12188. etc., use \ref selectedPlottables.
  12189. \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelection
  12190. */
  12191. QList<QCPGraph*> QCustomPlot::selectedGraphs() const
  12192. {
  12193. QList<QCPGraph*> result;
  12194. foreach (QCPGraph *graph, mGraphs)
  12195. {
  12196. if (graph->selected())
  12197. result.append(graph);
  12198. }
  12199. return result;
  12200. }
  12201. /*!
  12202. Returns the item with \a index. If the index is invalid, returns \c nullptr.
  12203. There is an overloaded version of this function with no parameter which returns the last added
  12204. item, see QCustomPlot::item()
  12205. \see itemCount
  12206. */
  12207. QCPAbstractItem *QCustomPlot::item(int index) const
  12208. {
  12209. if (index >= 0 && index < mItems.size())
  12210. {
  12211. return mItems.at(index);
  12212. } else
  12213. {
  12214. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12215. return nullptr;
  12216. }
  12217. }
  12218. /*! \overload
  12219. Returns the last item that was added to this plot. If there are no items in the plot,
  12220. returns \c nullptr.
  12221. \see itemCount
  12222. */
  12223. QCPAbstractItem *QCustomPlot::item() const
  12224. {
  12225. if (!mItems.isEmpty())
  12226. {
  12227. return mItems.last();
  12228. } else
  12229. return nullptr;
  12230. }
  12231. /*!
  12232. Removes the specified item from the plot and deletes it.
  12233. Returns true on success.
  12234. \see clearItems
  12235. */
  12236. bool QCustomPlot::removeItem(QCPAbstractItem *item)
  12237. {
  12238. if (mItems.contains(item))
  12239. {
  12240. delete item;
  12241. mItems.removeOne(item);
  12242. return true;
  12243. } else
  12244. {
  12245. qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast<quintptr>(item);
  12246. return false;
  12247. }
  12248. }
  12249. /*! \overload
  12250. Removes and deletes the item by its \a index.
  12251. */
  12252. bool QCustomPlot::removeItem(int index)
  12253. {
  12254. if (index >= 0 && index < mItems.size())
  12255. return removeItem(mItems[index]);
  12256. else
  12257. {
  12258. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12259. return false;
  12260. }
  12261. }
  12262. /*!
  12263. Removes all items from the plot and deletes them.
  12264. Returns the number of items removed.
  12265. \see removeItem
  12266. */
  12267. int QCustomPlot::clearItems()
  12268. {
  12269. int c = mItems.size();
  12270. for (int i=c-1; i >= 0; --i)
  12271. removeItem(mItems[i]);
  12272. return c;
  12273. }
  12274. /*!
  12275. Returns the number of currently existing items in the plot
  12276. \see item
  12277. */
  12278. int QCustomPlot::itemCount() const
  12279. {
  12280. return mItems.size();
  12281. }
  12282. /*!
  12283. Returns a list of the selected items. If no items are currently selected, the list is empty.
  12284. \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected
  12285. */
  12286. QList<QCPAbstractItem*> QCustomPlot::selectedItems() const
  12287. {
  12288. QList<QCPAbstractItem*> result;
  12289. foreach (QCPAbstractItem *item, mItems)
  12290. {
  12291. if (item->selected())
  12292. result.append(item);
  12293. }
  12294. return result;
  12295. }
  12296. /*!
  12297. Returns the item at the pixel position \a pos. Since it can capture all items, the
  12298. return type is the abstract base class of all items, QCPAbstractItem.
  12299. For details, and if you wish to specify a certain item type (e.g. QCPItemLine), see the
  12300. template method itemAt<ItemType>()
  12301. \see itemAt<ItemType>(), plottableAt, layoutElementAt
  12302. */
  12303. QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const
  12304. {
  12305. return itemAt<QCPAbstractItem>(pos, onlySelectable);
  12306. }
  12307. /*!
  12308. Returns whether this QCustomPlot contains the \a item.
  12309. \see item
  12310. */
  12311. bool QCustomPlot::hasItem(QCPAbstractItem *item) const
  12312. {
  12313. return mItems.contains(item);
  12314. }
  12315. /*!
  12316. Returns the layer with the specified \a name. If there is no layer with the specified name, \c
  12317. nullptr is returned.
  12318. Layer names are case-sensitive.
  12319. \see addLayer, moveLayer, removeLayer
  12320. */
  12321. QCPLayer *QCustomPlot::layer(const QString &name) const
  12322. {
  12323. foreach (QCPLayer *layer, mLayers)
  12324. {
  12325. if (layer->name() == name)
  12326. return layer;
  12327. }
  12328. return nullptr;
  12329. }
  12330. /*! \overload
  12331. Returns the layer by \a index. If the index is invalid, \c nullptr is returned.
  12332. \see addLayer, moveLayer, removeLayer
  12333. */
  12334. QCPLayer *QCustomPlot::layer(int index) const
  12335. {
  12336. if (index >= 0 && index < mLayers.size())
  12337. {
  12338. return mLayers.at(index);
  12339. } else
  12340. {
  12341. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  12342. return nullptr;
  12343. }
  12344. }
  12345. /*!
  12346. Returns the layer that is set as current layer (see \ref setCurrentLayer).
  12347. */
  12348. QCPLayer *QCustomPlot::currentLayer() const
  12349. {
  12350. return mCurrentLayer;
  12351. }
  12352. /*!
  12353. Sets the layer with the specified \a name to be the current layer. All layerables (\ref
  12354. QCPLayerable), e.g. plottables and items, are created on the current layer.
  12355. Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot.
  12356. Layer names are case-sensitive.
  12357. \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer
  12358. */
  12359. bool QCustomPlot::setCurrentLayer(const QString &name)
  12360. {
  12361. if (QCPLayer *newCurrentLayer = layer(name))
  12362. {
  12363. return setCurrentLayer(newCurrentLayer);
  12364. } else
  12365. {
  12366. qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name;
  12367. return false;
  12368. }
  12369. }
  12370. /*! \overload
  12371. Sets the provided \a layer to be the current layer.
  12372. Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot.
  12373. \see addLayer, moveLayer, removeLayer
  12374. */
  12375. bool QCustomPlot::setCurrentLayer(QCPLayer *layer)
  12376. {
  12377. if (!mLayers.contains(layer))
  12378. {
  12379. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  12380. return false;
  12381. }
  12382. mCurrentLayer = layer;
  12383. return true;
  12384. }
  12385. /*!
  12386. Returns the number of currently existing layers in the plot
  12387. \see layer, addLayer
  12388. */
  12389. int QCustomPlot::layerCount() const
  12390. {
  12391. return mLayers.size();
  12392. }
  12393. /*!
  12394. Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which
  12395. must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer.
  12396. Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a
  12397. valid layer inside this QCustomPlot.
  12398. If \a otherLayer is 0, the highest layer in the QCustomPlot will be used.
  12399. For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer.
  12400. \see layer, moveLayer, removeLayer
  12401. */
  12402. bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
  12403. {
  12404. if (!otherLayer)
  12405. otherLayer = mLayers.last();
  12406. if (!mLayers.contains(otherLayer))
  12407. {
  12408. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
  12409. return false;
  12410. }
  12411. if (layer(name))
  12412. {
  12413. qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name;
  12414. return false;
  12415. }
  12416. QCPLayer *newLayer = new QCPLayer(this, name);
  12417. mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer);
  12418. updateLayerIndices();
  12419. setupPaintBuffers(); // associates new layer with the appropriate paint buffer
  12420. return true;
  12421. }
  12422. /*!
  12423. Removes the specified \a layer and returns true on success.
  12424. All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below
  12425. \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both
  12426. cases, the total rendering order of all layerables in the QCustomPlot is preserved.
  12427. If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom
  12428. layer) becomes the new current layer.
  12429. It is not possible to remove the last layer of the plot.
  12430. \see layer, addLayer, moveLayer
  12431. */
  12432. bool QCustomPlot::removeLayer(QCPLayer *layer)
  12433. {
  12434. if (!mLayers.contains(layer))
  12435. {
  12436. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  12437. return false;
  12438. }
  12439. if (mLayers.size() < 2)
  12440. {
  12441. qDebug() << Q_FUNC_INFO << "can't remove last layer";
  12442. return false;
  12443. }
  12444. // append all children of this layer to layer below (if this is lowest layer, prepend to layer above)
  12445. int removedIndex = layer->index();
  12446. bool isFirstLayer = removedIndex==0;
  12447. QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1);
  12448. QList<QCPLayerable*> children = layer->children();
  12449. if (isFirstLayer) // prepend in reverse order (such that relative order stays the same)
  12450. std::reverse(children.begin(), children.end());
  12451. foreach (QCPLayerable *child, children)
  12452. child->moveToLayer(targetLayer, isFirstLayer); // prepend if isFirstLayer, otherwise append
  12453. // if removed layer is current layer, change current layer to layer below/above:
  12454. if (layer == mCurrentLayer)
  12455. setCurrentLayer(targetLayer);
  12456. // invalidate the paint buffer that was responsible for this layer:
  12457. if (QSharedPointer<QCPAbstractPaintBuffer> pb = layer->mPaintBuffer.toStrongRef())
  12458. pb->setInvalidated();
  12459. // remove layer:
  12460. delete layer;
  12461. mLayers.removeOne(layer);
  12462. updateLayerIndices();
  12463. return true;
  12464. }
  12465. /*!
  12466. Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or
  12467. below is controlled with \a insertMode.
  12468. Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the
  12469. QCustomPlot.
  12470. \see layer, addLayer, moveLayer
  12471. */
  12472. bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode)
  12473. {
  12474. if (!mLayers.contains(layer))
  12475. {
  12476. qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(layer);
  12477. return false;
  12478. }
  12479. if (!mLayers.contains(otherLayer))
  12480. {
  12481. qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast<quintptr>(otherLayer);
  12482. return false;
  12483. }
  12484. if (layer->index() > otherLayer->index())
  12485. mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0));
  12486. else if (layer->index() < otherLayer->index())
  12487. mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 0:-1));
  12488. // invalidate the paint buffers that are responsible for the layers:
  12489. if (QSharedPointer<QCPAbstractPaintBuffer> pb = layer->mPaintBuffer.toStrongRef())
  12490. pb->setInvalidated();
  12491. if (QSharedPointer<QCPAbstractPaintBuffer> pb = otherLayer->mPaintBuffer.toStrongRef())
  12492. pb->setInvalidated();
  12493. updateLayerIndices();
  12494. return true;
  12495. }
  12496. /*!
  12497. Returns the number of axis rects in the plot.
  12498. All axis rects can be accessed via QCustomPlot::axisRect().
  12499. Initially, only one axis rect exists in the plot.
  12500. \see axisRect, axisRects
  12501. */
  12502. int QCustomPlot::axisRectCount() const
  12503. {
  12504. return axisRects().size();
  12505. }
  12506. /*!
  12507. Returns the axis rect with \a index.
  12508. Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were
  12509. added, all of them may be accessed with this function in a linear fashion (even when they are
  12510. nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout).
  12511. The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding
  12512. them. For example, if the axis rects are in the top level grid layout (accessible via \ref
  12513. QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's
  12514. default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst
  12515. "foColumnsFirst" wasn't changed.
  12516. If you want to access axis rects by their row and column index, use the layout interface. For
  12517. example, use \ref QCPLayoutGrid::element of the top level grid layout, and \c qobject_cast the
  12518. returned layout element to \ref QCPAxisRect. (See also \ref thelayoutsystem.)
  12519. \see axisRectCount, axisRects, QCPLayoutGrid::setFillOrder
  12520. */
  12521. QCPAxisRect *QCustomPlot::axisRect(int index) const
  12522. {
  12523. const QList<QCPAxisRect*> rectList = axisRects();
  12524. if (index >= 0 && index < rectList.size())
  12525. {
  12526. return rectList.at(index);
  12527. } else
  12528. {
  12529. qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index;
  12530. return nullptr;
  12531. }
  12532. }
  12533. /*!
  12534. Returns all axis rects in the plot.
  12535. The order of the axis rects is given by the fill order of the \ref QCPLayout that is holding
  12536. them. For example, if the axis rects are in the top level grid layout (accessible via \ref
  12537. QCustomPlot::plotLayout), they are ordered from left to right, top to bottom, if the layout's
  12538. default \ref QCPLayoutGrid::setFillOrder "setFillOrder" of \ref QCPLayoutGrid::foColumnsFirst
  12539. "foColumnsFirst" wasn't changed.
  12540. \see axisRectCount, axisRect, QCPLayoutGrid::setFillOrder
  12541. */
  12542. QList<QCPAxisRect*> QCustomPlot::axisRects() const
  12543. {
  12544. QList<QCPAxisRect*> result;
  12545. QStack<QCPLayoutElement*> elementStack;
  12546. if (mPlotLayout)
  12547. elementStack.push(mPlotLayout);
  12548. while (!elementStack.isEmpty())
  12549. {
  12550. foreach (QCPLayoutElement *element, elementStack.pop()->elements(false))
  12551. {
  12552. if (element)
  12553. {
  12554. elementStack.push(element);
  12555. if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(element))
  12556. result.append(ar);
  12557. }
  12558. }
  12559. }
  12560. return result;
  12561. }
  12562. /*!
  12563. Returns the layout element at pixel position \a pos. If there is no element at that position,
  12564. returns \c nullptr.
  12565. Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on
  12566. any of its parent elements is set to false, it will not be considered.
  12567. \see itemAt, plottableAt
  12568. */
  12569. QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const
  12570. {
  12571. QCPLayoutElement *currentElement = mPlotLayout;
  12572. bool searchSubElements = true;
  12573. while (searchSubElements && currentElement)
  12574. {
  12575. searchSubElements = false;
  12576. foreach (QCPLayoutElement *subElement, currentElement->elements(false))
  12577. {
  12578. if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
  12579. {
  12580. currentElement = subElement;
  12581. searchSubElements = true;
  12582. break;
  12583. }
  12584. }
  12585. }
  12586. return currentElement;
  12587. }
  12588. /*!
  12589. Returns the layout element of type \ref QCPAxisRect at pixel position \a pos. This method ignores
  12590. other layout elements even if they are visually in front of the axis rect (e.g. a \ref
  12591. QCPLegend). If there is no axis rect at that position, returns \c nullptr.
  12592. Only visible axis rects are used. If \ref QCPLayoutElement::setVisible on the axis rect itself or
  12593. on any of its parent elements is set to false, it will not be considered.
  12594. \see layoutElementAt
  12595. */
  12596. QCPAxisRect *QCustomPlot::axisRectAt(const QPointF &pos) const
  12597. {
  12598. QCPAxisRect *result = nullptr;
  12599. QCPLayoutElement *currentElement = mPlotLayout;
  12600. bool searchSubElements = true;
  12601. while (searchSubElements && currentElement)
  12602. {
  12603. searchSubElements = false;
  12604. foreach (QCPLayoutElement *subElement, currentElement->elements(false))
  12605. {
  12606. if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0)
  12607. {
  12608. currentElement = subElement;
  12609. searchSubElements = true;
  12610. if (QCPAxisRect *ar = qobject_cast<QCPAxisRect*>(currentElement))
  12611. result = ar;
  12612. break;
  12613. }
  12614. }
  12615. }
  12616. return result;
  12617. }
  12618. /*!
  12619. Returns the axes that currently have selected parts, i.e. whose selection state is not \ref
  12620. QCPAxis::spNone.
  12621. \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts,
  12622. QCPAxis::setSelectableParts
  12623. */
  12624. QList<QCPAxis*> QCustomPlot::selectedAxes() const
  12625. {
  12626. QList<QCPAxis*> result, allAxes;
  12627. foreach (QCPAxisRect *rect, axisRects())
  12628. allAxes << rect->axes();
  12629. foreach (QCPAxis *axis, allAxes)
  12630. {
  12631. if (axis->selectedParts() != QCPAxis::spNone)
  12632. result.append(axis);
  12633. }
  12634. return result;
  12635. }
  12636. /*!
  12637. Returns the legends that currently have selected parts, i.e. whose selection state is not \ref
  12638. QCPLegend::spNone.
  12639. \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts,
  12640. QCPLegend::setSelectableParts, QCPLegend::selectedItems
  12641. */
  12642. QList<QCPLegend*> QCustomPlot::selectedLegends() const
  12643. {
  12644. QList<QCPLegend*> result;
  12645. QStack<QCPLayoutElement*> elementStack;
  12646. if (mPlotLayout)
  12647. elementStack.push(mPlotLayout);
  12648. while (!elementStack.isEmpty())
  12649. {
  12650. foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false))
  12651. {
  12652. if (subElement)
  12653. {
  12654. elementStack.push(subElement);
  12655. if (QCPLegend *leg = qobject_cast<QCPLegend*>(subElement))
  12656. {
  12657. if (leg->selectedParts() != QCPLegend::spNone)
  12658. result.append(leg);
  12659. }
  12660. }
  12661. }
  12662. }
  12663. return result;
  12664. }
  12665. /*!
  12666. Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot.
  12667. Since calling this function is not a user interaction, this does not emit the \ref
  12668. selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the
  12669. objects were previously selected.
  12670. \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends
  12671. */
  12672. void QCustomPlot::deselectAll()
  12673. {
  12674. foreach (QCPLayer *layer, mLayers)
  12675. {
  12676. foreach (QCPLayerable *layerable, layer->children())
  12677. layerable->deselectEvent(nullptr);
  12678. }
  12679. }
  12680. /*!
  12681. Causes a complete replot into the internal paint buffer(s). Finally, the widget surface is
  12682. refreshed with the new buffer contents. This is the method that must be called to make changes to
  12683. the plot, e.g. on the axis ranges or data points of graphs, visible.
  12684. The parameter \a refreshPriority can be used to fine-tune the timing of the replot. For example
  12685. if your application calls \ref replot very quickly in succession (e.g. multiple independent
  12686. functions change some aspects of the plot and each wants to make sure the change gets replotted),
  12687. it is advisable to set \a refreshPriority to \ref QCustomPlot::rpQueuedReplot. This way, the
  12688. actual replotting is deferred to the next event loop iteration. Multiple successive calls of \ref
  12689. replot with this priority will only cause a single replot, avoiding redundant replots and
  12690. improving performance.
  12691. Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the
  12692. QCustomPlot widget and user interactions (object selection and range dragging/zooming).
  12693. Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref
  12694. afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two
  12695. signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite
  12696. recursion.
  12697. If a layer is in mode \ref QCPLayer::lmBuffered (\ref QCPLayer::setMode), it is also possible to
  12698. replot only that specific layer via \ref QCPLayer::replot. See the documentation there for
  12699. details.
  12700. \see replotTime
  12701. */
  12702. void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority)
  12703. {
  12704. if (refreshPriority == QCustomPlot::rpQueuedReplot)
  12705. {
  12706. if (!mReplotQueued)
  12707. {
  12708. mReplotQueued = true;
  12709. QTimer::singleShot(0, this, SLOT(replot()));
  12710. }
  12711. return;
  12712. }
  12713. if (mReplotting) // incase signals loop back to replot slot
  12714. return;
  12715. mReplotting = true;
  12716. mReplotQueued = false;
  12717. emit beforeReplot();
  12718. # if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
  12719. QTime replotTimer;
  12720. replotTimer.start();
  12721. # else
  12722. QElapsedTimer replotTimer;
  12723. replotTimer.start();
  12724. # endif
  12725. updateLayout();
  12726. // draw all layered objects (grid, axes, plottables, items, legend,...) into their buffers:
  12727. setupPaintBuffers();
  12728. foreach (QCPLayer *layer, mLayers)
  12729. layer->drawToPaintBuffer();
  12730. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  12731. buffer->setInvalidated(false);
  12732. if ((refreshPriority == rpRefreshHint && mPlottingHints.testFlag(QCP::phImmediateRefresh)) || refreshPriority==rpImmediateRefresh)
  12733. repaint();
  12734. else
  12735. update();
  12736. # if QT_VERSION < QT_VERSION_CHECK(4, 8, 0)
  12737. mReplotTime = replotTimer.elapsed();
  12738. # else
  12739. mReplotTime = replotTimer.nsecsElapsed()*1e-6;
  12740. # endif
  12741. if (!qFuzzyIsNull(mReplotTimeAverage))
  12742. mReplotTimeAverage = mReplotTimeAverage*0.9 + mReplotTime*0.1; // exponential moving average with a time constant of 10 last replots
  12743. else
  12744. mReplotTimeAverage = mReplotTime; // no previous replots to average with, so initialize with replot time
  12745. emit afterReplot();
  12746. mReplotting = false;
  12747. }
  12748. /*!
  12749. Returns the time in milliseconds that the last replot took. If \a average is set to true, an
  12750. exponential moving average over the last couple of replots is returned.
  12751. \see replot
  12752. */
  12753. double QCustomPlot::replotTime(bool average) const
  12754. {
  12755. return average ? mReplotTimeAverage : mReplotTime;
  12756. }
  12757. /*!
  12758. Rescales the axes such that all plottables (like graphs) in the plot are fully visible.
  12759. if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true
  12760. (QCPLayerable::setVisible), will be used to rescale the axes.
  12761. \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale
  12762. */
  12763. void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables)
  12764. {
  12765. QList<QCPAxis*> allAxes;
  12766. foreach (QCPAxisRect *rect, axisRects())
  12767. allAxes << rect->axes();
  12768. foreach (QCPAxis *axis, allAxes)
  12769. axis->rescale(onlyVisiblePlottables);
  12770. }
  12771. /*!
  12772. Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale
  12773. of texts and lines will be derived from the specified \a width and \a height. This means, the
  12774. output will look like the normal on-screen output of a QCustomPlot widget with the corresponding
  12775. pixel width and height. If either \a width or \a height is zero, the exported image will have the
  12776. same dimensions as the QCustomPlot widget currently has.
  12777. Setting \a exportPen to \ref QCP::epNoCosmetic allows to disable the use of cosmetic pens when
  12778. drawing to the PDF file. Cosmetic pens are pens with numerical width 0, which are always drawn as
  12779. a one pixel wide line, no matter what zoom factor is set in the PDF-Viewer. For more information
  12780. about cosmetic pens, see the QPainter and QPen documentation.
  12781. The objects of the plot will appear in the current selection state. If you don't want any
  12782. selected objects to be painted in their selected look, deselect everything with \ref deselectAll
  12783. before calling this function.
  12784. Returns true on success.
  12785. \warning
  12786. \li If you plan on editing the exported PDF file with a vector graphics editor like Inkscape, it
  12787. is advised to set \a exportPen to \ref QCP::epNoCosmetic to avoid losing those cosmetic lines
  12788. (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks).
  12789. \li If calling this function inside the constructor of the parent of the QCustomPlot widget
  12790. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12791. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12792. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12793. aren't defined yet inside the constructor, so you would get an image that has strange
  12794. widths/heights.
  12795. \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting
  12796. PDF file.
  12797. \note On Android systems, this method does nothing and issues an according qDebug warning
  12798. message. This is also the case if for other reasons the define flag \c QT_NO_PRINTER is set.
  12799. \see savePng, saveBmp, saveJpg, saveRastered
  12800. */
  12801. bool QCustomPlot::savePdf(const QString &fileName, int width, int height, QCP::ExportPen exportPen, const QString &pdfCreator, const QString &pdfTitle)
  12802. {
  12803. bool success = false;
  12804. #ifdef QT_NO_PRINTER
  12805. Q_UNUSED(fileName)
  12806. Q_UNUSED(exportPen)
  12807. Q_UNUSED(width)
  12808. Q_UNUSED(height)
  12809. Q_UNUSED(pdfCreator)
  12810. Q_UNUSED(pdfTitle)
  12811. qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created.";
  12812. #else
  12813. int newWidth, newHeight;
  12814. if (width == 0 || height == 0)
  12815. {
  12816. newWidth = this->width();
  12817. newHeight = this->height();
  12818. } else
  12819. {
  12820. newWidth = width;
  12821. newHeight = height;
  12822. }
  12823. QPrinter printer(QPrinter::ScreenResolution);
  12824. printer.setOutputFileName(fileName);
  12825. printer.setOutputFormat(QPrinter::PdfFormat);
  12826. printer.setColorMode(QPrinter::Color);
  12827. printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator);
  12828. printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle);
  12829. QRect oldViewport = viewport();
  12830. setViewport(QRect(0, 0, newWidth, newHeight));
  12831. #if QT_VERSION < QT_VERSION_CHECK(5, 3, 0)
  12832. printer.setFullPage(true);
  12833. printer.setPaperSize(viewport().size(), QPrinter::DevicePixel);
  12834. #else
  12835. QPageLayout pageLayout;
  12836. pageLayout.setMode(QPageLayout::FullPageMode);
  12837. pageLayout.setOrientation(QPageLayout::Portrait);
  12838. pageLayout.setMargins(QMarginsF(0, 0, 0, 0));
  12839. pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch));
  12840. printer.setPageLayout(pageLayout);
  12841. #endif
  12842. QCPPainter printpainter;
  12843. if (printpainter.begin(&printer))
  12844. {
  12845. printpainter.setMode(QCPPainter::pmVectorized);
  12846. printpainter.setMode(QCPPainter::pmNoCaching);
  12847. printpainter.setMode(QCPPainter::pmNonCosmetic, exportPen==QCP::ExportPen::epNoCosmetic);
  12848. printpainter.setWindow(mViewport);
  12849. if (mBackgroundBrush.style() != Qt::NoBrush &&
  12850. mBackgroundBrush.color() != Qt::white &&
  12851. mBackgroundBrush.color() != Qt::transparent &&
  12852. mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent
  12853. printpainter.fillRect(viewport(), mBackgroundBrush);
  12854. draw(&printpainter);
  12855. printpainter.end();
  12856. success = true;
  12857. }
  12858. setViewport(oldViewport);
  12859. #endif // QT_NO_PRINTER
  12860. return success;
  12861. }
  12862. /*!
  12863. Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width
  12864. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12865. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12866. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12867. parameter.
  12868. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12869. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12870. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12871. 200*200 pixel resolution.
  12872. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12873. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12874. QCustomPlot to place objects with sub-pixel accuracy.
  12875. image compression can be controlled with the \a quality parameter which must be between 0 and 100
  12876. or -1 to use the default setting.
  12877. The \a resolution will be written to the image file header and has no direct consequence for the
  12878. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12879. it will be able to scale the image to match either a given size in real units of length (inch,
  12880. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12881. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12882. resolution unit internally.
  12883. Returns true on success. If this function fails, most likely the PNG format isn't supported by
  12884. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12885. The objects of the plot will appear in the current selection state. If you don't want any selected
  12886. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12887. this function.
  12888. If you want the PNG to have a transparent background, call \ref setBackground(const QBrush &brush)
  12889. with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving.
  12890. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12891. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12892. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12893. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12894. aren't defined yet inside the constructor, so you would get an image that has strange
  12895. widths/heights.
  12896. \see savePdf, saveBmp, saveJpg, saveRastered
  12897. */
  12898. bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  12899. {
  12900. return saveRastered(fileName, width, height, scale, "PNG", quality, resolution, resolutionUnit);
  12901. }
  12902. /*!
  12903. Saves a JPEG image file to \a fileName on disc. The output plot will have the dimensions \a width
  12904. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12905. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12906. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12907. parameter.
  12908. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12909. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12910. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12911. 200*200 pixel resolution.
  12912. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12913. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12914. QCustomPlot to place objects with sub-pixel accuracy.
  12915. image compression can be controlled with the \a quality parameter which must be between 0 and 100
  12916. or -1 to use the default setting.
  12917. The \a resolution will be written to the image file header and has no direct consequence for the
  12918. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12919. it will be able to scale the image to match either a given size in real units of length (inch,
  12920. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12921. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12922. resolution unit internally.
  12923. Returns true on success. If this function fails, most likely the JPEG format isn't supported by
  12924. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12925. The objects of the plot will appear in the current selection state. If you don't want any selected
  12926. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12927. this function.
  12928. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12929. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12930. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12931. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12932. aren't defined yet inside the constructor, so you would get an image that has strange
  12933. widths/heights.
  12934. \see savePdf, savePng, saveBmp, saveRastered
  12935. */
  12936. bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  12937. {
  12938. return saveRastered(fileName, width, height, scale, "JPG", quality, resolution, resolutionUnit);
  12939. }
  12940. /*!
  12941. Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width
  12942. and \a height in pixels, multiplied by \a scale. If either \a width or \a height is zero, the
  12943. current width and height of the QCustomPlot widget is used instead. Line widths and texts etc.
  12944. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale
  12945. parameter.
  12946. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an
  12947. image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths,
  12948. texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full
  12949. 200*200 pixel resolution.
  12950. If you use a high scaling factor, it is recommended to enable antialiasing for all elements by
  12951. temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows
  12952. QCustomPlot to place objects with sub-pixel accuracy.
  12953. The \a resolution will be written to the image file header and has no direct consequence for the
  12954. quality or the pixel size. However, if opening the image with a tool which respects the metadata,
  12955. it will be able to scale the image to match either a given size in real units of length (inch,
  12956. centimeters, etc.), or the target display DPI. You can specify in which units \a resolution is
  12957. given, by setting \a resolutionUnit. The \a resolution is converted to the format's expected
  12958. resolution unit internally.
  12959. Returns true on success. If this function fails, most likely the BMP format isn't supported by
  12960. the system, see Qt docs about QImageWriter::supportedImageFormats().
  12961. The objects of the plot will appear in the current selection state. If you don't want any selected
  12962. objects to be painted in their selected look, deselect everything with \ref deselectAll before calling
  12963. this function.
  12964. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget
  12965. (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide
  12966. explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this
  12967. function uses the current width and height of the QCustomPlot widget. However, in Qt, these
  12968. aren't defined yet inside the constructor, so you would get an image that has strange
  12969. widths/heights.
  12970. \see savePdf, savePng, saveJpg, saveRastered
  12971. */
  12972. bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale, int resolution, QCP::ResolutionUnit resolutionUnit)
  12973. {
  12974. return saveRastered(fileName, width, height, scale, "BMP", -1, resolution, resolutionUnit);
  12975. }
  12976. /*! \internal
  12977. Returns a minimum size hint that corresponds to the minimum size of the top level layout
  12978. (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum
  12979. size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot.
  12980. This is especially important, when placed in a QLayout where other components try to take in as
  12981. much space as possible (e.g. QMdiArea).
  12982. */
  12983. QSize QCustomPlot::minimumSizeHint() const
  12984. {
  12985. return mPlotLayout->minimumOuterSizeHint();
  12986. }
  12987. /*! \internal
  12988. Returns a size hint that is the same as \ref minimumSizeHint.
  12989. */
  12990. QSize QCustomPlot::sizeHint() const
  12991. {
  12992. return mPlotLayout->minimumOuterSizeHint();
  12993. }
  12994. /*! \internal
  12995. Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but
  12996. draws the internal buffer on the widget surface.
  12997. */
  12998. void QCustomPlot::paintEvent(QPaintEvent *event)
  12999. {
  13000. Q_UNUSED(event)
  13001. QCPPainter painter(this);
  13002. if (painter.isActive())
  13003. {
  13004. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  13005. painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem
  13006. #endif
  13007. if (mBackgroundBrush.style() != Qt::NoBrush)
  13008. painter.fillRect(mViewport, mBackgroundBrush);
  13009. drawBackground(&painter);
  13010. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  13011. buffer->draw(&painter);
  13012. }
  13013. }
  13014. /*! \internal
  13015. Event handler for a resize of the QCustomPlot widget. The viewport (which becomes the outer rect
  13016. of mPlotLayout) is resized appropriately. Finally a \ref replot is performed.
  13017. */
  13018. void QCustomPlot::resizeEvent(QResizeEvent *event)
  13019. {
  13020. Q_UNUSED(event)
  13021. // resize and repaint the buffer:
  13022. setViewport(rect());
  13023. replot(rpQueuedRefresh); // queued refresh is important here, to prevent painting issues in some contexts (e.g. MDI subwindow)
  13024. }
  13025. /*! \internal
  13026. Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then
  13027. determines the layerable under the cursor and forwards the event to it. Finally, emits the
  13028. specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref
  13029. axisDoubleClick, etc.).
  13030. \see mousePressEvent, mouseReleaseEvent
  13031. */
  13032. void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event)
  13033. {
  13034. emit mouseDoubleClick(event);
  13035. mMouseHasMoved = false;
  13036. mMousePressPos = event->pos();
  13037. // determine layerable under the cursor (this event is called instead of the second press event in a double-click):
  13038. QList<QVariant> details;
  13039. QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
  13040. for (int i=0; i<candidates.size(); ++i)
  13041. {
  13042. event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
  13043. candidates.at(i)->mouseDoubleClickEvent(event, details.at(i));
  13044. if (event->isAccepted())
  13045. {
  13046. mMouseEventLayerable = candidates.at(i);
  13047. mMouseEventLayerableDetails = details.at(i);
  13048. break;
  13049. }
  13050. }
  13051. // emit specialized object double click signals:
  13052. if (!candidates.isEmpty())
  13053. {
  13054. if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(candidates.first()))
  13055. {
  13056. int dataIndex = 0;
  13057. if (!details.first().value<QCPDataSelection>().isEmpty())
  13058. dataIndex = details.first().value<QCPDataSelection>().dataRange().begin();
  13059. emit plottableDoubleClick(ap, dataIndex, event);
  13060. } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(candidates.first()))
  13061. emit axisDoubleClick(ax, details.first().value<QCPAxis::SelectablePart>(), event);
  13062. else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(candidates.first()))
  13063. emit itemDoubleClick(ai, event);
  13064. else if (QCPLegend *lg = qobject_cast<QCPLegend*>(candidates.first()))
  13065. emit legendDoubleClick(lg, nullptr, event);
  13066. else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(candidates.first()))
  13067. emit legendDoubleClick(li->parentLegend(), li, event);
  13068. }
  13069. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13070. }
  13071. /*! \internal
  13072. Event handler for when a mouse button is pressed. Emits the mousePress signal.
  13073. If the current \ref setSelectionRectMode is not \ref QCP::srmNone, passes the event to the
  13074. selection rect. Otherwise determines the layerable under the cursor and forwards the event to it.
  13075. \see mouseMoveEvent, mouseReleaseEvent
  13076. */
  13077. void QCustomPlot::mousePressEvent(QMouseEvent *event)
  13078. {
  13079. emit mousePress(event);
  13080. // save some state to tell in releaseEvent whether it was a click:
  13081. mMouseHasMoved = false;
  13082. mMousePressPos = event->pos();
  13083. if (mSelectionRect && mSelectionRectMode != QCP::srmNone)
  13084. {
  13085. if (mSelectionRectMode != QCP::srmZoom || qobject_cast<QCPAxisRect*>(axisRectAt(mMousePressPos))) // in zoom mode only activate selection rect if on an axis rect
  13086. mSelectionRect->startSelection(event);
  13087. } else
  13088. {
  13089. // no selection rect interaction, prepare for click signal emission and forward event to layerable under the cursor:
  13090. QList<QVariant> details;
  13091. QList<QCPLayerable*> candidates = layerableListAt(mMousePressPos, false, &details);
  13092. if (!candidates.isEmpty())
  13093. {
  13094. mMouseSignalLayerable = candidates.first(); // candidate for signal emission is always topmost hit layerable (signal emitted in release event)
  13095. mMouseSignalLayerableDetails = details.first();
  13096. }
  13097. // forward event to topmost candidate which accepts the event:
  13098. for (int i=0; i<candidates.size(); ++i)
  13099. {
  13100. event->accept(); // default impl of QCPLayerable's mouse events call ignore() on the event, in that case propagate to next candidate in list
  13101. candidates.at(i)->mousePressEvent(event, details.at(i));
  13102. if (event->isAccepted())
  13103. {
  13104. mMouseEventLayerable = candidates.at(i);
  13105. mMouseEventLayerableDetails = details.at(i);
  13106. break;
  13107. }
  13108. }
  13109. }
  13110. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13111. }
  13112. /*! \internal
  13113. Event handler for when the cursor is moved. Emits the \ref mouseMove signal.
  13114. If the selection rect (\ref setSelectionRect) is currently active, the event is forwarded to it
  13115. in order to update the rect geometry.
  13116. Otherwise, if a layout element has mouse capture focus (a mousePressEvent happened on top of the
  13117. layout element before), the mouseMoveEvent is forwarded to that element.
  13118. \see mousePressEvent, mouseReleaseEvent
  13119. */
  13120. void QCustomPlot::mouseMoveEvent(QMouseEvent *event)
  13121. {
  13122. emit mouseMove(event);
  13123. if (!mMouseHasMoved && (mMousePressPos-event->pos()).manhattanLength() > 3)
  13124. mMouseHasMoved = true; // moved too far from mouse press position, don't handle as click on mouse release
  13125. if (mSelectionRect && mSelectionRect->isActive())
  13126. mSelectionRect->moveSelection(event);
  13127. else if (mMouseEventLayerable) // call event of affected layerable:
  13128. mMouseEventLayerable->mouseMoveEvent(event, mMousePressPos);
  13129. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13130. }
  13131. /*! \internal
  13132. Event handler for when a mouse button is released. Emits the \ref mouseRelease signal.
  13133. If the mouse was moved less than a certain threshold in any direction since the \ref
  13134. mousePressEvent, it is considered a click which causes the selection mechanism (if activated via
  13135. \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse
  13136. click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.)
  13137. If a layerable is the mouse capturer (a \ref mousePressEvent happened on top of the layerable
  13138. before), the \ref mouseReleaseEvent is forwarded to that element.
  13139. \see mousePressEvent, mouseMoveEvent
  13140. */
  13141. void QCustomPlot::mouseReleaseEvent(QMouseEvent *event)
  13142. {
  13143. emit mouseRelease(event);
  13144. if (!mMouseHasMoved) // mouse hasn't moved (much) between press and release, so handle as click
  13145. {
  13146. if (mSelectionRect && mSelectionRect->isActive()) // a simple click shouldn't successfully finish a selection rect, so cancel it here
  13147. mSelectionRect->cancel();
  13148. if (event->button() == Qt::LeftButton)
  13149. processPointSelection(event);
  13150. // emit specialized click signals of QCustomPlot instance:
  13151. if (QCPAbstractPlottable *ap = qobject_cast<QCPAbstractPlottable*>(mMouseSignalLayerable))
  13152. {
  13153. int dataIndex = 0;
  13154. if (!mMouseSignalLayerableDetails.value<QCPDataSelection>().isEmpty())
  13155. dataIndex = mMouseSignalLayerableDetails.value<QCPDataSelection>().dataRange().begin();
  13156. emit plottableClick(ap, dataIndex, event);
  13157. } else if (QCPAxis *ax = qobject_cast<QCPAxis*>(mMouseSignalLayerable))
  13158. emit axisClick(ax, mMouseSignalLayerableDetails.value<QCPAxis::SelectablePart>(), event);
  13159. else if (QCPAbstractItem *ai = qobject_cast<QCPAbstractItem*>(mMouseSignalLayerable))
  13160. emit itemClick(ai, event);
  13161. else if (QCPLegend *lg = qobject_cast<QCPLegend*>(mMouseSignalLayerable))
  13162. emit legendClick(lg, nullptr, event);
  13163. else if (QCPAbstractLegendItem *li = qobject_cast<QCPAbstractLegendItem*>(mMouseSignalLayerable))
  13164. emit legendClick(li->parentLegend(), li, event);
  13165. mMouseSignalLayerable = nullptr;
  13166. }
  13167. if (mSelectionRect && mSelectionRect->isActive()) // Note: if a click was detected above, the selection rect is canceled there
  13168. {
  13169. // finish selection rect, the appropriate action will be taken via signal-slot connection:
  13170. mSelectionRect->endSelection(event);
  13171. } else
  13172. {
  13173. // call event of affected layerable:
  13174. if (mMouseEventLayerable)
  13175. {
  13176. mMouseEventLayerable->mouseReleaseEvent(event, mMousePressPos);
  13177. mMouseEventLayerable = nullptr;
  13178. }
  13179. }
  13180. if (noAntialiasingOnDrag())
  13181. replot(rpQueuedReplot);
  13182. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13183. }
  13184. /*! \internal
  13185. Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then
  13186. determines the affected layerable and forwards the event to it.
  13187. */
  13188. void QCustomPlot::wheelEvent(QWheelEvent *event)
  13189. {
  13190. emit mouseWheel(event);
  13191. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  13192. const QPointF pos = event->pos();
  13193. #else
  13194. const QPointF pos = event->position();
  13195. #endif
  13196. // forward event to layerable under cursor:
  13197. foreach (QCPLayerable *candidate, layerableListAt(pos, false))
  13198. {
  13199. event->accept(); // default impl of QCPLayerable's mouse events ignore the event, in that case propagate to next candidate in list
  13200. candidate->wheelEvent(event);
  13201. if (event->isAccepted())
  13202. break;
  13203. }
  13204. event->accept(); // in case QCPLayerable reimplementation manipulates event accepted state. In QWidget event system, QCustomPlot wants to accept the event.
  13205. }
  13206. /*! \internal
  13207. This function draws the entire plot, including background pixmap, with the specified \a painter.
  13208. It does not make use of the paint buffers like \ref replot, so this is the function typically
  13209. used by saving/exporting methods such as \ref savePdf or \ref toPainter.
  13210. Note that it does not fill the background with the background brush (as the user may specify with
  13211. \ref setBackground(const QBrush &brush)), this is up to the respective functions calling this
  13212. method.
  13213. */
  13214. void QCustomPlot::draw(QCPPainter *painter)
  13215. {
  13216. updateLayout();
  13217. // draw viewport background pixmap:
  13218. drawBackground(painter);
  13219. // draw all layered objects (grid, axes, plottables, items, legend,...):
  13220. foreach (QCPLayer *layer, mLayers)
  13221. layer->draw(painter);
  13222. /* Debug code to draw all layout element rects
  13223. foreach (QCPLayoutElement *el, findChildren<QCPLayoutElement*>())
  13224. {
  13225. painter->setBrush(Qt::NoBrush);
  13226. painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine));
  13227. painter->drawRect(el->rect());
  13228. painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine));
  13229. painter->drawRect(el->outerRect());
  13230. }
  13231. */
  13232. }
  13233. /*! \internal
  13234. Performs the layout update steps defined by \ref QCPLayoutElement::UpdatePhase, by calling \ref
  13235. QCPLayoutElement::update on the main plot layout.
  13236. Here, the layout elements calculate their positions and margins, and prepare for the following
  13237. draw call.
  13238. */
  13239. void QCustomPlot::updateLayout()
  13240. {
  13241. // run through layout phases:
  13242. mPlotLayout->update(QCPLayoutElement::upPreparation);
  13243. mPlotLayout->update(QCPLayoutElement::upMargins);
  13244. mPlotLayout->update(QCPLayoutElement::upLayout);
  13245. emit afterLayout();
  13246. }
  13247. /*! \internal
  13248. Draws the viewport background pixmap of the plot.
  13249. If a pixmap was provided via \ref setBackground, this function buffers the scaled version
  13250. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  13251. the viewport with the provided \a painter. The scaled version is buffered in
  13252. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  13253. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  13254. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  13255. set.
  13256. Note that this function does not draw a fill with the background brush
  13257. (\ref setBackground(const QBrush &brush)) beneath the pixmap.
  13258. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  13259. */
  13260. void QCustomPlot::drawBackground(QCPPainter *painter)
  13261. {
  13262. // Note: background color is handled in individual replot/save functions
  13263. // draw background pixmap (on top of fill, if brush specified):
  13264. if (!mBackgroundPixmap.isNull())
  13265. {
  13266. if (mBackgroundScaled)
  13267. {
  13268. // check whether mScaledBackground needs to be updated:
  13269. QSize scaledSize(mBackgroundPixmap.size());
  13270. scaledSize.scale(mViewport.size(), mBackgroundScaledMode);
  13271. if (mScaledBackgroundPixmap.size() != scaledSize)
  13272. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  13273. painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect());
  13274. } else
  13275. {
  13276. painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()));
  13277. }
  13278. }
  13279. }
  13280. /*! \internal
  13281. Goes through the layers and makes sure this QCustomPlot instance holds the correct number of
  13282. paint buffers and that they have the correct configuration (size, pixel ratio, etc.).
  13283. Allocations, reallocations and deletions of paint buffers are performed as necessary. It also
  13284. associates the paint buffers with the layers, so they draw themselves into the right buffer when
  13285. \ref QCPLayer::drawToPaintBuffer is called. This means it associates adjacent \ref
  13286. QCPLayer::lmLogical layers to a mutual paint buffer and creates dedicated paint buffers for
  13287. layers in \ref QCPLayer::lmBuffered mode.
  13288. This method uses \ref createPaintBuffer to create new paint buffers.
  13289. After this method, the paint buffers are empty (filled with \c Qt::transparent) and invalidated
  13290. (so an attempt to replot only a single buffered layer causes a full replot).
  13291. This method is called in every \ref replot call, prior to actually drawing the layers (into their
  13292. associated paint buffer). If the paint buffers don't need changing/reallocating, this method
  13293. basically leaves them alone and thus finishes very fast.
  13294. */
  13295. void QCustomPlot::setupPaintBuffers()
  13296. {
  13297. int bufferIndex = 0;
  13298. if (mPaintBuffers.isEmpty())
  13299. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  13300. for (int layerIndex = 0; layerIndex < mLayers.size(); ++layerIndex)
  13301. {
  13302. QCPLayer *layer = mLayers.at(layerIndex);
  13303. if (layer->mode() == QCPLayer::lmLogical)
  13304. {
  13305. layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
  13306. } else if (layer->mode() == QCPLayer::lmBuffered)
  13307. {
  13308. ++bufferIndex;
  13309. if (bufferIndex >= mPaintBuffers.size())
  13310. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  13311. layer->mPaintBuffer = mPaintBuffers.at(bufferIndex).toWeakRef();
  13312. 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
  13313. {
  13314. ++bufferIndex;
  13315. if (bufferIndex >= mPaintBuffers.size())
  13316. mPaintBuffers.append(QSharedPointer<QCPAbstractPaintBuffer>(createPaintBuffer()));
  13317. }
  13318. }
  13319. }
  13320. // remove unneeded buffers:
  13321. while (mPaintBuffers.size()-1 > bufferIndex)
  13322. mPaintBuffers.removeLast();
  13323. // resize buffers to viewport size and clear contents:
  13324. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  13325. {
  13326. buffer->setSize(viewport().size()); // won't do anything if already correct size
  13327. buffer->clear(Qt::transparent);
  13328. buffer->setInvalidated();
  13329. }
  13330. }
  13331. /*! \internal
  13332. This method is used by \ref setupPaintBuffers when it needs to create new paint buffers.
  13333. Depending on the current setting of \ref setOpenGl, and the current Qt version, different
  13334. backends (subclasses of \ref QCPAbstractPaintBuffer) are created, initialized with the proper
  13335. size and device pixel ratio, and returned.
  13336. */
  13337. QCPAbstractPaintBuffer *QCustomPlot::createPaintBuffer()
  13338. {
  13339. if (mOpenGl)
  13340. {
  13341. #if defined(QCP_OPENGL_FBO)
  13342. return new QCPPaintBufferGlFbo(viewport().size(), mBufferDevicePixelRatio, mGlContext, mGlPaintDevice);
  13343. #elif defined(QCP_OPENGL_PBUFFER)
  13344. return new QCPPaintBufferGlPbuffer(viewport().size(), mBufferDevicePixelRatio, mOpenGlMultisamples);
  13345. #else
  13346. 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.";
  13347. return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
  13348. #endif
  13349. } else
  13350. return new QCPPaintBufferPixmap(viewport().size(), mBufferDevicePixelRatio);
  13351. }
  13352. /*!
  13353. This method returns whether any of the paint buffers held by this QCustomPlot instance are
  13354. invalidated.
  13355. If any buffer is invalidated, a partial replot (\ref QCPLayer::replot) is not allowed and always
  13356. causes a full replot (\ref QCustomPlot::replot) of all layers. This is the case when for example
  13357. the layer order has changed, new layers were added or removed, layer modes were changed (\ref
  13358. QCPLayer::setMode), or layerables were added or removed.
  13359. \see QCPAbstractPaintBuffer::setInvalidated
  13360. */
  13361. bool QCustomPlot::hasInvalidatedPaintBuffers()
  13362. {
  13363. foreach (QSharedPointer<QCPAbstractPaintBuffer> buffer, mPaintBuffers)
  13364. {
  13365. if (buffer->invalidated())
  13366. return true;
  13367. }
  13368. return false;
  13369. }
  13370. /*! \internal
  13371. When \ref setOpenGl is set to true, this method is used to initialize OpenGL (create a context,
  13372. surface, paint device).
  13373. Returns true on success.
  13374. If this method is successful, all paint buffers should be deleted and then reallocated by calling
  13375. \ref setupPaintBuffers, so the OpenGL-based paint buffer subclasses (\ref
  13376. QCPPaintBufferGlPbuffer, \ref QCPPaintBufferGlFbo) are used for subsequent replots.
  13377. \see freeOpenGl
  13378. */
  13379. bool QCustomPlot::setupOpenGl()
  13380. {
  13381. #ifdef QCP_OPENGL_FBO
  13382. freeOpenGl();
  13383. QSurfaceFormat proposedSurfaceFormat;
  13384. proposedSurfaceFormat.setSamples(mOpenGlMultisamples);
  13385. #ifdef QCP_OPENGL_OFFSCREENSURFACE
  13386. QOffscreenSurface *surface = new QOffscreenSurface;
  13387. #else
  13388. QWindow *surface = new QWindow;
  13389. surface->setSurfaceType(QSurface::OpenGLSurface);
  13390. #endif
  13391. surface->setFormat(proposedSurfaceFormat);
  13392. surface->create();
  13393. mGlSurface = QSharedPointer<QSurface>(surface);
  13394. mGlContext = QSharedPointer<QOpenGLContext>(new QOpenGLContext);
  13395. mGlContext->setFormat(mGlSurface->format());
  13396. if (!mGlContext->create())
  13397. {
  13398. qDebug() << Q_FUNC_INFO << "Failed to create OpenGL context";
  13399. mGlContext.clear();
  13400. mGlSurface.clear();
  13401. return false;
  13402. }
  13403. if (!mGlContext->makeCurrent(mGlSurface.data())) // context needs to be current to create paint device
  13404. {
  13405. qDebug() << Q_FUNC_INFO << "Failed to make opengl context current";
  13406. mGlContext.clear();
  13407. mGlSurface.clear();
  13408. return false;
  13409. }
  13410. if (!QOpenGLFramebufferObject::hasOpenGLFramebufferObjects())
  13411. {
  13412. qDebug() << Q_FUNC_INFO << "OpenGL of this system doesn't support frame buffer objects";
  13413. mGlContext.clear();
  13414. mGlSurface.clear();
  13415. return false;
  13416. }
  13417. mGlPaintDevice = QSharedPointer<QOpenGLPaintDevice>(new QOpenGLPaintDevice);
  13418. return true;
  13419. #elif defined(QCP_OPENGL_PBUFFER)
  13420. return QGLFormat::hasOpenGL();
  13421. #else
  13422. return false;
  13423. #endif
  13424. }
  13425. /*! \internal
  13426. When \ref setOpenGl is set to false, this method is used to deinitialize OpenGL (releases the
  13427. context and frees resources).
  13428. After OpenGL is disabled, all paint buffers should be deleted and then reallocated by calling
  13429. \ref setupPaintBuffers, so the standard software rendering paint buffer subclass (\ref
  13430. QCPPaintBufferPixmap) is used for subsequent replots.
  13431. \see setupOpenGl
  13432. */
  13433. void QCustomPlot::freeOpenGl()
  13434. {
  13435. #ifdef QCP_OPENGL_FBO
  13436. mGlPaintDevice.clear();
  13437. mGlContext.clear();
  13438. mGlSurface.clear();
  13439. #endif
  13440. }
  13441. /*! \internal
  13442. This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot
  13443. so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly.
  13444. */
  13445. void QCustomPlot::axisRemoved(QCPAxis *axis)
  13446. {
  13447. if (xAxis == axis)
  13448. xAxis = nullptr;
  13449. if (xAxis2 == axis)
  13450. xAxis2 = nullptr;
  13451. if (yAxis == axis)
  13452. yAxis = nullptr;
  13453. if (yAxis2 == axis)
  13454. yAxis2 = nullptr;
  13455. // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers
  13456. }
  13457. /*! \internal
  13458. This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so
  13459. it may clear its QCustomPlot::legend member accordingly.
  13460. */
  13461. void QCustomPlot::legendRemoved(QCPLegend *legend)
  13462. {
  13463. if (this->legend == legend)
  13464. this->legend = nullptr;
  13465. }
  13466. /*! \internal
  13467. This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
  13468. setSelectionRectMode is set to \ref QCP::srmSelect.
  13469. First, it determines which axis rect was the origin of the selection rect judging by the starting
  13470. point of the selection. Then it goes through the plottables (\ref QCPAbstractPlottable1D to be
  13471. precise) associated with that axis rect and finds the data points that are in \a rect. It does
  13472. this by querying their \ref QCPAbstractPlottable1D::selectTestRect method.
  13473. Then, the actual selection is done by calling the plottables' \ref
  13474. QCPAbstractPlottable::selectEvent, placing the found selected data points in the \a details
  13475. parameter as <tt>QVariant(\ref QCPDataSelection)</tt>. All plottables that weren't touched by \a
  13476. rect receive a \ref QCPAbstractPlottable::deselectEvent.
  13477. \see processRectZoom
  13478. */
  13479. void QCustomPlot::processRectSelection(QRect rect, QMouseEvent *event)
  13480. {
  13481. typedef QPair<QCPAbstractPlottable*, QCPDataSelection> SelectionCandidate;
  13482. typedef QMultiMap<int, SelectionCandidate> SelectionCandidates; // map key is number of selected data points, so we have selections sorted by size
  13483. bool selectionStateChanged = false;
  13484. if (mInteractions.testFlag(QCP::iSelectPlottables))
  13485. {
  13486. SelectionCandidates potentialSelections;
  13487. QRectF rectF(rect.normalized());
  13488. if (QCPAxisRect *affectedAxisRect = axisRectAt(rectF.topLeft()))
  13489. {
  13490. // determine plottables that were hit by the rect and thus are candidates for selection:
  13491. foreach (QCPAbstractPlottable *plottable, affectedAxisRect->plottables())
  13492. {
  13493. if (QCPPlottableInterface1D *plottableInterface = plottable->interface1D())
  13494. {
  13495. QCPDataSelection dataSel = plottableInterface->selectTestRect(rectF, true);
  13496. if (!dataSel.isEmpty())
  13497. potentialSelections.insert(dataSel.dataPointCount(), SelectionCandidate(plottable, dataSel));
  13498. }
  13499. }
  13500. if (!mInteractions.testFlag(QCP::iMultiSelect))
  13501. {
  13502. // only leave plottable with most selected points in map, since we will only select a single plottable:
  13503. if (!potentialSelections.isEmpty())
  13504. {
  13505. SelectionCandidates::iterator it = potentialSelections.begin();
  13506. while (it != std::prev(potentialSelections.end())) // erase all except last element
  13507. it = potentialSelections.erase(it);
  13508. }
  13509. }
  13510. bool additive = event->modifiers().testFlag(mMultiSelectModifier);
  13511. // deselect all other layerables if not additive selection:
  13512. if (!additive)
  13513. {
  13514. // emit deselection except to those plottables who will be selected afterwards:
  13515. foreach (QCPLayer *layer, mLayers)
  13516. {
  13517. foreach (QCPLayerable *layerable, layer->children())
  13518. {
  13519. if ((potentialSelections.isEmpty() || potentialSelections.constBegin()->first != layerable) && mInteractions.testFlag(layerable->selectionCategory()))
  13520. {
  13521. bool selChanged = false;
  13522. layerable->deselectEvent(&selChanged);
  13523. selectionStateChanged |= selChanged;
  13524. }
  13525. }
  13526. }
  13527. }
  13528. // go through selections in reverse (largest selection first) and emit select events:
  13529. SelectionCandidates::const_iterator it = potentialSelections.constEnd();
  13530. while (it != potentialSelections.constBegin())
  13531. {
  13532. --it;
  13533. if (mInteractions.testFlag(it.value().first->selectionCategory()))
  13534. {
  13535. bool selChanged = false;
  13536. it.value().first->selectEvent(event, additive, QVariant::fromValue(it.value().second), &selChanged);
  13537. selectionStateChanged |= selChanged;
  13538. }
  13539. }
  13540. }
  13541. }
  13542. if (selectionStateChanged)
  13543. {
  13544. emit selectionChangedByUser();
  13545. replot(rpQueuedReplot);
  13546. } else if (mSelectionRect)
  13547. mSelectionRect->layer()->replot();
  13548. }
  13549. /*! \internal
  13550. This slot is connected to the selection rect's \ref QCPSelectionRect::accepted signal when \ref
  13551. setSelectionRectMode is set to \ref QCP::srmZoom.
  13552. It determines which axis rect was the origin of the selection rect judging by the starting point
  13553. of the selection, and then zooms the axes defined via \ref QCPAxisRect::setRangeZoomAxes to the
  13554. provided \a rect (see \ref QCPAxisRect::zoom).
  13555. \see processRectSelection
  13556. */
  13557. void QCustomPlot::processRectZoom(QRect rect, QMouseEvent *event)
  13558. {
  13559. Q_UNUSED(event)
  13560. if (QCPAxisRect *axisRect = axisRectAt(rect.topLeft()))
  13561. {
  13562. QList<QCPAxis*> affectedAxes = QList<QCPAxis*>() << axisRect->rangeZoomAxes(Qt::Horizontal) << axisRect->rangeZoomAxes(Qt::Vertical);
  13563. affectedAxes.removeAll(static_cast<QCPAxis*>(nullptr));
  13564. axisRect->zoom(QRectF(rect), affectedAxes);
  13565. }
  13566. replot(rpQueuedReplot); // always replot to make selection rect disappear
  13567. }
  13568. /*! \internal
  13569. This method is called when a simple left mouse click was detected on the QCustomPlot surface.
  13570. It first determines the layerable that was hit by the click, and then calls its \ref
  13571. QCPLayerable::selectEvent. All other layerables receive a QCPLayerable::deselectEvent (unless the
  13572. multi-select modifier was pressed, see \ref setMultiSelectModifier).
  13573. In this method the hit layerable is determined a second time using \ref layerableAt (after the
  13574. one in \ref mousePressEvent), because we want \a onlySelectable set to true this time. This
  13575. implies that the mouse event grabber (mMouseEventLayerable) may be a different one from the
  13576. clicked layerable determined here. For example, if a non-selectable layerable is in front of a
  13577. selectable layerable at the click position, the front layerable will receive mouse events but the
  13578. selectable one in the back will receive the \ref QCPLayerable::selectEvent.
  13579. \see processRectSelection, QCPLayerable::selectTest
  13580. */
  13581. void QCustomPlot::processPointSelection(QMouseEvent *event)
  13582. {
  13583. QVariant details;
  13584. QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details);
  13585. bool selectionStateChanged = false;
  13586. bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier);
  13587. // deselect all other layerables if not additive selection:
  13588. if (!additive)
  13589. {
  13590. foreach (QCPLayer *layer, mLayers)
  13591. {
  13592. foreach (QCPLayerable *layerable, layer->children())
  13593. {
  13594. if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory()))
  13595. {
  13596. bool selChanged = false;
  13597. layerable->deselectEvent(&selChanged);
  13598. selectionStateChanged |= selChanged;
  13599. }
  13600. }
  13601. }
  13602. }
  13603. if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory()))
  13604. {
  13605. // a layerable was actually clicked, call its selectEvent:
  13606. bool selChanged = false;
  13607. clickedLayerable->selectEvent(event, additive, details, &selChanged);
  13608. selectionStateChanged |= selChanged;
  13609. }
  13610. if (selectionStateChanged)
  13611. {
  13612. emit selectionChangedByUser();
  13613. replot(rpQueuedReplot);
  13614. }
  13615. }
  13616. /*! \internal
  13617. Registers the specified plottable with this QCustomPlot and, if \ref setAutoAddPlottableToLegend
  13618. is enabled, adds it to the legend (QCustomPlot::legend). QCustomPlot takes ownership of the
  13619. plottable.
  13620. Returns true on success, i.e. when \a plottable isn't already in this plot and the parent plot of
  13621. \a plottable is this QCustomPlot.
  13622. This method is called automatically in the QCPAbstractPlottable base class constructor.
  13623. */
  13624. bool QCustomPlot::registerPlottable(QCPAbstractPlottable *plottable)
  13625. {
  13626. if (mPlottables.contains(plottable))
  13627. {
  13628. qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast<quintptr>(plottable);
  13629. return false;
  13630. }
  13631. if (plottable->parentPlot() != this)
  13632. {
  13633. qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(plottable);
  13634. return false;
  13635. }
  13636. mPlottables.append(plottable);
  13637. // possibly add plottable to legend:
  13638. if (mAutoAddPlottableToLegend)
  13639. plottable->addToLegend();
  13640. if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
  13641. plottable->setLayer(currentLayer());
  13642. return true;
  13643. }
  13644. /*! \internal
  13645. In order to maintain the simplified graph interface of QCustomPlot, this method is called by the
  13646. QCPGraph constructor to register itself with this QCustomPlot's internal graph list. Returns true
  13647. on success, i.e. if \a graph is valid and wasn't already registered with this QCustomPlot.
  13648. This graph specific registration happens in addition to the call to \ref registerPlottable by the
  13649. QCPAbstractPlottable base class.
  13650. */
  13651. bool QCustomPlot::registerGraph(QCPGraph *graph)
  13652. {
  13653. if (!graph)
  13654. {
  13655. qDebug() << Q_FUNC_INFO << "passed graph is zero";
  13656. return false;
  13657. }
  13658. if (mGraphs.contains(graph))
  13659. {
  13660. qDebug() << Q_FUNC_INFO << "graph already registered with this QCustomPlot";
  13661. return false;
  13662. }
  13663. mGraphs.append(graph);
  13664. return true;
  13665. }
  13666. /*! \internal
  13667. Registers the specified item with this QCustomPlot. QCustomPlot takes ownership of the item.
  13668. Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a
  13669. item is this QCustomPlot.
  13670. This method is called automatically in the QCPAbstractItem base class constructor.
  13671. */
  13672. bool QCustomPlot::registerItem(QCPAbstractItem *item)
  13673. {
  13674. if (mItems.contains(item))
  13675. {
  13676. qDebug() << Q_FUNC_INFO << "item already added to this QCustomPlot:" << reinterpret_cast<quintptr>(item);
  13677. return false;
  13678. }
  13679. if (item->parentPlot() != this)
  13680. {
  13681. qDebug() << Q_FUNC_INFO << "item not created with this QCustomPlot as parent:" << reinterpret_cast<quintptr>(item);
  13682. return false;
  13683. }
  13684. mItems.append(item);
  13685. if (!item->layer()) // usually the layer is already set in the constructor of the item (via QCPLayerable constructor)
  13686. item->setLayer(currentLayer());
  13687. return true;
  13688. }
  13689. /*! \internal
  13690. Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called
  13691. after every operation that changes the layer indices, like layer removal, layer creation, layer
  13692. moving.
  13693. */
  13694. void QCustomPlot::updateLayerIndices() const
  13695. {
  13696. for (int i=0; i<mLayers.size(); ++i)
  13697. mLayers.at(i)->mIndex = i;
  13698. }
  13699. /*! \internal
  13700. Returns the top-most layerable at pixel position \a pos. If \a onlySelectable is set to true,
  13701. only those layerables that are selectable will be considered. (Layerable subclasses communicate
  13702. their selectability via the QCPLayerable::selectTest method, by returning -1.)
  13703. \a selectionDetails is an output parameter that contains selection specifics of the affected
  13704. layerable. This is useful if the respective layerable shall be given a subsequent
  13705. QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
  13706. information about which part of the layerable was hit, in multi-part layerables (e.g.
  13707. QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
  13708. QCPDataSelection instance with the single data point which is closest to \a pos.
  13709. \see layerableListAt, layoutElementAt, axisRectAt
  13710. */
  13711. QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const
  13712. {
  13713. QList<QVariant> details;
  13714. QList<QCPLayerable*> candidates = layerableListAt(pos, onlySelectable, selectionDetails ? &details : nullptr);
  13715. if (selectionDetails && !details.isEmpty())
  13716. *selectionDetails = details.first();
  13717. if (!candidates.isEmpty())
  13718. return candidates.first();
  13719. else
  13720. return nullptr;
  13721. }
  13722. /*! \internal
  13723. Returns the layerables at pixel position \a pos. If \a onlySelectable is set to true, only those
  13724. layerables that are selectable will be considered. (Layerable subclasses communicate their
  13725. selectability via the QCPLayerable::selectTest method, by returning -1.)
  13726. The returned list is sorted by the layerable/drawing order such that the layerable that appears
  13727. on top in the plot is at index 0 of the returned list. If you only need to know the top
  13728. layerable, rather use \ref layerableAt.
  13729. \a selectionDetails is an output parameter that contains selection specifics of the affected
  13730. layerable. This is useful if the respective layerable shall be given a subsequent
  13731. QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains
  13732. information about which part of the layerable was hit, in multi-part layerables (e.g.
  13733. QCPAxis::SelectablePart). If the layerable is a plottable, \a selectionDetails contains a \ref
  13734. QCPDataSelection instance with the single data point which is closest to \a pos.
  13735. \see layerableAt, layoutElementAt, axisRectAt
  13736. */
  13737. QList<QCPLayerable*> QCustomPlot::layerableListAt(const QPointF &pos, bool onlySelectable, QList<QVariant> *selectionDetails) const
  13738. {
  13739. QList<QCPLayerable*> result;
  13740. for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex)
  13741. {
  13742. const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
  13743. for (int i=layerables.size()-1; i>=0; --i)
  13744. {
  13745. if (!layerables.at(i)->realVisibility())
  13746. continue;
  13747. QVariant details;
  13748. double dist = layerables.at(i)->selectTest(pos, onlySelectable, selectionDetails ? &details : nullptr);
  13749. if (dist >= 0 && dist < selectionTolerance())
  13750. {
  13751. result.append(layerables.at(i));
  13752. if (selectionDetails)
  13753. selectionDetails->append(details);
  13754. }
  13755. }
  13756. }
  13757. return result;
  13758. }
  13759. /*!
  13760. Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is
  13761. sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead
  13762. to a full resolution file with width 200.) If the \a format supports compression, \a quality may
  13763. be between 0 and 100 to control it.
  13764. Returns true on success. If this function fails, most likely the given \a format isn't supported
  13765. by the system, see Qt docs about QImageWriter::supportedImageFormats().
  13766. The \a resolution will be written to the image file header (if the file format supports this) and
  13767. has no direct consequence for the quality or the pixel size. However, if opening the image with a
  13768. tool which respects the metadata, it will be able to scale the image to match either a given size
  13769. in real units of length (inch, centimeters, etc.), or the target display DPI. You can specify in
  13770. which units \a resolution is given, by setting \a resolutionUnit. The \a resolution is converted
  13771. to the format's expected resolution unit internally.
  13772. \see saveBmp, saveJpg, savePng, savePdf
  13773. */
  13774. bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality, int resolution, QCP::ResolutionUnit resolutionUnit)
  13775. {
  13776. QImage buffer = toPixmap(width, height, scale).toImage();
  13777. int dotsPerMeter = 0;
  13778. switch (resolutionUnit)
  13779. {
  13780. case QCP::ruDotsPerMeter: dotsPerMeter = resolution; break;
  13781. case QCP::ruDotsPerCentimeter: dotsPerMeter = resolution*100; break;
  13782. case QCP::ruDotsPerInch: dotsPerMeter = int(resolution/0.0254); break;
  13783. }
  13784. buffer.setDotsPerMeterX(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
  13785. buffer.setDotsPerMeterY(dotsPerMeter); // this is saved together with some image formats, e.g. PNG, and is relevant when opening image in other tools
  13786. if (!buffer.isNull())
  13787. return buffer.save(fileName, format, quality);
  13788. else
  13789. return false;
  13790. }
  13791. /*!
  13792. Renders the plot to a pixmap and returns it.
  13793. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and
  13794. scale 2.0 lead to a full resolution pixmap with width 200.)
  13795. \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf
  13796. */
  13797. QPixmap QCustomPlot::toPixmap(int width, int height, double scale)
  13798. {
  13799. // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too.
  13800. int newWidth, newHeight;
  13801. if (width == 0 || height == 0)
  13802. {
  13803. newWidth = this->width();
  13804. newHeight = this->height();
  13805. } else
  13806. {
  13807. newWidth = width;
  13808. newHeight = height;
  13809. }
  13810. int scaledWidth = qRound(scale*newWidth);
  13811. int scaledHeight = qRound(scale*newHeight);
  13812. QPixmap result(scaledWidth, scaledHeight);
  13813. result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later
  13814. QCPPainter painter;
  13815. painter.begin(&result);
  13816. if (painter.isActive())
  13817. {
  13818. QRect oldViewport = viewport();
  13819. setViewport(QRect(0, 0, newWidth, newHeight));
  13820. painter.setMode(QCPPainter::pmNoCaching);
  13821. if (!qFuzzyCompare(scale, 1.0))
  13822. {
  13823. if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales
  13824. painter.setMode(QCPPainter::pmNonCosmetic);
  13825. painter.scale(scale, scale);
  13826. }
  13827. if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) // solid fills were done a few lines above with QPixmap::fill
  13828. painter.fillRect(mViewport, mBackgroundBrush);
  13829. draw(&painter);
  13830. setViewport(oldViewport);
  13831. painter.end();
  13832. } else // might happen if pixmap has width or height zero
  13833. {
  13834. qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap";
  13835. return QPixmap();
  13836. }
  13837. return result;
  13838. }
  13839. /*!
  13840. Renders the plot using the passed \a painter.
  13841. 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
  13842. appear scaled accordingly.
  13843. \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter
  13844. on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with
  13845. the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter.
  13846. \see toPixmap
  13847. */
  13848. void QCustomPlot::toPainter(QCPPainter *painter, int width, int height)
  13849. {
  13850. // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too.
  13851. int newWidth, newHeight;
  13852. if (width == 0 || height == 0)
  13853. {
  13854. newWidth = this->width();
  13855. newHeight = this->height();
  13856. } else
  13857. {
  13858. newWidth = width;
  13859. newHeight = height;
  13860. }
  13861. if (painter->isActive())
  13862. {
  13863. QRect oldViewport = viewport();
  13864. setViewport(QRect(0, 0, newWidth, newHeight));
  13865. painter->setMode(QCPPainter::pmNoCaching);
  13866. 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
  13867. painter->fillRect(mViewport, mBackgroundBrush);
  13868. draw(painter);
  13869. setViewport(oldViewport);
  13870. } else
  13871. qDebug() << Q_FUNC_INFO << "Passed painter is not active";
  13872. }
  13873. /* end of 'src/core.cpp' */
  13874. /* including file 'src/colorgradient.cpp' */
  13875. /* modified 2021-03-29T02:30:44, size 25278 */
  13876. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13877. //////////////////// QCPColorGradient
  13878. ////////////////////////////////////////////////////////////////////////////////////////////////////
  13879. /*! \class QCPColorGradient
  13880. \brief Defines a color gradient for use with e.g. \ref QCPColorMap
  13881. This class describes a color gradient which can be used to encode data with color. For example,
  13882. QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which
  13883. take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color)
  13884. with a \a position from 0 to 1. In between these defined color positions, the
  13885. color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation.
  13886. Alternatively, load one of the preset color gradients shown in the image below, with \ref
  13887. loadPreset, or by directly specifying the preset in the constructor.
  13888. Apart from red, green and blue components, the gradient also interpolates the alpha values of the
  13889. configured color stops. This allows to display some portions of the data range as transparent in
  13890. the plot.
  13891. How NaN values are interpreted can be configured with \ref setNanHandling.
  13892. \image html QCPColorGradient.png
  13893. The constructor \ref QCPColorGradient(GradientPreset preset) allows directly converting a \ref
  13894. GradientPreset to a QCPColorGradient. This means that you can directly pass \ref GradientPreset
  13895. to all the \a setGradient methods, e.g.:
  13896. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorgradient-setgradient
  13897. The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the
  13898. color gradient shall be applied periodically (wrapping around) to data values that lie outside
  13899. the data range specified on the plottable instance can be controlled with \ref setPeriodic.
  13900. */
  13901. /*!
  13902. Constructs a new, empty QCPColorGradient with no predefined color stops. You can add own color
  13903. stops with \ref setColorStopAt.
  13904. The color level count is initialized to 350.
  13905. */
  13906. QCPColorGradient::QCPColorGradient() :
  13907. mLevelCount(350),
  13908. mColorInterpolation(ColorInterpolation::ciRGB),
  13909. mNanHandling(NanHandling::nhNone),
  13910. mNanColor(Qt::black),
  13911. mPeriodic(false),
  13912. mColorBufferInvalidated(true)
  13913. {
  13914. mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
  13915. }
  13916. /*!
  13917. Constructs a new QCPColorGradient initialized with the colors and color interpolation according
  13918. to \a preset.
  13919. The color level count is initialized to 350.
  13920. */
  13921. QCPColorGradient::QCPColorGradient(GradientPreset preset) :
  13922. mLevelCount(350),
  13923. mColorInterpolation(ColorInterpolation::ciRGB),
  13924. mNanHandling(NanHandling::nhNone),
  13925. mNanColor(Qt::black),
  13926. mPeriodic(false),
  13927. mColorBufferInvalidated(true)
  13928. {
  13929. mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount);
  13930. loadPreset(preset);
  13931. }
  13932. /* undocumented operator */
  13933. bool QCPColorGradient::operator==(const QCPColorGradient &other) const
  13934. {
  13935. return ((other.mLevelCount == this->mLevelCount) &&
  13936. (other.mColorInterpolation == this->mColorInterpolation) &&
  13937. (other.mNanHandling == this ->mNanHandling) &&
  13938. (other.mNanColor == this->mNanColor) &&
  13939. (other.mPeriodic == this->mPeriodic) &&
  13940. (other.mColorStops == this->mColorStops));
  13941. }
  13942. /*!
  13943. Sets the number of discretization levels of the color gradient to \a n. The default is 350 which
  13944. is typically enough to create a smooth appearance. The minimum number of levels is 2.
  13945. \image html QCPColorGradient-levelcount.png
  13946. */
  13947. void QCPColorGradient::setLevelCount(int n)
  13948. {
  13949. if (n < 2)
  13950. {
  13951. qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n;
  13952. n = 2;
  13953. }
  13954. if (n != mLevelCount)
  13955. {
  13956. mLevelCount = n;
  13957. mColorBufferInvalidated = true;
  13958. }
  13959. }
  13960. /*!
  13961. Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the
  13962. colors are the values of the passed QMap \a colorStops. In between these color stops, the color
  13963. is interpolated according to \ref setColorInterpolation.
  13964. A more convenient way to create a custom gradient may be to clear all color stops with \ref
  13965. clearColorStops (or creating a new, empty QCPColorGradient) and then adding them one by one with
  13966. \ref setColorStopAt.
  13967. \see clearColorStops
  13968. */
  13969. void QCPColorGradient::setColorStops(const QMap<double, QColor> &colorStops)
  13970. {
  13971. mColorStops = colorStops;
  13972. mColorBufferInvalidated = true;
  13973. }
  13974. /*!
  13975. Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between
  13976. these color stops, the color is interpolated according to \ref setColorInterpolation.
  13977. \see setColorStops, clearColorStops
  13978. */
  13979. void QCPColorGradient::setColorStopAt(double position, const QColor &color)
  13980. {
  13981. mColorStops.insert(position, color);
  13982. mColorBufferInvalidated = true;
  13983. }
  13984. /*!
  13985. Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be
  13986. interpolated linearly in RGB or in HSV color space.
  13987. For example, a sweep in RGB space from red to green will have a muddy brown intermediate color,
  13988. whereas in HSV space the intermediate color is yellow.
  13989. */
  13990. void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation)
  13991. {
  13992. if (interpolation != mColorInterpolation)
  13993. {
  13994. mColorInterpolation = interpolation;
  13995. mColorBufferInvalidated = true;
  13996. }
  13997. }
  13998. /*!
  13999. Sets how NaNs in the data are displayed in the plot.
  14000. \see setNanColor
  14001. */
  14002. void QCPColorGradient::setNanHandling(QCPColorGradient::NanHandling handling)
  14003. {
  14004. mNanHandling = handling;
  14005. }
  14006. /*!
  14007. Sets the color that NaN data is represented by, if \ref setNanHandling is set
  14008. to ref nhNanColor.
  14009. \see setNanHandling
  14010. */
  14011. void QCPColorGradient::setNanColor(const QColor &color)
  14012. {
  14013. mNanColor = color;
  14014. }
  14015. /*!
  14016. Sets whether data points that are outside the configured data range (e.g. \ref
  14017. QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether
  14018. they all have the same color, corresponding to the respective gradient boundary color.
  14019. \image html QCPColorGradient-periodic.png
  14020. As shown in the image above, gradients that have the same start and end color are especially
  14021. suitable for a periodic gradient mapping, since they produce smooth color transitions throughout
  14022. the color map. A preset that has this property is \ref gpHues.
  14023. In practice, using periodic color gradients makes sense when the data corresponds to a periodic
  14024. dimension, such as an angle or a phase. If this is not the case, the color encoding might become
  14025. ambiguous, because multiple different data values are shown as the same color.
  14026. */
  14027. void QCPColorGradient::setPeriodic(bool enabled)
  14028. {
  14029. mPeriodic = enabled;
  14030. }
  14031. /*! \overload
  14032. This method is used to quickly convert a \a data array to colors. The colors will be output in
  14033. the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this
  14034. function. The data range that shall be used for mapping the data value to the gradient is passed
  14035. in \a range. \a logarithmic indicates whether the data values shall be mapped to colors
  14036. logarithmically.
  14037. if \a data actually contains 2D-data linearized via <tt>[row*columnCount + column]</tt>, you can
  14038. set \a dataIndexFactor to <tt>columnCount</tt> to convert a column instead of a row of the data
  14039. array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data
  14040. is addressed <tt>data[i*dataIndexFactor]</tt>.
  14041. Use the overloaded method to additionally provide alpha map data.
  14042. The QRgb values that are placed in \a scanLine have their r, g, and b components premultiplied
  14043. with alpha (see QImage::Format_ARGB32_Premultiplied).
  14044. */
  14045. void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
  14046. {
  14047. // If you change something here, make sure to also adapt color() and the other colorize() overload
  14048. if (!data)
  14049. {
  14050. qDebug() << Q_FUNC_INFO << "null pointer given as data";
  14051. return;
  14052. }
  14053. if (!scanLine)
  14054. {
  14055. qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
  14056. return;
  14057. }
  14058. if (mColorBufferInvalidated)
  14059. updateColorBuffer();
  14060. const bool skipNanCheck = mNanHandling == NanHandling::nhNone;
  14061. const double posToIndexFactor = !logarithmic ? (mLevelCount-1.0)/range.size() : (mLevelCount-1.0)/qLn(range.upper/range.lower);
  14062. for (int i=0; i<n; ++i)
  14063. {
  14064. const double value = data[dataIndexFactor*i];
  14065. if (skipNanCheck || !std::isnan(value))
  14066. {
  14067. int index = int((!logarithmic ? value-range.lower : qLn(value/range.lower)) * posToIndexFactor);
  14068. if (!mPeriodic)
  14069. {
  14070. index = qBound(0, index, mLevelCount-1);
  14071. } else
  14072. {
  14073. index %= mLevelCount;
  14074. if (index < 0)
  14075. index += mLevelCount;
  14076. }
  14077. scanLine[i] = mColorBuffer.at(index);
  14078. } else
  14079. {
  14080. switch(mNanHandling)
  14081. {
  14082. case NanHandling::nhLowestColor: scanLine[i] = mColorBuffer.first(); break;
  14083. case NanHandling::nhHighestColor: scanLine[i] = mColorBuffer.last(); break;
  14084. case NanHandling::nhTransparent: scanLine[i] = qRgba(0, 0, 0, 0); break;
  14085. case NanHandling::nhNanColor: scanLine[i] = mNanColor.rgba(); break;
  14086. case NanHandling::nhNone: break; // shouldn't happen
  14087. }
  14088. }
  14089. }
  14090. }
  14091. /*! \overload
  14092. Additionally to the other overload of \ref colorize, this method takes the array \a alpha, which
  14093. has the same size and structure as \a data and encodes the alpha information per data point.
  14094. The QRgb values that are placed in \a scanLine have their r, g and b components premultiplied
  14095. with alpha (see QImage::Format_ARGB32_Premultiplied).
  14096. */
  14097. void QCPColorGradient::colorize(const double *data, const unsigned char *alpha, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic)
  14098. {
  14099. // If you change something here, make sure to also adapt color() and the other colorize() overload
  14100. if (!data)
  14101. {
  14102. qDebug() << Q_FUNC_INFO << "null pointer given as data";
  14103. return;
  14104. }
  14105. if (!alpha)
  14106. {
  14107. qDebug() << Q_FUNC_INFO << "null pointer given as alpha";
  14108. return;
  14109. }
  14110. if (!scanLine)
  14111. {
  14112. qDebug() << Q_FUNC_INFO << "null pointer given as scanLine";
  14113. return;
  14114. }
  14115. if (mColorBufferInvalidated)
  14116. updateColorBuffer();
  14117. const bool skipNanCheck = mNanHandling == NanHandling::nhNone;
  14118. const double posToIndexFactor = !logarithmic ? ((double)mLevelCount-1.0)/range.size() : ((double)mLevelCount-1.0)/qLn(range.upper/range.lower);
  14119. for (int i=0; i<n; ++i)
  14120. {
  14121. const double value = data[dataIndexFactor*i];
  14122. if (skipNanCheck || !std::isnan(value))
  14123. {
  14124. int index = int((!logarithmic ? value-range.lower : qLn(value/range.lower)) * posToIndexFactor);
  14125. if (!mPeriodic)
  14126. {
  14127. index = qBound(0, index, mLevelCount-1);
  14128. } else
  14129. {
  14130. index %= mLevelCount;
  14131. if (index < 0)
  14132. index += mLevelCount;
  14133. }
  14134. if (alpha[dataIndexFactor*i] == 255)
  14135. {
  14136. scanLine[i] = mColorBuffer.at(index);
  14137. } else
  14138. {
  14139. const QRgb rgb = mColorBuffer.at(index);
  14140. const float alphaF = alpha[dataIndexFactor*i]/255.0f;
  14141. 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
  14142. }
  14143. } else
  14144. {
  14145. switch(mNanHandling)
  14146. {
  14147. case NanHandling::nhLowestColor: scanLine[i] = mColorBuffer.first(); break;
  14148. case NanHandling::nhHighestColor: scanLine[i] = mColorBuffer.last(); break;
  14149. case NanHandling::nhTransparent: scanLine[i] = qRgba(0, 0, 0, 0); break;
  14150. case NanHandling::nhNanColor: scanLine[i] = mNanColor.rgba(); break;
  14151. case NanHandling::nhNone: break; // shouldn't happen
  14152. }
  14153. }
  14154. }
  14155. }
  14156. /*! \internal
  14157. This method is used to colorize a single data value given in \a position, to colors. The data
  14158. range that shall be used for mapping the data value to the gradient is passed in \a range. \a
  14159. logarithmic indicates whether the data value shall be mapped to a color logarithmically.
  14160. If an entire array of data values shall be converted, rather use \ref colorize, for better
  14161. performance.
  14162. The returned QRgb has its r, g and b components premultiplied with alpha (see
  14163. QImage::Format_ARGB32_Premultiplied).
  14164. */
  14165. QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic)
  14166. {
  14167. // If you change something here, make sure to also adapt ::colorize()
  14168. if (mColorBufferInvalidated)
  14169. updateColorBuffer();
  14170. const bool skipNanCheck = mNanHandling == NanHandling::nhNone;
  14171. if (!skipNanCheck && std::isnan(position))
  14172. {
  14173. switch(mNanHandling)
  14174. {
  14175. case NanHandling::nhLowestColor: return mColorBuffer.first();
  14176. case NanHandling::nhHighestColor: return mColorBuffer.last();
  14177. case NanHandling::nhTransparent: return qRgba(0, 0, 0, 0);
  14178. case NanHandling::nhNanColor: return mNanColor.rgba();
  14179. case NanHandling::nhNone: return qRgba(0, 0, 0, 0); // shouldn't happen
  14180. }
  14181. }
  14182. const double posToIndexFactor = !logarithmic ? ((double)mLevelCount-1.0)/ (double)range.size() : (mLevelCount-1)/qLn((double)range.upper/ (double)range.lower);
  14183. int index = int((!logarithmic ? (double)position-range.lower : qLn((double)position/ (double)range.lower)) * (double)posToIndexFactor);
  14184. if (!mPeriodic)
  14185. {
  14186. index = qBound(0, index, mLevelCount-1);
  14187. } else
  14188. {
  14189. index %= mLevelCount;
  14190. if (index < 0)
  14191. index += mLevelCount;
  14192. }
  14193. return mColorBuffer.at(index);
  14194. }
  14195. /*!
  14196. Clears the current color stops and loads the specified \a preset. A preset consists of predefined
  14197. color stops and the corresponding color interpolation method.
  14198. The available presets are:
  14199. \image html QCPColorGradient.png
  14200. */
  14201. void QCPColorGradient::loadPreset(GradientPreset preset)
  14202. {
  14203. clearColorStops();
  14204. switch (preset)
  14205. {
  14206. case GradientPreset::gpGrayscale:
  14207. setColorInterpolation(ColorInterpolation::ciRGB);
  14208. setColorStopAt(0, Qt::black);
  14209. setColorStopAt(1, Qt::white);
  14210. break;
  14211. case GradientPreset::gpHot:
  14212. setColorInterpolation(ColorInterpolation::ciRGB);
  14213. setColorStopAt(0, QColor(50, 0, 0));
  14214. setColorStopAt(0.2, QColor(180, 10, 0));
  14215. setColorStopAt(0.4, QColor(245, 50, 0));
  14216. setColorStopAt(0.6, QColor(255, 150, 10));
  14217. setColorStopAt(0.8, QColor(255, 255, 50));
  14218. setColorStopAt(1, QColor(255, 255, 255));
  14219. break;
  14220. case GradientPreset::gpCold:
  14221. setColorInterpolation(ColorInterpolation::ciRGB);
  14222. setColorStopAt(0, QColor(0, 0, 50));
  14223. setColorStopAt(0.2, QColor(0, 10, 180));
  14224. setColorStopAt(0.4, QColor(0, 50, 245));
  14225. setColorStopAt(0.6, QColor(10, 150, 255));
  14226. setColorStopAt(0.8, QColor(50, 255, 255));
  14227. setColorStopAt(1, QColor(255, 255, 255));
  14228. break;
  14229. case GradientPreset::gpNight:
  14230. setColorInterpolation(ColorInterpolation::ciHSV);
  14231. setColorStopAt(0, QColor(10, 20, 30));
  14232. setColorStopAt(1, QColor(250, 255, 250));
  14233. break;
  14234. case GradientPreset::gpCandy:
  14235. setColorInterpolation(ColorInterpolation::ciHSV);
  14236. setColorStopAt(0, QColor(0, 0, 255));
  14237. setColorStopAt(1, QColor(255, 250, 250));
  14238. break;
  14239. case GradientPreset::gpGeography:
  14240. setColorInterpolation(ColorInterpolation::ciRGB);
  14241. setColorStopAt(0, QColor(70, 170, 210));
  14242. setColorStopAt(0.20, QColor(90, 160, 180));
  14243. setColorStopAt(0.25, QColor(45, 130, 175));
  14244. setColorStopAt(0.30, QColor(100, 140, 125));
  14245. setColorStopAt(0.5, QColor(100, 140, 100));
  14246. setColorStopAt(0.6, QColor(130, 145, 120));
  14247. setColorStopAt(0.7, QColor(140, 130, 120));
  14248. setColorStopAt(0.9, QColor(180, 190, 190));
  14249. setColorStopAt(1, QColor(210, 210, 230));
  14250. break;
  14251. case GradientPreset::gpIon:
  14252. setColorInterpolation(ColorInterpolation::ciHSV);
  14253. setColorStopAt(0, QColor(50, 10, 10));
  14254. setColorStopAt(0.45, QColor(0, 0, 255));
  14255. setColorStopAt(0.8, QColor(0, 255, 255));
  14256. setColorStopAt(1, QColor(0, 255, 0));
  14257. break;
  14258. case GradientPreset::gpThermal:
  14259. setColorInterpolation(ColorInterpolation::ciRGB);
  14260. setColorStopAt(0, QColor(0, 0, 50));
  14261. setColorStopAt(0.15, QColor(20, 0, 120));
  14262. setColorStopAt(0.33, QColor(200, 30, 140));
  14263. setColorStopAt(0.6, QColor(255, 100, 0));
  14264. setColorStopAt(0.85, QColor(255, 255, 40));
  14265. setColorStopAt(1, QColor(255, 255, 255));
  14266. break;
  14267. case GradientPreset::gpPolar:
  14268. setColorInterpolation(ColorInterpolation::ciRGB);
  14269. setColorStopAt(0, QColor(50, 255, 255));
  14270. setColorStopAt(0.18, QColor(10, 70, 255));
  14271. setColorStopAt(0.28, QColor(10, 10, 190));
  14272. setColorStopAt(0.5, QColor(0, 0, 0));
  14273. setColorStopAt(0.72, QColor(190, 10, 10));
  14274. setColorStopAt(0.82, QColor(255, 70, 10));
  14275. setColorStopAt(1, QColor(255, 255, 50));
  14276. break;
  14277. case GradientPreset::gpSpectrum:
  14278. setColorInterpolation(ColorInterpolation::ciHSV);
  14279. setColorStopAt(0, QColor(50, 0, 50));
  14280. setColorStopAt(0.15, QColor(0, 0, 255));
  14281. setColorStopAt(0.35, QColor(0, 255, 255));
  14282. setColorStopAt(0.6, QColor(255, 255, 0));
  14283. setColorStopAt(0.75, QColor(255, 30, 0));
  14284. setColorStopAt(1, QColor(50, 0, 0));
  14285. break;
  14286. case GradientPreset::gpJet:
  14287. setColorInterpolation(ColorInterpolation::ciRGB);
  14288. setColorStopAt(0, QColor(0, 0, 100));
  14289. setColorStopAt(0.15, QColor(0, 50, 255));
  14290. setColorStopAt(0.35, QColor(0, 255, 255));
  14291. setColorStopAt(0.65, QColor(255, 255, 0));
  14292. setColorStopAt(0.85, QColor(255, 30, 0));
  14293. setColorStopAt(1, QColor(100, 0, 0));
  14294. break;
  14295. case GradientPreset::gpHues:
  14296. setColorInterpolation(ColorInterpolation::ciHSV);
  14297. setColorStopAt(0, QColor(255, 0, 0));
  14298. setColorStopAt(1.0/3.0, QColor(0, 0, 255));
  14299. setColorStopAt(2.0/3.0, QColor(0, 255, 0));
  14300. setColorStopAt(1, QColor(255, 0, 0));
  14301. break;
  14302. }
  14303. }
  14304. /*!
  14305. Clears all color stops.
  14306. \see setColorStops, setColorStopAt
  14307. */
  14308. void QCPColorGradient::clearColorStops()
  14309. {
  14310. mColorStops.clear();
  14311. mColorBufferInvalidated = true;
  14312. }
  14313. /*!
  14314. Returns an inverted gradient. The inverted gradient has all properties as this \ref
  14315. QCPColorGradient, but the order of the color stops is inverted.
  14316. \see setColorStops, setColorStopAt
  14317. */
  14318. QCPColorGradient QCPColorGradient::inverted() const
  14319. {
  14320. QCPColorGradient result(*this);
  14321. result.clearColorStops();
  14322. for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
  14323. result.setColorStopAt(1.0-it.key(), it.value());
  14324. return result;
  14325. }
  14326. /*! \internal
  14327. Returns true if the color gradient uses transparency, i.e. if any of the configured color stops
  14328. has an alpha value below 255.
  14329. */
  14330. bool QCPColorGradient::stopsUseAlpha() const
  14331. {
  14332. for (QMap<double, QColor>::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it)
  14333. {
  14334. if (it.value().alpha() < 255)
  14335. return true;
  14336. }
  14337. return false;
  14338. }
  14339. /*! \internal
  14340. Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly
  14341. convert positions to colors. This is where the interpolation between color stops is calculated.
  14342. */
  14343. void QCPColorGradient::updateColorBuffer()
  14344. {
  14345. if (mColorBuffer.size() != mLevelCount)
  14346. mColorBuffer.resize(mLevelCount);
  14347. if (mColorStops.size() > 1)
  14348. {
  14349. double indexToPosFactor = 1.0/double((double)mLevelCount -1.0);
  14350. const bool useAlpha = stopsUseAlpha();
  14351. for (int i=0; i<mLevelCount; ++i)
  14352. {
  14353. double position = i*indexToPosFactor;
  14354. QMap<double, QColor>::const_iterator it = mColorStops.lowerBound(position);
  14355. if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop
  14356. {
  14357. if (useAlpha)
  14358. {
  14359. const QColor col = std::prev(it).value();
  14360. const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied
  14361. mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier),
  14362. int(col.green()*alphaPremultiplier),
  14363. int(col.blue()*alphaPremultiplier),
  14364. col.alpha());
  14365. } else
  14366. mColorBuffer[i] = std::prev(it).value().rgba();
  14367. } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop
  14368. {
  14369. if (useAlpha)
  14370. {
  14371. const QColor &col = it.value();
  14372. const double alphaPremultiplier = col.alpha()/255.0; // since we use QImage::Format_ARGB32_Premultiplied
  14373. mColorBuffer[i] = qRgba(int(col.red()*alphaPremultiplier),
  14374. int(col.green()*alphaPremultiplier),
  14375. int(col.blue()*alphaPremultiplier),
  14376. col.alpha());
  14377. } else
  14378. mColorBuffer[i] = it.value().rgba();
  14379. } else // position is in between stops (or on an intermediate stop), interpolate color
  14380. {
  14381. QMap<double, QColor>::const_iterator high = it;
  14382. QMap<double, QColor>::const_iterator low = std::prev(it);
  14383. double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1
  14384. switch (mColorInterpolation)
  14385. {
  14386. case ColorInterpolation::ciRGB:
  14387. {
  14388. if (useAlpha)
  14389. {
  14390. const int alpha = int((1-t)*low.value().alpha() + t*high.value().alpha());
  14391. const double alphaPremultiplier = alpha/255.0; // since we use QImage::Format_ARGB32_Premultiplied
  14392. mColorBuffer[i] = qRgba(int( ((1-t)*low.value().red() + t*high.value().red())*alphaPremultiplier ),
  14393. int( ((1-t)*low.value().green() + t*high.value().green())*alphaPremultiplier ),
  14394. int( ((1-t)*low.value().blue() + t*high.value().blue())*alphaPremultiplier ),
  14395. alpha);
  14396. } else
  14397. {
  14398. mColorBuffer[i] = qRgb(int( ((1-t)*low.value().red() + t*high.value().red()) ),
  14399. int( ((1-t)*low.value().green() + t*high.value().green()) ),
  14400. int( ((1-t)*low.value().blue() + t*high.value().blue())) );
  14401. }
  14402. break;
  14403. }
  14404. case ColorInterpolation::ciHSV:
  14405. {
  14406. QColor lowHsv = low.value().toHsv();
  14407. QColor highHsv = high.value().toHsv();
  14408. double hue = 0;
  14409. double hueDiff = highHsv.hueF()-lowHsv.hueF();
  14410. if (hueDiff > 0.5)
  14411. hue = lowHsv.hueF() - t*(1.0-hueDiff);
  14412. else if (hueDiff < -0.5)
  14413. hue = lowHsv.hueF() + t*(1.0+hueDiff);
  14414. else
  14415. hue = lowHsv.hueF() + t*hueDiff;
  14416. if (hue < 0) hue += 1.0;
  14417. else if (hue >= 1.0) hue -= 1.0;
  14418. if (useAlpha)
  14419. {
  14420. const QRgb rgb = QColor::fromHsvF(hue,
  14421. (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
  14422. (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
  14423. const double alpha = (1-t)*lowHsv.alphaF() + t*highHsv.alphaF();
  14424. mColorBuffer[i] = qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha));
  14425. }
  14426. else
  14427. {
  14428. mColorBuffer[i] = QColor::fromHsvF(hue,
  14429. (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(),
  14430. (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb();
  14431. }
  14432. break;
  14433. }
  14434. }
  14435. }
  14436. }
  14437. } else if (mColorStops.size() == 1)
  14438. {
  14439. const QRgb rgb = mColorStops.constBegin().value().rgb();
  14440. const double alpha = mColorStops.constBegin().value().alphaF();
  14441. mColorBuffer.fill(qRgba(int(qRed(rgb)*alpha), int(qGreen(rgb)*alpha), int(qBlue(rgb)*alpha), int(255*alpha)));
  14442. } else // mColorStops is empty, fill color buffer with black
  14443. {
  14444. mColorBuffer.fill(qRgb(0, 0, 0));
  14445. }
  14446. mColorBufferInvalidated = false;
  14447. }
  14448. /* end of 'src/colorgradient.cpp' */
  14449. /* including file 'src/selectiondecorator-bracket.cpp' */
  14450. /* modified 2021-03-29T02:30:44, size 12308 */
  14451. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14452. //////////////////// QCPSelectionDecoratorBracket
  14453. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14454. /*! \class QCPSelectionDecoratorBracket
  14455. \brief A selection decorator which draws brackets around each selected data segment
  14456. Additionally to the regular highlighting of selected segments via color, fill and scatter style,
  14457. this \ref QCPSelectionDecorator subclass draws markers at the begin and end of each selected data
  14458. segment of the plottable.
  14459. The shape of the markers can be controlled with \ref setBracketStyle, \ref setBracketWidth and
  14460. \ref setBracketHeight. The color/fill can be controlled with \ref setBracketPen and \ref
  14461. setBracketBrush.
  14462. To introduce custom bracket styles, it is only necessary to sublcass \ref
  14463. QCPSelectionDecoratorBracket and reimplement \ref drawBracket. The rest will be managed by the
  14464. base class.
  14465. */
  14466. /*!
  14467. Creates a new QCPSelectionDecoratorBracket instance with default values.
  14468. */
  14469. QCPSelectionDecoratorBracket::QCPSelectionDecoratorBracket() :
  14470. mBracketPen(QPen(Qt::black)),
  14471. mBracketBrush(Qt::NoBrush),
  14472. mBracketWidth(5),
  14473. mBracketHeight(50),
  14474. mBracketStyle(bsSquareBracket),
  14475. mTangentToData(false),
  14476. mTangentAverage(2)
  14477. {
  14478. }
  14479. QCPSelectionDecoratorBracket::~QCPSelectionDecoratorBracket()
  14480. {
  14481. }
  14482. /*!
  14483. Sets the pen that will be used to draw the brackets at the beginning and end of each selected
  14484. data segment.
  14485. */
  14486. void QCPSelectionDecoratorBracket::setBracketPen(const QPen &pen)
  14487. {
  14488. mBracketPen = pen;
  14489. }
  14490. /*!
  14491. Sets the brush that will be used to draw the brackets at the beginning and end of each selected
  14492. data segment.
  14493. */
  14494. void QCPSelectionDecoratorBracket::setBracketBrush(const QBrush &brush)
  14495. {
  14496. mBracketBrush = brush;
  14497. }
  14498. /*!
  14499. Sets the width of the drawn bracket. The width dimension is always parallel to the key axis of
  14500. the data, or the tangent direction of the current data slope, if \ref setTangentToData is
  14501. enabled.
  14502. */
  14503. void QCPSelectionDecoratorBracket::setBracketWidth(int width)
  14504. {
  14505. mBracketWidth = width;
  14506. }
  14507. /*!
  14508. Sets the height of the drawn bracket. The height dimension is always perpendicular to the key axis
  14509. of the data, or the tangent direction of the current data slope, if \ref setTangentToData is
  14510. enabled.
  14511. */
  14512. void QCPSelectionDecoratorBracket::setBracketHeight(int height)
  14513. {
  14514. mBracketHeight = height;
  14515. }
  14516. /*!
  14517. Sets the shape that the bracket/marker will have.
  14518. \see setBracketWidth, setBracketHeight
  14519. */
  14520. void QCPSelectionDecoratorBracket::setBracketStyle(QCPSelectionDecoratorBracket::BracketStyle style)
  14521. {
  14522. mBracketStyle = style;
  14523. }
  14524. /*!
  14525. Sets whether the brackets will be rotated such that they align with the slope of the data at the
  14526. position that they appear in.
  14527. For noisy data, it might be more visually appealing to average the slope over multiple data
  14528. points. This can be configured via \ref setTangentAverage.
  14529. */
  14530. void QCPSelectionDecoratorBracket::setTangentToData(bool enabled)
  14531. {
  14532. mTangentToData = enabled;
  14533. }
  14534. /*!
  14535. Controls over how many data points the slope shall be averaged, when brackets shall be aligned
  14536. with the data (if \ref setTangentToData is true).
  14537. From the position of the bracket, \a pointCount points towards the selected data range will be
  14538. taken into account. The smallest value of \a pointCount is 1, which is effectively equivalent to
  14539. disabling \ref setTangentToData.
  14540. */
  14541. void QCPSelectionDecoratorBracket::setTangentAverage(int pointCount)
  14542. {
  14543. mTangentAverage = pointCount;
  14544. if (mTangentAverage < 1)
  14545. mTangentAverage = 1;
  14546. }
  14547. /*!
  14548. Draws the bracket shape with \a painter. The parameter \a direction is either -1 or 1 and
  14549. indicates whether the bracket shall point to the left or the right (i.e. is a closing or opening
  14550. bracket, respectively).
  14551. The passed \a painter already contains all transformations that are necessary to position and
  14552. rotate the bracket appropriately. Painting operations can be performed as if drawing upright
  14553. brackets on flat data with horizontal key axis, with (0, 0) being the center of the bracket.
  14554. If you wish to sublcass \ref QCPSelectionDecoratorBracket in order to provide custom bracket
  14555. shapes (see \ref QCPSelectionDecoratorBracket::bsUserStyle), this is the method you should
  14556. reimplement.
  14557. */
  14558. void QCPSelectionDecoratorBracket::drawBracket(QCPPainter *painter, int direction) const
  14559. {
  14560. switch (mBracketStyle)
  14561. {
  14562. case bsSquareBracket:
  14563. {
  14564. painter->drawLine(QLineF(mBracketWidth*direction, -mBracketHeight*0.5, 0, -mBracketHeight*0.5));
  14565. painter->drawLine(QLineF(mBracketWidth*direction, mBracketHeight*0.5, 0, mBracketHeight*0.5));
  14566. painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
  14567. break;
  14568. }
  14569. case bsHalfEllipse:
  14570. {
  14571. painter->drawArc(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight), -90*16, -180*16*direction);
  14572. break;
  14573. }
  14574. case bsEllipse:
  14575. {
  14576. painter->drawEllipse(QRectF(-mBracketWidth*0.5, -mBracketHeight*0.5, mBracketWidth, mBracketHeight));
  14577. break;
  14578. }
  14579. case bsPlus:
  14580. {
  14581. painter->drawLine(QLineF(0, -mBracketHeight*0.5, 0, mBracketHeight*0.5));
  14582. painter->drawLine(QLineF(-mBracketWidth*0.5, 0, mBracketWidth*0.5, 0));
  14583. break;
  14584. }
  14585. default:
  14586. {
  14587. qDebug() << Q_FUNC_INFO << "unknown/custom bracket style can't be handeld by default implementation:" << static_cast<int>(mBracketStyle);
  14588. break;
  14589. }
  14590. }
  14591. }
  14592. /*!
  14593. Draws the bracket decoration on the data points at the begin and end of each selected data
  14594. segment given in \a seletion.
  14595. It uses the method \ref drawBracket to actually draw the shapes.
  14596. \seebaseclassmethod
  14597. */
  14598. void QCPSelectionDecoratorBracket::drawDecoration(QCPPainter *painter, QCPDataSelection selection)
  14599. {
  14600. if (!mPlottable || selection.isEmpty()) return;
  14601. if (QCPPlottableInterface1D *interface1d = mPlottable->interface1D())
  14602. {
  14603. foreach (const QCPDataRange &dataRange, selection.dataRanges())
  14604. {
  14605. // determine position and (if tangent mode is enabled) angle of brackets:
  14606. int openBracketDir = (mPlottable->keyAxis() && !mPlottable->keyAxis()->rangeReversed()) ? 1 : -1;
  14607. int closeBracketDir = -openBracketDir;
  14608. QPointF openBracketPos = getPixelCoordinates(interface1d, dataRange.begin());
  14609. QPointF closeBracketPos = getPixelCoordinates(interface1d, dataRange.end()-1);
  14610. double openBracketAngle = 0;
  14611. double closeBracketAngle = 0;
  14612. if (mTangentToData)
  14613. {
  14614. openBracketAngle = getTangentAngle(interface1d, dataRange.begin(), openBracketDir);
  14615. closeBracketAngle = getTangentAngle(interface1d, dataRange.end()-1, closeBracketDir);
  14616. }
  14617. // draw opening bracket:
  14618. QTransform oldTransform = painter->transform();
  14619. painter->setPen(mBracketPen);
  14620. painter->setBrush(mBracketBrush);
  14621. painter->translate(openBracketPos);
  14622. painter->rotate(openBracketAngle/M_PI*180.0);
  14623. drawBracket(painter, openBracketDir);
  14624. painter->setTransform(oldTransform);
  14625. // draw closing bracket:
  14626. painter->setPen(mBracketPen);
  14627. painter->setBrush(mBracketBrush);
  14628. painter->translate(closeBracketPos);
  14629. painter->rotate(closeBracketAngle/M_PI*180.0);
  14630. drawBracket(painter, closeBracketDir);
  14631. painter->setTransform(oldTransform);
  14632. }
  14633. }
  14634. }
  14635. /*! \internal
  14636. If \ref setTangentToData is enabled, brackets need to be rotated according to the data slope.
  14637. This method returns the angle in radians by which a bracket at the given \a dataIndex must be
  14638. rotated.
  14639. The parameter \a direction must be set to either -1 or 1, representing whether it is an opening
  14640. or closing bracket. Since for slope calculation multiple data points are required, this defines
  14641. the direction in which the algorithm walks, starting at \a dataIndex, to average those data
  14642. points. (see \ref setTangentToData and \ref setTangentAverage)
  14643. \a interface1d is the interface to the plottable's data which is used to query data coordinates.
  14644. */
  14645. double QCPSelectionDecoratorBracket::getTangentAngle(const QCPPlottableInterface1D *interface1d, int dataIndex, int direction) const
  14646. {
  14647. if (!interface1d || dataIndex < 0 || dataIndex >= interface1d->dataCount())
  14648. return 0;
  14649. direction = direction < 0 ? -1 : 1; // enforce direction is either -1 or 1
  14650. // how many steps we can actually go from index in the given direction without exceeding data bounds:
  14651. int averageCount;
  14652. if (direction < 0)
  14653. averageCount = qMin(mTangentAverage, dataIndex);
  14654. else
  14655. averageCount = qMin(mTangentAverage, interface1d->dataCount()-1-dataIndex);
  14656. //qDebug() << averageCount;
  14657. // calculate point average of averageCount points:
  14658. QVector<QPointF> points(averageCount);
  14659. QPointF pointsAverage;
  14660. int currentIndex = dataIndex;
  14661. for (int i=0; i<averageCount; ++i)
  14662. {
  14663. points[i] = getPixelCoordinates(interface1d, currentIndex);
  14664. pointsAverage += points[i];
  14665. currentIndex += direction;
  14666. }
  14667. pointsAverage /= double(averageCount);
  14668. // calculate slope of linear regression through points:
  14669. double numSum = 0;
  14670. double denomSum = 0;
  14671. for (int i=0; i<averageCount; ++i)
  14672. {
  14673. const double dx = points.at(i).x()-pointsAverage.x();
  14674. const double dy = points.at(i).y()-pointsAverage.y();
  14675. numSum += dx*dy;
  14676. denomSum += dx*dx;
  14677. }
  14678. if (!qFuzzyIsNull(denomSum) && !qFuzzyIsNull(numSum))
  14679. {
  14680. return qAtan2(numSum, denomSum);
  14681. } else // undetermined angle, probably mTangentAverage == 1, so using only one data point
  14682. return 0;
  14683. }
  14684. /*! \internal
  14685. Returns the pixel coordinates of the data point at \a dataIndex, using \a interface1d to access
  14686. the data points.
  14687. */
  14688. QPointF QCPSelectionDecoratorBracket::getPixelCoordinates(const QCPPlottableInterface1D *interface1d, int dataIndex) const
  14689. {
  14690. QCPAxis *keyAxis = mPlottable->keyAxis();
  14691. QCPAxis *valueAxis = mPlottable->valueAxis();
  14692. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {0, 0}; }
  14693. if (keyAxis->orientation() == Qt::Horizontal)
  14694. return {keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex)), valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex))};
  14695. else
  14696. return {valueAxis->coordToPixel(interface1d->dataMainValue(dataIndex)), keyAxis->coordToPixel(interface1d->dataMainKey(dataIndex))};
  14697. }
  14698. /* end of 'src/selectiondecorator-bracket.cpp' */
  14699. /* including file 'src/layoutelements/layoutelement-axisrect.cpp' */
  14700. /* modified 2021-03-29T02:30:44, size 47193 */
  14701. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14702. //////////////////// QCPAxisRect
  14703. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14704. /*! \class QCPAxisRect
  14705. \brief Holds multiple axes and arranges them in a rectangular shape.
  14706. This class represents an axis rect, a rectangular area that is bounded on all sides with an
  14707. arbitrary number of axes.
  14708. Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the
  14709. layout system allows to have multiple axis rects, e.g. arranged in a grid layout
  14710. (QCustomPlot::plotLayout).
  14711. By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be
  14712. accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index.
  14713. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be
  14714. invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref
  14715. addAxes. To remove an axis, use \ref removeAxis.
  14716. The axis rect layerable itself only draws a background pixmap or color, if specified (\ref
  14717. setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an
  14718. explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be
  14719. placed on other layers, independently of the axis rect.
  14720. Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref
  14721. insetLayout and can be used to have other layout elements (or even other layouts with multiple
  14722. elements) hovering inside the axis rect.
  14723. If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The
  14724. behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel
  14725. is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable
  14726. via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are
  14727. only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref
  14728. QCP::iRangeZoom.
  14729. \image html AxisRectSpacingOverview.png
  14730. <center>Overview of the spacings and paddings that define the geometry of an axis. The dashed
  14731. line on the far left indicates the viewport/widget border.</center>
  14732. */
  14733. /* start documentation of inline functions */
  14734. /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const
  14735. Returns the inset layout of this axis rect. It can be used to place other layout elements (or
  14736. even layouts with multiple other elements) inside/on top of an axis rect.
  14737. \see QCPLayoutInset
  14738. */
  14739. /*! \fn int QCPAxisRect::left() const
  14740. Returns the pixel position of the left border of this axis rect. Margins are not taken into
  14741. account here, so the returned value is with respect to the inner \ref rect.
  14742. */
  14743. /*! \fn int QCPAxisRect::right() const
  14744. Returns the pixel position of the right border of this axis rect. Margins are not taken into
  14745. account here, so the returned value is with respect to the inner \ref rect.
  14746. */
  14747. /*! \fn int QCPAxisRect::top() const
  14748. Returns the pixel position of the top border of this axis rect. Margins are not taken into
  14749. account here, so the returned value is with respect to the inner \ref rect.
  14750. */
  14751. /*! \fn int QCPAxisRect::bottom() const
  14752. Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
  14753. account here, so the returned value is with respect to the inner \ref rect.
  14754. */
  14755. /*! \fn int QCPAxisRect::width() const
  14756. Returns the pixel width of this axis rect. Margins are not taken into account here, so the
  14757. returned value is with respect to the inner \ref rect.
  14758. */
  14759. /*! \fn int QCPAxisRect::height() const
  14760. Returns the pixel height of this axis rect. Margins are not taken into account here, so the
  14761. returned value is with respect to the inner \ref rect.
  14762. */
  14763. /*! \fn QSize QCPAxisRect::size() const
  14764. Returns the pixel size of this axis rect. Margins are not taken into account here, so the
  14765. returned value is with respect to the inner \ref rect.
  14766. */
  14767. /*! \fn QPoint QCPAxisRect::topLeft() const
  14768. Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
  14769. so the returned value is with respect to the inner \ref rect.
  14770. */
  14771. /*! \fn QPoint QCPAxisRect::topRight() const
  14772. Returns the top right corner of this axis rect in pixels. Margins are not taken into account
  14773. here, so the returned value is with respect to the inner \ref rect.
  14774. */
  14775. /*! \fn QPoint QCPAxisRect::bottomLeft() const
  14776. Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
  14777. here, so the returned value is with respect to the inner \ref rect.
  14778. */
  14779. /*! \fn QPoint QCPAxisRect::bottomRight() const
  14780. Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
  14781. here, so the returned value is with respect to the inner \ref rect.
  14782. */
  14783. /*! \fn QPoint QCPAxisRect::center() const
  14784. Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
  14785. returned value is with respect to the inner \ref rect.
  14786. */
  14787. /* end documentation of inline functions */
  14788. /*!
  14789. Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four
  14790. sides, the top and right axes are set invisible initially.
  14791. */
  14792. QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) :
  14793. QCPLayoutElement(parentPlot),
  14794. mBackgroundBrush(Qt::NoBrush),
  14795. mBackgroundScaled(true),
  14796. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  14797. mInsetLayout(new QCPLayoutInset),
  14798. mRangeDrag(Qt::Horizontal|Qt::Vertical),
  14799. mRangeZoom(Qt::Horizontal|Qt::Vertical),
  14800. mRangeZoomFactorHorz(0.85),
  14801. mRangeZoomFactorVert(0.85),
  14802. mDragging(false)
  14803. {
  14804. mInsetLayout->initializeParentPlot(mParentPlot);
  14805. mInsetLayout->setParentLayerable(this);
  14806. mInsetLayout->setParent(this);
  14807. setMinimumSize(50, 50);
  14808. setMinimumMargins(QMargins(15, 15, 15, 15));
  14809. mAxes.insert(QCPAxis::AxisType::atLeft, QList<QCPAxis*>());
  14810. mAxes.insert(QCPAxis::AxisType::atRight, QList<QCPAxis*>());
  14811. mAxes.insert(QCPAxis::AxisType::atTop, QList<QCPAxis*>());
  14812. mAxes.insert(QCPAxis::AxisType::atBottom, QList<QCPAxis*>());
  14813. if (setupDefaultAxes)
  14814. {
  14815. QCPAxis *xAxis = addAxis(QCPAxis::AxisType::atBottom);
  14816. QCPAxis *yAxis = addAxis(QCPAxis::AxisType::atLeft);
  14817. QCPAxis *xAxis2 = addAxis(QCPAxis::AxisType::atTop);
  14818. QCPAxis *yAxis2 = addAxis(QCPAxis::AxisType::atRight);
  14819. setRangeDragAxes(xAxis, yAxis);
  14820. setRangeZoomAxes(xAxis, yAxis);
  14821. xAxis2->setVisible(false);
  14822. yAxis2->setVisible(false);
  14823. xAxis->grid()->setVisible(true);
  14824. yAxis->grid()->setVisible(true);
  14825. xAxis2->grid()->setVisible(false);
  14826. yAxis2->grid()->setVisible(false);
  14827. xAxis2->grid()->setZeroLinePen(Qt::NoPen);
  14828. yAxis2->grid()->setZeroLinePen(Qt::NoPen);
  14829. xAxis2->grid()->setVisible(false);
  14830. yAxis2->grid()->setVisible(false);
  14831. }
  14832. }
  14833. QCPAxisRect::~QCPAxisRect()
  14834. {
  14835. delete mInsetLayout;
  14836. mInsetLayout = nullptr;
  14837. foreach (QCPAxis *axis, axes())
  14838. removeAxis(axis);
  14839. }
  14840. /*!
  14841. Returns the number of axes on the axis rect side specified with \a type.
  14842. \see axis
  14843. */
  14844. int QCPAxisRect::axisCount(QCPAxis::AxisType type) const
  14845. {
  14846. return mAxes.value(type).size();
  14847. }
  14848. /*!
  14849. Returns the axis with the given \a index on the axis rect side specified with \a type.
  14850. \see axisCount, axes
  14851. */
  14852. QCPAxis *QCPAxisRect::axis(QCPAxis::AxisType type, int index) const
  14853. {
  14854. QList<QCPAxis*> ax(mAxes.value(type));
  14855. if (index >= 0 && index < ax.size())
  14856. {
  14857. return ax.at(index);
  14858. } else
  14859. {
  14860. qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
  14861. return nullptr;
  14862. }
  14863. }
  14864. /*!
  14865. Returns all axes on the axis rect sides specified with \a types.
  14866. \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
  14867. multiple sides.
  14868. \see axis
  14869. */
  14870. QList<QCPAxis*> QCPAxisRect::axes(QCPAxis::AxisTypes types) const
  14871. {
  14872. QList<QCPAxis*> result;
  14873. if (types.testFlag(QCPAxis::AxisType::atLeft))
  14874. result << mAxes.value(QCPAxis::AxisType::atLeft);
  14875. if (types.testFlag(QCPAxis::AxisType::atRight))
  14876. result << mAxes.value(QCPAxis::AxisType::atRight);
  14877. if (types.testFlag(QCPAxis::AxisType::atTop))
  14878. result << mAxes.value(QCPAxis::AxisType::atTop);
  14879. if (types.testFlag(QCPAxis::AxisType::atBottom))
  14880. result << mAxes.value(QCPAxis::AxisType::atBottom);
  14881. return result;
  14882. }
  14883. /*! \overload
  14884. Returns all axes of this axis rect.
  14885. */
  14886. QList<QCPAxis*> QCPAxisRect::axes() const
  14887. {
  14888. QList<QCPAxis*> result;
  14889. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
  14890. while (it.hasNext())
  14891. {
  14892. it.next();
  14893. result << it.value();
  14894. }
  14895. return result;
  14896. }
  14897. /*!
  14898. Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
  14899. new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
  14900. remove an axis, use \ref removeAxis instead of deleting it manually.
  14901. You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was
  14902. previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
  14903. of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
  14904. with this axis rect as parent and with the same axis type as specified in \a type. If this is not
  14905. the case, a debug output is generated, the axis is not added, and the method returns \c nullptr.
  14906. This method can not be used to move \a axis between axis rects. The same \a axis instance must
  14907. not be added multiple times to the same or different axis rects.
  14908. If an axis rect side already contains one or more axes, the lower and upper endings of the new
  14909. axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
  14910. QCPLineEnding::esHalfBar.
  14911. \see addAxes, setupFullAxesBox
  14912. */
  14913. QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type, QCPAxis *axis)
  14914. {
  14915. QCPAxis *newAxis = axis;
  14916. if (!newAxis)
  14917. {
  14918. newAxis = new QCPAxis(this, type);
  14919. } else // user provided existing axis instance, do some sanity checks
  14920. {
  14921. if (newAxis->axisType() != type)
  14922. {
  14923. qDebug() << Q_FUNC_INFO << "passed axis has different axis type than specified in type parameter";
  14924. return nullptr;
  14925. }
  14926. if (newAxis->axisRect() != this)
  14927. {
  14928. qDebug() << Q_FUNC_INFO << "passed axis doesn't have this axis rect as parent axis rect";
  14929. return nullptr;
  14930. }
  14931. if (axes().contains(newAxis))
  14932. {
  14933. qDebug() << Q_FUNC_INFO << "passed axis is already owned by this axis rect";
  14934. return nullptr;
  14935. }
  14936. }
  14937. if (!mAxes[type].isEmpty()) // multiple axes on one side, add half-bar axis ending to additional axes with offset
  14938. {
  14939. bool invert = (type == QCPAxis::AxisType::atRight) || (type == QCPAxis::AxisType::atBottom);
  14940. newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::EndingStyle::esHalfBar, 6, 10, !invert));
  14941. newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::EndingStyle::esHalfBar, 6, 10, invert));
  14942. }
  14943. mAxes[type].append(newAxis);
  14944. // reset convenience axis pointers on parent QCustomPlot if they are unset:
  14945. if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
  14946. {
  14947. switch (type)
  14948. {
  14949. case QCPAxis::AxisType::atBottom: { if (!mParentPlot->xAxis) mParentPlot->xAxis = newAxis; break; }
  14950. case QCPAxis::AxisType::atLeft: { if (!mParentPlot->yAxis) mParentPlot->yAxis = newAxis; break; }
  14951. case QCPAxis::AxisType::atTop: { if (!mParentPlot->xAxis2) mParentPlot->xAxis2 = newAxis; break; }
  14952. case QCPAxis::AxisType::atRight: { if (!mParentPlot->yAxis2) mParentPlot->yAxis2 = newAxis; break; }
  14953. }
  14954. }
  14955. return newAxis;
  14956. }
  14957. /*!
  14958. Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an
  14959. <tt>or</tt>-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once.
  14960. Returns a list of the added axes.
  14961. \see addAxis, setupFullAxesBox
  14962. */
  14963. QList<QCPAxis*> QCPAxisRect::addAxes(QCPAxis::AxisTypes types)
  14964. {
  14965. QList<QCPAxis*> result;
  14966. if (types.testFlag(QCPAxis::AxisType::atLeft))
  14967. result << addAxis(QCPAxis::AxisType::atLeft);
  14968. if (types.testFlag(QCPAxis::AxisType::atRight))
  14969. result << addAxis(QCPAxis::AxisType::atRight);
  14970. if (types.testFlag(QCPAxis::AxisType::atTop))
  14971. result << addAxis(QCPAxis::AxisType::atTop);
  14972. if (types.testFlag(QCPAxis::AxisType::atBottom))
  14973. result << addAxis(QCPAxis::AxisType::atBottom);
  14974. return result;
  14975. }
  14976. /*!
  14977. Removes the specified \a axis from the axis rect and deletes it.
  14978. Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
  14979. \see addAxis
  14980. */
  14981. bool QCPAxisRect::removeAxis(QCPAxis *axis)
  14982. {
  14983. // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers:
  14984. QHashIterator<QCPAxis::AxisType, QList<QCPAxis*> > it(mAxes);
  14985. while (it.hasNext())
  14986. {
  14987. it.next();
  14988. if (it.value().contains(axis))
  14989. {
  14990. 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)
  14991. it.value()[1]->setOffset(axis->offset());
  14992. mAxes[it.key()].removeOne(axis);
  14993. 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)
  14994. parentPlot()->axisRemoved(axis);
  14995. delete axis;
  14996. return true;
  14997. }
  14998. }
  14999. qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast<quintptr>(axis);
  15000. return false;
  15001. }
  15002. /*!
  15003. Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
  15004. All axes of this axis rect will have their range zoomed accordingly. If you only wish to zoom
  15005. specific axes, use the overloaded version of this method.
  15006. \see QCustomPlot::setSelectionRectMode
  15007. */
  15008. void QCPAxisRect::zoom(const QRectF &pixelRect)
  15009. {
  15010. zoom(pixelRect, axes());
  15011. }
  15012. /*! \overload
  15013. Zooms in (or out) to the passed rectangular region \a pixelRect, given in pixel coordinates.
  15014. Only the axes passed in \a affectedAxes will have their ranges zoomed accordingly.
  15015. \see QCustomPlot::setSelectionRectMode
  15016. */
  15017. void QCPAxisRect::zoom(const QRectF &pixelRect, const QList<QCPAxis*> &affectedAxes)
  15018. {
  15019. foreach (QCPAxis *axis, affectedAxes)
  15020. {
  15021. if (!axis)
  15022. {
  15023. qDebug() << Q_FUNC_INFO << "a passed axis was zero";
  15024. continue;
  15025. }
  15026. QCPRange pixelRange;
  15027. if (axis->orientation() == Qt::Horizontal)
  15028. pixelRange = QCPRange(pixelRect.left(), pixelRect.right());
  15029. else
  15030. pixelRange = QCPRange(pixelRect.top(), pixelRect.bottom());
  15031. axis->setRange(axis->pixelToCoord(pixelRange.lower), axis->pixelToCoord(pixelRange.upper));
  15032. }
  15033. }
  15034. /*!
  15035. Convenience function to create an axis on each side that doesn't have any axes yet and set their
  15036. visibility to true. Further, the top/right axes are assigned the following properties of the
  15037. bottom/left axes:
  15038. \li range (\ref QCPAxis::setRange)
  15039. \li range reversed (\ref QCPAxis::setRangeReversed)
  15040. \li scale type (\ref QCPAxis::setScaleType)
  15041. \li tick visibility (\ref QCPAxis::setTicks)
  15042. \li number format (\ref QCPAxis::setNumberFormat)
  15043. \li number precision (\ref QCPAxis::setNumberPrecision)
  15044. \li tick count of ticker (\ref QCPAxisTicker::setTickCount)
  15045. \li tick origin of ticker (\ref QCPAxisTicker::setTickOrigin)
  15046. Tick label visibility (\ref QCPAxis::setTickLabels) of the right and top axes are set to false.
  15047. If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom
  15048. and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes.
  15049. */
  15050. void QCPAxisRect::setupFullAxesBox(bool connectRanges)
  15051. {
  15052. QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2;
  15053. if (axisCount(QCPAxis::AxisType::atBottom) == 0)
  15054. xAxis = addAxis(QCPAxis::AxisType::atBottom);
  15055. else
  15056. xAxis = axis(QCPAxis::AxisType::atBottom);
  15057. if (axisCount(QCPAxis::AxisType::atLeft) == 0)
  15058. yAxis = addAxis(QCPAxis::AxisType::atLeft);
  15059. else
  15060. yAxis = axis(QCPAxis::AxisType::atLeft);
  15061. if (axisCount(QCPAxis::AxisType::atTop) == 0)
  15062. xAxis2 = addAxis(QCPAxis::AxisType::atTop);
  15063. else
  15064. xAxis2 = axis(QCPAxis::AxisType::atTop);
  15065. if (axisCount(QCPAxis::AxisType::atRight) == 0)
  15066. yAxis2 = addAxis(QCPAxis::AxisType::atRight);
  15067. else
  15068. yAxis2 = axis(QCPAxis::AxisType::atRight);
  15069. xAxis->setVisible(true);
  15070. yAxis->setVisible(true);
  15071. xAxis2->setVisible(true);
  15072. yAxis2->setVisible(true);
  15073. xAxis2->setTickLabels(false);
  15074. yAxis2->setTickLabels(false);
  15075. xAxis2->setRange(xAxis->range());
  15076. xAxis2->setRangeReversed(xAxis->rangeReversed());
  15077. xAxis2->setScaleType(xAxis->scaleType());
  15078. xAxis2->setTicks(xAxis->ticks());
  15079. xAxis2->setNumberFormat(xAxis->numberFormat());
  15080. xAxis2->setNumberPrecision(xAxis->numberPrecision());
  15081. xAxis2->ticker()->setTickCount(xAxis->ticker()->tickCount());
  15082. xAxis2->ticker()->setTickOrigin(xAxis->ticker()->tickOrigin());
  15083. yAxis2->setRange(yAxis->range());
  15084. yAxis2->setRangeReversed(yAxis->rangeReversed());
  15085. yAxis2->setScaleType(yAxis->scaleType());
  15086. yAxis2->setTicks(yAxis->ticks());
  15087. yAxis2->setNumberFormat(yAxis->numberFormat());
  15088. yAxis2->setNumberPrecision(yAxis->numberPrecision());
  15089. yAxis2->ticker()->setTickCount(yAxis->ticker()->tickCount());
  15090. yAxis2->ticker()->setTickOrigin(yAxis->ticker()->tickOrigin());
  15091. if (connectRanges)
  15092. {
  15093. connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange)));
  15094. connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange)));
  15095. }
  15096. }
  15097. /*!
  15098. Returns a list of all the plottables that are associated with this axis rect.
  15099. A plottable is considered associated with an axis rect if its key or value axis (or both) is in
  15100. this axis rect.
  15101. \see graphs, items
  15102. */
  15103. QList<QCPAbstractPlottable*> QCPAxisRect::plottables() const
  15104. {
  15105. // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries
  15106. QList<QCPAbstractPlottable*> result;
  15107. foreach (QCPAbstractPlottable *plottable, mParentPlot->mPlottables)
  15108. {
  15109. if (plottable->keyAxis()->axisRect() == this || plottable->valueAxis()->axisRect() == this)
  15110. result.append(plottable);
  15111. }
  15112. return result;
  15113. }
  15114. /*!
  15115. Returns a list of all the graphs that are associated with this axis rect.
  15116. A graph is considered associated with an axis rect if its key or value axis (or both) is in
  15117. this axis rect.
  15118. \see plottables, items
  15119. */
  15120. QList<QCPGraph*> QCPAxisRect::graphs() const
  15121. {
  15122. // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries
  15123. QList<QCPGraph*> result;
  15124. foreach (QCPGraph *graph, mParentPlot->mGraphs)
  15125. {
  15126. if (graph->keyAxis()->axisRect() == this || graph->valueAxis()->axisRect() == this)
  15127. result.append(graph);
  15128. }
  15129. return result;
  15130. }
  15131. /*!
  15132. Returns a list of all the items that are associated with this axis rect.
  15133. An item is considered associated with an axis rect if any of its positions has key or value axis
  15134. set to an axis that is in this axis rect, or if any of its positions has \ref
  15135. QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref
  15136. QCPAbstractItem::setClipAxisRect) is set to this axis rect.
  15137. \see plottables, graphs
  15138. */
  15139. QList<QCPAbstractItem *> QCPAxisRect::items() const
  15140. {
  15141. // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries
  15142. // and miss those items that have this axis rect as clipAxisRect.
  15143. QList<QCPAbstractItem*> result;
  15144. foreach (QCPAbstractItem *item, mParentPlot->mItems)
  15145. {
  15146. if (item->clipAxisRect() == this)
  15147. {
  15148. result.append(item);
  15149. continue;
  15150. }
  15151. foreach (QCPItemPosition *position, item->positions())
  15152. {
  15153. if (position->axisRect() == this ||
  15154. position->keyAxis()->axisRect() == this ||
  15155. position->valueAxis()->axisRect() == this)
  15156. {
  15157. result.append(item);
  15158. break;
  15159. }
  15160. }
  15161. }
  15162. return result;
  15163. }
  15164. /*!
  15165. This method is called automatically upon replot and doesn't need to be called by users of
  15166. QCPAxisRect.
  15167. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
  15168. and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
  15169. QCPInsetLayout::update function.
  15170. \seebaseclassmethod
  15171. */
  15172. void QCPAxisRect::update(UpdatePhase phase)
  15173. {
  15174. QCPLayoutElement::update(phase);
  15175. switch (phase)
  15176. {
  15177. case upPreparation:
  15178. {
  15179. foreach (QCPAxis *axis, axes())
  15180. axis->setupTickVectors();
  15181. break;
  15182. }
  15183. case upLayout:
  15184. {
  15185. mInsetLayout->setOuterRect(rect());
  15186. break;
  15187. }
  15188. default: break;
  15189. }
  15190. // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout):
  15191. mInsetLayout->update(phase);
  15192. }
  15193. /* inherits documentation from base class */
  15194. QList<QCPLayoutElement*> QCPAxisRect::elements(bool recursive) const
  15195. {
  15196. QList<QCPLayoutElement*> result;
  15197. if (mInsetLayout)
  15198. {
  15199. result << mInsetLayout;
  15200. if (recursive)
  15201. result << mInsetLayout->elements(recursive);
  15202. }
  15203. return result;
  15204. }
  15205. /* inherits documentation from base class */
  15206. void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const
  15207. {
  15208. painter->setAntialiasing(false);
  15209. }
  15210. /* inherits documentation from base class */
  15211. void QCPAxisRect::draw(QCPPainter *painter)
  15212. {
  15213. drawBackground(painter);
  15214. }
  15215. /*!
  15216. Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
  15217. axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
  15218. backgrounds are usually drawn below everything else.
  15219. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
  15220. enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
  15221. is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  15222. consider using the overloaded version of this function.
  15223. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
  15224. setBackground(const QBrush &brush).
  15225. \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
  15226. */
  15227. void QCPAxisRect::setBackground(const QPixmap &pm)
  15228. {
  15229. mBackgroundPixmap = pm;
  15230. mScaledBackgroundPixmap = QPixmap();
  15231. }
  15232. /*! \overload
  15233. Sets \a brush as the background brush. The axis rect background will be filled with this brush.
  15234. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
  15235. are usually drawn below everything else.
  15236. The brush will be drawn before (under) any background pixmap, which may be specified with \ref
  15237. setBackground(const QPixmap &pm).
  15238. To disable drawing of a background brush, set \a brush to Qt::NoBrush.
  15239. \see setBackground(const QPixmap &pm)
  15240. */
  15241. void QCPAxisRect::setBackground(const QBrush &brush)
  15242. {
  15243. mBackgroundBrush = brush;
  15244. }
  15245. /*! \overload
  15246. Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
  15247. shall be scaled in one call.
  15248. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  15249. */
  15250. void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  15251. {
  15252. mBackgroundPixmap = pm;
  15253. mScaledBackgroundPixmap = QPixmap();
  15254. mBackgroundScaled = scaled;
  15255. mBackgroundScaledMode = mode;
  15256. }
  15257. /*!
  15258. Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
  15259. is set to true, you may control whether and how the aspect ratio of the original pixmap is
  15260. preserved with \ref setBackgroundScaledMode.
  15261. Note that the scaled version of the original pixmap is buffered, so there is no performance
  15262. penalty on replots. (Except when the axis rect dimensions are changed continuously.)
  15263. \see setBackground, setBackgroundScaledMode
  15264. */
  15265. void QCPAxisRect::setBackgroundScaled(bool scaled)
  15266. {
  15267. mBackgroundScaled = scaled;
  15268. }
  15269. /*!
  15270. If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
  15271. define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
  15272. \see setBackground, setBackgroundScaled
  15273. */
  15274. void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  15275. {
  15276. mBackgroundScaledMode = mode;
  15277. }
  15278. /*!
  15279. Returns the range drag axis of the \a orientation provided. If multiple axes were set, returns
  15280. the first one (use \ref rangeDragAxes to retrieve a list with all set axes).
  15281. \see setRangeDragAxes
  15282. */
  15283. QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation)
  15284. {
  15285. if (orientation == Qt::Horizontal)
  15286. return mRangeDragHorzAxis.isEmpty() ? nullptr : mRangeDragHorzAxis.first().data();
  15287. else
  15288. return mRangeDragVertAxis.isEmpty() ? nullptr : mRangeDragVertAxis.first().data();
  15289. }
  15290. /*!
  15291. Returns the range zoom axis of the \a orientation provided. If multiple axes were set, returns
  15292. the first one (use \ref rangeZoomAxes to retrieve a list with all set axes).
  15293. \see setRangeZoomAxes
  15294. */
  15295. QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation)
  15296. {
  15297. if (orientation == Qt::Horizontal)
  15298. return mRangeZoomHorzAxis.isEmpty() ? nullptr : mRangeZoomHorzAxis.first().data();
  15299. else
  15300. return mRangeZoomVertAxis.isEmpty() ? nullptr : mRangeZoomVertAxis.first().data();
  15301. }
  15302. /*!
  15303. Returns all range drag axes of the \a orientation provided.
  15304. \see rangeZoomAxis, setRangeZoomAxes
  15305. */
  15306. QList<QCPAxis*> QCPAxisRect::rangeDragAxes(Qt::Orientation orientation)
  15307. {
  15308. QList<QCPAxis*> result;
  15309. if (orientation == Qt::Horizontal)
  15310. {
  15311. foreach (QPointer<QCPAxis> axis, mRangeDragHorzAxis)
  15312. {
  15313. if (!axis.isNull())
  15314. result.append(axis.data());
  15315. }
  15316. } else
  15317. {
  15318. foreach (QPointer<QCPAxis> axis, mRangeDragVertAxis)
  15319. {
  15320. if (!axis.isNull())
  15321. result.append(axis.data());
  15322. }
  15323. }
  15324. return result;
  15325. }
  15326. /*!
  15327. Returns all range zoom axes of the \a orientation provided.
  15328. \see rangeDragAxis, setRangeDragAxes
  15329. */
  15330. QList<QCPAxis*> QCPAxisRect::rangeZoomAxes(Qt::Orientation orientation)
  15331. {
  15332. QList<QCPAxis*> result;
  15333. if (orientation == Qt::Horizontal)
  15334. {
  15335. foreach (QPointer<QCPAxis> axis, mRangeZoomHorzAxis)
  15336. {
  15337. if (!axis.isNull())
  15338. result.append(axis.data());
  15339. }
  15340. } else
  15341. {
  15342. foreach (QPointer<QCPAxis> axis, mRangeZoomVertAxis)
  15343. {
  15344. if (!axis.isNull())
  15345. result.append(axis.data());
  15346. }
  15347. }
  15348. return result;
  15349. }
  15350. /*!
  15351. Returns the range zoom factor of the \a orientation provided.
  15352. \see setRangeZoomFactor
  15353. */
  15354. double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation)
  15355. {
  15356. return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert);
  15357. }
  15358. /*!
  15359. Sets which axis orientation may be range dragged by the user with mouse interaction.
  15360. What orientation corresponds to which specific axis can be set with
  15361. \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By
  15362. default, the horizontal axis is the bottom axis (xAxis) and the vertical axis
  15363. is the left axis (yAxis).
  15364. To disable range dragging entirely, pass \c nullptr as \a orientations or remove \ref
  15365. QCP::iRangeDrag from \ref QCustomPlot::setInteractions. To enable range dragging for both
  15366. directions, pass <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations.
  15367. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
  15368. contains \ref QCP::iRangeDrag to enable the range dragging interaction.
  15369. \see setRangeZoom, setRangeDragAxes, QCustomPlot::setNoAntialiasingOnDrag
  15370. */
  15371. void QCPAxisRect::setRangeDrag(Qt::Orientations orientations)
  15372. {
  15373. mRangeDrag = orientations;
  15374. }
  15375. /*!
  15376. Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation
  15377. corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal,
  15378. QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical
  15379. axis is the left axis (yAxis).
  15380. To disable range zooming entirely, pass \c nullptr as \a orientations or remove \ref
  15381. QCP::iRangeZoom from \ref QCustomPlot::setInteractions. To enable range zooming for both
  15382. directions, pass <tt>Qt::Horizontal | Qt::Vertical</tt> as \a orientations.
  15383. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions
  15384. contains \ref QCP::iRangeZoom to enable the range zooming interaction.
  15385. \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag
  15386. */
  15387. void QCPAxisRect::setRangeZoom(Qt::Orientations orientations)
  15388. {
  15389. mRangeZoom = orientations;
  15390. }
  15391. /*! \overload
  15392. Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on
  15393. the QCustomPlot widget. Pass \c nullptr if no axis shall be dragged in the respective
  15394. orientation.
  15395. Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
  15396. react to dragging interactions.
  15397. \see setRangeZoomAxes
  15398. */
  15399. void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical)
  15400. {
  15401. QList<QCPAxis*> horz, vert;
  15402. if (horizontal)
  15403. horz.append(horizontal);
  15404. if (vertical)
  15405. vert.append(vertical);
  15406. setRangeDragAxes(horz, vert);
  15407. }
  15408. /*! \overload
  15409. This method allows to set up multiple axes to react to horizontal and vertical dragging. The drag
  15410. orientation that the respective axis will react to is deduced from its orientation (\ref
  15411. QCPAxis::orientation).
  15412. In the unusual case that you wish to e.g. drag a vertically oriented axis with a horizontal drag
  15413. motion, use the overload taking two separate lists for horizontal and vertical dragging.
  15414. */
  15415. void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> axes)
  15416. {
  15417. QList<QCPAxis*> horz, vert;
  15418. foreach (QCPAxis *ax, axes)
  15419. {
  15420. if (ax->orientation() == Qt::Horizontal)
  15421. horz.append(ax);
  15422. else
  15423. vert.append(ax);
  15424. }
  15425. setRangeDragAxes(horz, vert);
  15426. }
  15427. /*! \overload
  15428. This method allows to set multiple axes up to react to horizontal and vertical dragging, and
  15429. define specifically which axis reacts to which drag orientation (irrespective of the axis
  15430. orientation).
  15431. */
  15432. void QCPAxisRect::setRangeDragAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
  15433. {
  15434. mRangeDragHorzAxis.clear();
  15435. foreach (QCPAxis *ax, horizontal)
  15436. {
  15437. QPointer<QCPAxis> axPointer(ax);
  15438. if (!axPointer.isNull())
  15439. mRangeDragHorzAxis.append(axPointer);
  15440. else
  15441. qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
  15442. }
  15443. mRangeDragVertAxis.clear();
  15444. foreach (QCPAxis *ax, vertical)
  15445. {
  15446. QPointer<QCPAxis> axPointer(ax);
  15447. if (!axPointer.isNull())
  15448. mRangeDragVertAxis.append(axPointer);
  15449. else
  15450. qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
  15451. }
  15452. }
  15453. /*!
  15454. Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on
  15455. the QCustomPlot widget. Pass \c nullptr if no axis shall be zoomed in the respective orientation.
  15456. The two axes can be zoomed with different strengths, when different factors are passed to \ref
  15457. setRangeZoomFactor(double horizontalFactor, double verticalFactor).
  15458. Use the overload taking a list of axes, if multiple axes (more than one per orientation) shall
  15459. react to zooming interactions.
  15460. \see setRangeDragAxes
  15461. */
  15462. void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical)
  15463. {
  15464. QList<QCPAxis*> horz, vert;
  15465. if (horizontal)
  15466. horz.append(horizontal);
  15467. if (vertical)
  15468. vert.append(vertical);
  15469. setRangeZoomAxes(horz, vert);
  15470. }
  15471. /*! \overload
  15472. This method allows to set up multiple axes to react to horizontal and vertical range zooming. The
  15473. zoom orientation that the respective axis will react to is deduced from its orientation (\ref
  15474. QCPAxis::orientation).
  15475. In the unusual case that you wish to e.g. zoom a vertically oriented axis with a horizontal zoom
  15476. interaction, use the overload taking two separate lists for horizontal and vertical zooming.
  15477. */
  15478. void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> axes)
  15479. {
  15480. QList<QCPAxis*> horz, vert;
  15481. foreach (QCPAxis *ax, axes)
  15482. {
  15483. if (ax->orientation() == Qt::Horizontal)
  15484. horz.append(ax);
  15485. else
  15486. vert.append(ax);
  15487. }
  15488. setRangeZoomAxes(horz, vert);
  15489. }
  15490. /*! \overload
  15491. This method allows to set multiple axes up to react to horizontal and vertical zooming, and
  15492. define specifically which axis reacts to which zoom orientation (irrespective of the axis
  15493. orientation).
  15494. */
  15495. void QCPAxisRect::setRangeZoomAxes(QList<QCPAxis*> horizontal, QList<QCPAxis*> vertical)
  15496. {
  15497. mRangeZoomHorzAxis.clear();
  15498. foreach (QCPAxis *ax, horizontal)
  15499. {
  15500. QPointer<QCPAxis> axPointer(ax);
  15501. if (!axPointer.isNull())
  15502. mRangeZoomHorzAxis.append(axPointer);
  15503. else
  15504. qDebug() << Q_FUNC_INFO << "invalid axis passed in horizontal list:" << reinterpret_cast<quintptr>(ax);
  15505. }
  15506. mRangeZoomVertAxis.clear();
  15507. foreach (QCPAxis *ax, vertical)
  15508. {
  15509. QPointer<QCPAxis> axPointer(ax);
  15510. if (!axPointer.isNull())
  15511. mRangeZoomVertAxis.append(axPointer);
  15512. else
  15513. qDebug() << Q_FUNC_INFO << "invalid axis passed in vertical list:" << reinterpret_cast<quintptr>(ax);
  15514. }
  15515. }
  15516. /*!
  15517. Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with
  15518. \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to
  15519. let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal
  15520. and which is vertical, can be set with \ref setRangeZoomAxes.
  15521. When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user)
  15522. will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the
  15523. same scrolling direction will zoom out.
  15524. */
  15525. void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor)
  15526. {
  15527. mRangeZoomFactorHorz = horizontalFactor;
  15528. mRangeZoomFactorVert = verticalFactor;
  15529. }
  15530. /*! \overload
  15531. Sets both the horizontal and vertical zoom \a factor.
  15532. */
  15533. void QCPAxisRect::setRangeZoomFactor(double factor)
  15534. {
  15535. mRangeZoomFactorHorz = factor;
  15536. mRangeZoomFactorVert = factor;
  15537. }
  15538. /*! \internal
  15539. Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
  15540. pixmap.
  15541. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
  15542. according filling inside the axis rect with the provided \a painter.
  15543. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
  15544. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  15545. the axis rect with the provided \a painter. The scaled version is buffered in
  15546. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  15547. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  15548. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  15549. set.
  15550. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  15551. */
  15552. void QCPAxisRect::drawBackground(QCPPainter *painter)
  15553. {
  15554. // draw background fill:
  15555. if (mBackgroundBrush != Qt::NoBrush)
  15556. painter->fillRect(mRect, mBackgroundBrush);
  15557. // draw background pixmap (on top of fill, if brush specified):
  15558. if (!mBackgroundPixmap.isNull())
  15559. {
  15560. if (mBackgroundScaled)
  15561. {
  15562. // check whether mScaledBackground needs to be updated:
  15563. QSize scaledSize(mBackgroundPixmap.size());
  15564. scaledSize.scale(mRect.size(), mBackgroundScaledMode);
  15565. if (mScaledBackgroundPixmap.size() != scaledSize)
  15566. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  15567. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
  15568. } else
  15569. {
  15570. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
  15571. }
  15572. }
  15573. }
  15574. /*! \internal
  15575. This function makes sure multiple axes on the side specified with \a type don't collide, but are
  15576. distributed according to their respective space requirement (QCPAxis::calculateMargin).
  15577. It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the
  15578. one with index zero.
  15579. This function is called by \ref calculateAutoMargin.
  15580. */
  15581. void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type)
  15582. {
  15583. const QList<QCPAxis*> axesList = mAxes.value(type);
  15584. if (axesList.isEmpty())
  15585. return;
  15586. 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
  15587. for (int i=1; i<axesList.size(); ++i)
  15588. {
  15589. int offset = axesList.at(i-1)->offset() + axesList.at(i-1)->calculateMargin();
  15590. 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)
  15591. {
  15592. if (!isFirstVisible)
  15593. offset += axesList.at(i)->tickLengthIn();
  15594. isFirstVisible = false;
  15595. }
  15596. axesList.at(i)->setOffset(offset);
  15597. }
  15598. }
  15599. /* inherits documentation from base class */
  15600. int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side)
  15601. {
  15602. if (!mAutoMargins.testFlag(side))
  15603. qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin";
  15604. updateAxesOffset(QCPAxis::marginSideToAxisType(side));
  15605. // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call
  15606. const QList<QCPAxis*> axesList = mAxes.value(QCPAxis::marginSideToAxisType(side));
  15607. if (!axesList.isEmpty())
  15608. return axesList.last()->offset() + axesList.last()->calculateMargin();
  15609. else
  15610. return 0;
  15611. }
  15612. /*! \internal
  15613. Reacts to a change in layout to potentially set the convenience axis pointers \ref
  15614. QCustomPlot::xAxis, \ref QCustomPlot::yAxis, etc. of the parent QCustomPlot to the respective
  15615. axes of this axis rect. This is only done if the respective convenience pointer is currently zero
  15616. and if there is no QCPAxisRect at position (0, 0) of the plot layout.
  15617. This automation makes it simpler to replace the main axis rect with a newly created one, without
  15618. the need to manually reset the convenience pointers.
  15619. */
  15620. void QCPAxisRect::layoutChanged()
  15621. {
  15622. if (mParentPlot && mParentPlot->axisRectCount() > 0 && mParentPlot->axisRect(0) == this)
  15623. {
  15624. if (axisCount(QCPAxis::AxisType::atBottom) > 0 && !mParentPlot->xAxis)
  15625. mParentPlot->xAxis = axis(QCPAxis::AxisType::atBottom);
  15626. if (axisCount(QCPAxis::AxisType::atLeft) > 0 && !mParentPlot->yAxis)
  15627. mParentPlot->yAxis = axis(QCPAxis::AxisType::atLeft);
  15628. if (axisCount(QCPAxis::AxisType::atTop) > 0 && !mParentPlot->xAxis2)
  15629. mParentPlot->xAxis2 = axis(QCPAxis::AxisType::atTop);
  15630. if (axisCount(QCPAxis::AxisType::atRight) > 0 && !mParentPlot->yAxis2)
  15631. mParentPlot->yAxis2 = axis(QCPAxis::AxisType::atRight);
  15632. }
  15633. }
  15634. /*! \internal
  15635. Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
  15636. pressed, the range dragging interaction is initialized (the actual range manipulation happens in
  15637. the \ref mouseMoveEvent).
  15638. The mDragging flag is set to true and some anchor points are set that are needed to determine the
  15639. distance the mouse was dragged in the mouse move/release events later.
  15640. \see mouseMoveEvent, mouseReleaseEvent
  15641. */
  15642. void QCPAxisRect::mousePressEvent(QMouseEvent *event, const QVariant &details)
  15643. {
  15644. Q_UNUSED(details)
  15645. if (event->buttons() & Qt::LeftButton)
  15646. {
  15647. mDragging = true;
  15648. // initialize antialiasing backup in case we start dragging:
  15649. if (mParentPlot->noAntialiasingOnDrag())
  15650. {
  15651. mAADragBackup = mParentPlot->antialiasedElements();
  15652. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  15653. }
  15654. // Mouse range dragging interaction:
  15655. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  15656. {
  15657. mDragStartHorzRange.clear();
  15658. foreach (QPointer<QCPAxis> axis, mRangeDragHorzAxis)
  15659. mDragStartHorzRange.append(axis.isNull() ? QCPRange() : axis->range());
  15660. mDragStartVertRange.clear();
  15661. foreach (QPointer<QCPAxis> axis, mRangeDragVertAxis)
  15662. mDragStartVertRange.append(axis.isNull() ? QCPRange() : axis->range());
  15663. }
  15664. }
  15665. }
  15666. /*! \internal
  15667. Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
  15668. preceding \ref mousePressEvent, the range is moved accordingly.
  15669. \see mousePressEvent, mouseReleaseEvent
  15670. */
  15671. void QCPAxisRect::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  15672. {
  15673. Q_UNUSED(startPos)
  15674. // Mouse range dragging interaction:
  15675. if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  15676. {
  15677. if (mRangeDrag.testFlag(Qt::Horizontal))
  15678. {
  15679. for (int i=0; i<mRangeDragHorzAxis.size(); ++i)
  15680. {
  15681. QCPAxis *ax = mRangeDragHorzAxis.at(i).data();
  15682. if (!ax)
  15683. continue;
  15684. if (i >= mDragStartHorzRange.size())
  15685. break;
  15686. if (ax->mScaleType == QCPAxis::ScaleType::stLinear)
  15687. {
  15688. double diff = ax->pixelToCoord(startPos.x()) - ax->pixelToCoord(event->pos().x());
  15689. ax->setRange(mDragStartHorzRange.at(i).lower+diff, mDragStartHorzRange.at(i).upper+diff);
  15690. } else if (ax->mScaleType == QCPAxis::ScaleType::stLogarithmic)
  15691. {
  15692. double diff = ax->pixelToCoord(startPos.x()) / ax->pixelToCoord(event->pos().x());
  15693. ax->setRange(mDragStartHorzRange.at(i).lower*diff, mDragStartHorzRange.at(i).upper*diff);
  15694. }
  15695. }
  15696. }
  15697. if (mRangeDrag.testFlag(Qt::Vertical))
  15698. {
  15699. for (int i=0; i<mRangeDragVertAxis.size(); ++i)
  15700. {
  15701. QCPAxis *ax = mRangeDragVertAxis.at(i).data();
  15702. if (!ax)
  15703. continue;
  15704. if (i >= mDragStartVertRange.size())
  15705. break;
  15706. if (ax->mScaleType == QCPAxis::ScaleType::stLinear)
  15707. {
  15708. double diff = ax->pixelToCoord(startPos.y()) - ax->pixelToCoord(event->pos().y());
  15709. ax->setRange(mDragStartVertRange.at(i).lower+diff, mDragStartVertRange.at(i).upper+diff);
  15710. } else if (ax->mScaleType == QCPAxis::ScaleType::stLogarithmic)
  15711. {
  15712. double diff = ax->pixelToCoord(startPos.y()) / ax->pixelToCoord(event->pos().y());
  15713. ax->setRange(mDragStartVertRange.at(i).lower*diff, mDragStartVertRange.at(i).upper*diff);
  15714. }
  15715. }
  15716. }
  15717. if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot
  15718. {
  15719. if (mParentPlot->noAntialiasingOnDrag())
  15720. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  15721. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  15722. }
  15723. }
  15724. }
  15725. /* inherits documentation from base class */
  15726. void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  15727. {
  15728. Q_UNUSED(event)
  15729. Q_UNUSED(startPos)
  15730. mDragging = false;
  15731. if (mParentPlot->noAntialiasingOnDrag())
  15732. {
  15733. mParentPlot->setAntialiasedElements(mAADragBackup);
  15734. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  15735. }
  15736. }
  15737. /*! \internal
  15738. Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
  15739. ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
  15740. the scaling operation is the current cursor position inside the axis rect. The scaling factor is
  15741. dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
  15742. zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
  15743. Note, that event->angleDelta() is usually +/-120 for single rotation steps. However, if the mouse
  15744. wheel is turned rapidly, many steps may bunch up to one event, so the delta may then be multiples
  15745. of 120. This is taken into account here, by calculating \a wheelSteps and using it as exponent of
  15746. the range zoom factor. This takes care of the wheel direction automatically, by inverting the
  15747. factor, when the wheel step is negative (f^-1 = 1/f).
  15748. */
  15749. void QCPAxisRect::wheelEvent(QWheelEvent *event)
  15750. {
  15751. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  15752. const double delta = event->delta();
  15753. #else
  15754. const double delta = event->angleDelta().y();
  15755. #endif
  15756. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  15757. const QPointF pos = event->pos();
  15758. #else
  15759. const QPointF pos = event->position();
  15760. #endif
  15761. // Mouse range zooming interaction:
  15762. if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  15763. {
  15764. if (mRangeZoom != 0)
  15765. {
  15766. double factor;
  15767. double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
  15768. if (mRangeZoom.testFlag(Qt::Horizontal))
  15769. {
  15770. factor = qPow(mRangeZoomFactorHorz, wheelSteps);
  15771. foreach (QPointer<QCPAxis> axis, mRangeZoomHorzAxis)
  15772. {
  15773. if (!axis.isNull())
  15774. axis->scaleRange(factor, axis->pixelToCoord(pos.x()));
  15775. }
  15776. }
  15777. if (mRangeZoom.testFlag(Qt::Vertical))
  15778. {
  15779. factor = qPow(mRangeZoomFactorVert, wheelSteps);
  15780. foreach (QPointer<QCPAxis> axis, mRangeZoomVertAxis)
  15781. {
  15782. if (!axis.isNull())
  15783. axis->scaleRange(factor, axis->pixelToCoord(pos.y()));
  15784. }
  15785. }
  15786. mParentPlot->replot();
  15787. }
  15788. }
  15789. }
  15790. /* end of 'src/layoutelements/layoutelement-axisrect.cpp' */
  15791. /* including file 'src/layoutelements/layoutelement-legend.cpp' */
  15792. /* modified 2021-03-29T02:30:44, size 31762 */
  15793. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15794. //////////////////// QCPAbstractLegendItem
  15795. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15796. /*! \class QCPAbstractLegendItem
  15797. \brief The abstract base class for all entries in a QCPLegend.
  15798. It defines a very basic interface for entries in a QCPLegend. For representing plottables in the
  15799. legend, the subclass \ref QCPPlottableLegendItem is more suitable.
  15800. Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry
  15801. that's not even associated with a plottable).
  15802. You must implement the following pure virtual functions:
  15803. \li \ref draw (from QCPLayerable)
  15804. You inherit the following members you may use:
  15805. <table>
  15806. <tr>
  15807. <td>QCPLegend *\b mParentLegend</td>
  15808. <td>A pointer to the parent QCPLegend.</td>
  15809. </tr><tr>
  15810. <td>QFont \b mFont</td>
  15811. <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>
  15812. </tr>
  15813. </table>
  15814. */
  15815. /* start of documentation of signals */
  15816. /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected)
  15817. This signal is emitted when the selection state of this legend item has changed, either by user
  15818. interaction or by a direct call to \ref setSelected.
  15819. */
  15820. /* end of documentation of signals */
  15821. /*!
  15822. Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not
  15823. cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately.
  15824. */
  15825. QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) :
  15826. QCPLayoutElement(parent->parentPlot()),
  15827. mParentLegend(parent),
  15828. mFont(parent->font()),
  15829. mTextColor(parent->textColor()),
  15830. mSelectedFont(parent->selectedFont()),
  15831. mSelectedTextColor(parent->selectedTextColor()),
  15832. mSelectable(true),
  15833. mSelected(false)
  15834. {
  15835. setLayer(QLatin1String("legend"));
  15836. setMargins(QMargins(0, 0, 0, 0));
  15837. }
  15838. /*!
  15839. Sets the default font of this specific legend item to \a font.
  15840. \see setTextColor, QCPLegend::setFont
  15841. */
  15842. void QCPAbstractLegendItem::setFont(const QFont &font)
  15843. {
  15844. mFont = font;
  15845. }
  15846. /*!
  15847. Sets the default text color of this specific legend item to \a color.
  15848. \see setFont, QCPLegend::setTextColor
  15849. */
  15850. void QCPAbstractLegendItem::setTextColor(const QColor &color)
  15851. {
  15852. mTextColor = color;
  15853. }
  15854. /*!
  15855. When this legend item is selected, \a font is used to draw generic text, instead of the normal
  15856. font set with \ref setFont.
  15857. \see setFont, QCPLegend::setSelectedFont
  15858. */
  15859. void QCPAbstractLegendItem::setSelectedFont(const QFont &font)
  15860. {
  15861. mSelectedFont = font;
  15862. }
  15863. /*!
  15864. When this legend item is selected, \a color is used to draw generic text, instead of the normal
  15865. color set with \ref setTextColor.
  15866. \see setTextColor, QCPLegend::setSelectedTextColor
  15867. */
  15868. void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color)
  15869. {
  15870. mSelectedTextColor = color;
  15871. }
  15872. /*!
  15873. Sets whether this specific legend item is selectable.
  15874. \see setSelectedParts, QCustomPlot::setInteractions
  15875. */
  15876. void QCPAbstractLegendItem::setSelectable(bool selectable)
  15877. {
  15878. if (mSelectable != selectable)
  15879. {
  15880. mSelectable = selectable;
  15881. emit selectableChanged(mSelectable);
  15882. }
  15883. }
  15884. /*!
  15885. Sets whether this specific legend item is selected.
  15886. It is possible to set the selection state of this item by calling this function directly, even if
  15887. setSelectable is set to false.
  15888. \see setSelectableParts, QCustomPlot::setInteractions
  15889. */
  15890. void QCPAbstractLegendItem::setSelected(bool selected)
  15891. {
  15892. if (mSelected != selected)
  15893. {
  15894. mSelected = selected;
  15895. emit selectionChanged(mSelected);
  15896. }
  15897. }
  15898. /* inherits documentation from base class */
  15899. double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  15900. {
  15901. Q_UNUSED(details)
  15902. if (!mParentPlot) return -1;
  15903. if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems)))
  15904. return -1;
  15905. if (mRect.contains(pos.toPoint()))
  15906. return mParentPlot->selectionTolerance()*0.99;
  15907. else
  15908. return -1;
  15909. }
  15910. /* inherits documentation from base class */
  15911. void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const
  15912. {
  15913. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems);
  15914. }
  15915. /* inherits documentation from base class */
  15916. QRect QCPAbstractLegendItem::clipRect() const
  15917. {
  15918. return mOuterRect;
  15919. }
  15920. /* inherits documentation from base class */
  15921. void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  15922. {
  15923. Q_UNUSED(event)
  15924. Q_UNUSED(details)
  15925. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
  15926. {
  15927. bool selBefore = mSelected;
  15928. setSelected(additive ? !mSelected : true);
  15929. if (selectionStateChanged)
  15930. *selectionStateChanged = mSelected != selBefore;
  15931. }
  15932. }
  15933. /* inherits documentation from base class */
  15934. void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged)
  15935. {
  15936. if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems))
  15937. {
  15938. bool selBefore = mSelected;
  15939. setSelected(false);
  15940. if (selectionStateChanged)
  15941. *selectionStateChanged = mSelected != selBefore;
  15942. }
  15943. }
  15944. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15945. //////////////////// QCPPlottableLegendItem
  15946. ////////////////////////////////////////////////////////////////////////////////////////////////////
  15947. /*! \class QCPPlottableLegendItem
  15948. \brief A legend item representing a plottable with an icon and the plottable name.
  15949. This is the standard legend item for plottables. It displays an icon of the plottable next to the
  15950. plottable name. The icon is drawn by the respective plottable itself (\ref
  15951. QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable.
  15952. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the
  15953. middle.
  15954. Legend items of this type are always associated with one plottable (retrievable via the
  15955. plottable() function and settable with the constructor). You may change the font of the plottable
  15956. name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref
  15957. QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding.
  15958. The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend
  15959. creates/removes legend items of this type.
  15960. Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of
  15961. QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout
  15962. interface, QCPLegend has specialized functions for handling legend items conveniently, see the
  15963. documentation of \ref QCPLegend.
  15964. */
  15965. /*!
  15966. Creates a new legend item associated with \a plottable.
  15967. Once it's created, it can be added to the legend via \ref QCPLegend::addItem.
  15968. A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref
  15969. QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend.
  15970. */
  15971. QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) :
  15972. QCPAbstractLegendItem(parent),
  15973. mPlottable(plottable)
  15974. {
  15975. setAntialiased(false);
  15976. }
  15977. /*! \internal
  15978. Returns the pen that shall be used to draw the icon border, taking into account the selection
  15979. state of this item.
  15980. */
  15981. QPen QCPPlottableLegendItem::getIconBorderPen() const
  15982. {
  15983. return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
  15984. }
  15985. /*! \internal
  15986. Returns the text color that shall be used to draw text, taking into account the selection state
  15987. of this item.
  15988. */
  15989. QColor QCPPlottableLegendItem::getTextColor() const
  15990. {
  15991. return mSelected ? mSelectedTextColor : mTextColor;
  15992. }
  15993. /*! \internal
  15994. Returns the font that shall be used to draw text, taking into account the selection state of this
  15995. item.
  15996. */
  15997. QFont QCPPlottableLegendItem::getFont() const
  15998. {
  15999. return mSelected ? mSelectedFont : mFont;
  16000. }
  16001. /*! \internal
  16002. Draws the item with \a painter. The size and position of the drawn legend item is defined by the
  16003. parent layout (typically a \ref QCPLegend) and the \ref minimumOuterSizeHint and \ref
  16004. maximumOuterSizeHint of this legend item.
  16005. */
  16006. void QCPPlottableLegendItem::draw(QCPPainter *painter)
  16007. {
  16008. if (!mPlottable) return;
  16009. painter->setFont(getFont());
  16010. painter->setPen(QPen(getTextColor()));
  16011. QSize iconSize = mParentLegend->iconSize();
  16012. QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  16013. QRect iconRect(mRect.topLeft(), iconSize);
  16014. int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
  16015. painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name());
  16016. // draw icon:
  16017. painter->save();
  16018. painter->setClipRect(iconRect, Qt::IntersectClip);
  16019. mPlottable->drawLegendIcon(painter, iconRect);
  16020. painter->restore();
  16021. // draw icon border:
  16022. if (getIconBorderPen().style() != Qt::NoPen)
  16023. {
  16024. painter->setPen(getIconBorderPen());
  16025. painter->setBrush(Qt::NoBrush);
  16026. int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
  16027. painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
  16028. painter->drawRect(iconRect);
  16029. }
  16030. }
  16031. /*! \internal
  16032. Calculates and returns the size of this item. This includes the icon, the text and the padding in
  16033. between.
  16034. \seebaseclassmethod
  16035. */
  16036. QSize QCPPlottableLegendItem::minimumOuterSizeHint() const
  16037. {
  16038. if (!mPlottable) return {};
  16039. QSize result(0, 0);
  16040. QRect textRect;
  16041. QFontMetrics fontMetrics(getFont());
  16042. QSize iconSize = mParentLegend->iconSize();
  16043. textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name());
  16044. result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width());
  16045. result.setHeight(qMax(textRect.height(), iconSize.height()));
  16046. result.rwidth() += mMargins.left()+mMargins.right();
  16047. result.rheight() += mMargins.top()+mMargins.bottom();
  16048. return result;
  16049. }
  16050. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16051. //////////////////// QCPLegend
  16052. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16053. /*! \class QCPLegend
  16054. \brief Manages a legend inside a QCustomPlot.
  16055. A legend is a small box somewhere in the plot which lists plottables with their name and icon.
  16056. A legend is populated with legend items by calling \ref QCPAbstractPlottable::addToLegend on the
  16057. plottable, for which a legend item shall be created. In the case of the main legend (\ref
  16058. QCustomPlot::legend), simply adding plottables to the plot while \ref
  16059. QCustomPlot::setAutoAddPlottableToLegend is set to true (the default) creates corresponding
  16060. legend items. The legend item associated with a certain plottable can be removed with \ref
  16061. QCPAbstractPlottable::removeFromLegend. However, QCPLegend also offers an interface to add and
  16062. manipulate legend items directly: \ref item, \ref itemWithPlottable, \ref itemCount, \ref
  16063. addItem, \ref removeItem, etc.
  16064. Since \ref QCPLegend derives from \ref QCPLayoutGrid, it can be placed in any position a \ref
  16065. QCPLayoutElement may be positioned. The legend items are themselves \ref QCPLayoutElement
  16066. "QCPLayoutElements" which are placed in the grid layout of the legend. \ref QCPLegend only adds
  16067. an interface specialized for handling child elements of type \ref QCPAbstractLegendItem, as
  16068. mentioned above. In principle, any other layout elements may also be added to a legend via the
  16069. normal \ref QCPLayoutGrid interface. See the special page about \link thelayoutsystem The Layout
  16070. System\endlink for examples on how to add other elements to the legend and move it outside the axis
  16071. rect.
  16072. Use the methods \ref setFillOrder and \ref setWrap inherited from \ref QCPLayoutGrid to control
  16073. in which order (column first or row first) the legend is filled up when calling \ref addItem, and
  16074. at which column or row wrapping occurs. The default fill order for legends is \ref foRowsFirst.
  16075. By default, every QCustomPlot has one legend (\ref QCustomPlot::legend) which is placed in the
  16076. inset layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another
  16077. position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend
  16078. outside of the axis rect, place it anywhere else with the \ref QCPLayout/\ref QCPLayoutElement
  16079. interface.
  16080. */
  16081. /* start of documentation of signals */
  16082. /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection);
  16083. This signal is emitted when the selection state of this legend has changed.
  16084. \see setSelectedParts, setSelectableParts
  16085. */
  16086. /* end of documentation of signals */
  16087. /*!
  16088. Constructs a new QCPLegend instance with default values.
  16089. Note that by default, QCustomPlot already contains a legend ready to be used as \ref
  16090. QCustomPlot::legend
  16091. */
  16092. QCPLegend::QCPLegend() :
  16093. mIconTextPadding{}
  16094. {
  16095. setFillOrder(QCPLayoutGrid::FillOrder::foRowsFirst);
  16096. setWrap(0);
  16097. setRowSpacing(3);
  16098. setColumnSpacing(8);
  16099. setMargins(QMargins(7, 5, 7, 4));
  16100. setAntialiased(false);
  16101. setIconSize(32, 18);
  16102. setIconTextPadding(7);
  16103. setSelectableParts(spLegendBox | spItems);
  16104. setSelectedParts(spNone);
  16105. setBorderPen(QPen(Qt::black, 0));
  16106. setSelectedBorderPen(QPen(Qt::blue, 2));
  16107. setIconBorderPen(Qt::NoPen);
  16108. setSelectedIconBorderPen(QPen(Qt::blue, 2));
  16109. setBrush(Qt::white);
  16110. setSelectedBrush(Qt::white);
  16111. setTextColor(Qt::black);
  16112. setSelectedTextColor(Qt::blue);
  16113. }
  16114. QCPLegend::~QCPLegend()
  16115. {
  16116. clearItems();
  16117. 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)
  16118. mParentPlot->legendRemoved(this);
  16119. }
  16120. /* no doc for getter, see setSelectedParts */
  16121. QCPLegend::SelectableParts QCPLegend::selectedParts() const
  16122. {
  16123. // check whether any legend elements selected, if yes, add spItems to return value
  16124. bool hasSelectedItems = false;
  16125. for (int i=0; i<itemCount(); ++i)
  16126. {
  16127. if (item(i) && item(i)->selected())
  16128. {
  16129. hasSelectedItems = true;
  16130. break;
  16131. }
  16132. }
  16133. if (hasSelectedItems)
  16134. return mSelectedParts | spItems;
  16135. else
  16136. return mSelectedParts & ~spItems;
  16137. }
  16138. /*!
  16139. Sets the pen, the border of the entire legend is drawn with.
  16140. */
  16141. void QCPLegend::setBorderPen(const QPen &pen)
  16142. {
  16143. mBorderPen = pen;
  16144. }
  16145. /*!
  16146. Sets the brush of the legend background.
  16147. */
  16148. void QCPLegend::setBrush(const QBrush &brush)
  16149. {
  16150. mBrush = brush;
  16151. }
  16152. /*!
  16153. Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will
  16154. use this font by default. However, a different font can be specified on a per-item-basis by
  16155. accessing the specific legend item.
  16156. This function will also set \a font on all already existing legend items.
  16157. \see QCPAbstractLegendItem::setFont
  16158. */
  16159. void QCPLegend::setFont(const QFont &font)
  16160. {
  16161. mFont = font;
  16162. for (int i=0; i<itemCount(); ++i)
  16163. {
  16164. if (item(i))
  16165. item(i)->setFont(mFont);
  16166. }
  16167. }
  16168. /*!
  16169. Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph)
  16170. will use this color by default. However, a different colors can be specified on a per-item-basis
  16171. by accessing the specific legend item.
  16172. This function will also set \a color on all already existing legend items.
  16173. \see QCPAbstractLegendItem::setTextColor
  16174. */
  16175. void QCPLegend::setTextColor(const QColor &color)
  16176. {
  16177. mTextColor = color;
  16178. for (int i=0; i<itemCount(); ++i)
  16179. {
  16180. if (item(i))
  16181. item(i)->setTextColor(color);
  16182. }
  16183. }
  16184. /*!
  16185. Sets the size of legend icons. Legend items that draw an icon (e.g. a visual
  16186. representation of the graph) will use this size by default.
  16187. */
  16188. void QCPLegend::setIconSize(const QSize &size)
  16189. {
  16190. mIconSize = size;
  16191. }
  16192. /*! \overload
  16193. */
  16194. void QCPLegend::setIconSize(int width, int height)
  16195. {
  16196. mIconSize.setWidth(width);
  16197. mIconSize.setHeight(height);
  16198. }
  16199. /*!
  16200. Sets the horizontal space in pixels between the legend icon and the text next to it.
  16201. Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the
  16202. name of the graph) will use this space by default.
  16203. */
  16204. void QCPLegend::setIconTextPadding(int padding)
  16205. {
  16206. mIconTextPadding = padding;
  16207. }
  16208. /*!
  16209. Sets the pen used to draw a border around each legend icon. Legend items that draw an
  16210. icon (e.g. a visual representation of the graph) will use this pen by default.
  16211. If no border is wanted, set this to \a Qt::NoPen.
  16212. */
  16213. void QCPLegend::setIconBorderPen(const QPen &pen)
  16214. {
  16215. mIconBorderPen = pen;
  16216. }
  16217. /*!
  16218. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  16219. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.)
  16220. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  16221. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  16222. directly.
  16223. \see SelectablePart, setSelectedParts
  16224. */
  16225. void QCPLegend::setSelectableParts(const SelectableParts &selectable)
  16226. {
  16227. if (mSelectableParts != selectable)
  16228. {
  16229. mSelectableParts = selectable;
  16230. emit selectableChanged(mSelectableParts);
  16231. }
  16232. }
  16233. /*!
  16234. Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part
  16235. is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected
  16236. doesn't contain \ref spItems, those items become deselected.
  16237. The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions
  16238. contains iSelectLegend. You only need to call this function when you wish to change the selection
  16239. state manually.
  16240. This function can change the selection state of a part even when \ref setSelectableParts was set to a
  16241. value that actually excludes the part.
  16242. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  16243. Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set
  16244. before, because there's no way to specify which exact items to newly select. Do this by calling
  16245. \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select.
  16246. \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush,
  16247. setSelectedFont
  16248. */
  16249. void QCPLegend::setSelectedParts(const SelectableParts &selected)
  16250. {
  16251. SelectableParts newSelected = selected;
  16252. mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed
  16253. if (mSelectedParts != newSelected)
  16254. {
  16255. if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that)
  16256. {
  16257. qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function";
  16258. newSelected &= ~spItems;
  16259. }
  16260. if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection
  16261. {
  16262. for (int i=0; i<itemCount(); ++i)
  16263. {
  16264. if (item(i))
  16265. item(i)->setSelected(false);
  16266. }
  16267. }
  16268. mSelectedParts = newSelected;
  16269. emit selectionChanged(mSelectedParts);
  16270. }
  16271. }
  16272. /*!
  16273. When the legend box is selected, this pen is used to draw the border instead of the normal pen
  16274. set via \ref setBorderPen.
  16275. \see setSelectedParts, setSelectableParts, setSelectedBrush
  16276. */
  16277. void QCPLegend::setSelectedBorderPen(const QPen &pen)
  16278. {
  16279. mSelectedBorderPen = pen;
  16280. }
  16281. /*!
  16282. Sets the pen legend items will use to draw their icon borders, when they are selected.
  16283. \see setSelectedParts, setSelectableParts, setSelectedFont
  16284. */
  16285. void QCPLegend::setSelectedIconBorderPen(const QPen &pen)
  16286. {
  16287. mSelectedIconBorderPen = pen;
  16288. }
  16289. /*!
  16290. When the legend box is selected, this brush is used to draw the legend background instead of the normal brush
  16291. set via \ref setBrush.
  16292. \see setSelectedParts, setSelectableParts, setSelectedBorderPen
  16293. */
  16294. void QCPLegend::setSelectedBrush(const QBrush &brush)
  16295. {
  16296. mSelectedBrush = brush;
  16297. }
  16298. /*!
  16299. Sets the default font that is used by legend items when they are selected.
  16300. This function will also set \a font on all already existing legend items.
  16301. \see setFont, QCPAbstractLegendItem::setSelectedFont
  16302. */
  16303. void QCPLegend::setSelectedFont(const QFont &font)
  16304. {
  16305. mSelectedFont = font;
  16306. for (int i=0; i<itemCount(); ++i)
  16307. {
  16308. if (item(i))
  16309. item(i)->setSelectedFont(font);
  16310. }
  16311. }
  16312. /*!
  16313. Sets the default text color that is used by legend items when they are selected.
  16314. This function will also set \a color on all already existing legend items.
  16315. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor
  16316. */
  16317. void QCPLegend::setSelectedTextColor(const QColor &color)
  16318. {
  16319. mSelectedTextColor = color;
  16320. for (int i=0; i<itemCount(); ++i)
  16321. {
  16322. if (item(i))
  16323. item(i)->setSelectedTextColor(color);
  16324. }
  16325. }
  16326. /*!
  16327. Returns the item with index \a i. If non-legend items were added to the legend, and the element
  16328. at the specified cell index is not a QCPAbstractLegendItem, returns \c nullptr.
  16329. Note that the linear index depends on the current fill order (\ref setFillOrder).
  16330. \see itemCount, addItem, itemWithPlottable
  16331. */
  16332. QCPAbstractLegendItem *QCPLegend::item(int index) const
  16333. {
  16334. return qobject_cast<QCPAbstractLegendItem*>(elementAt(index));
  16335. }
  16336. /*!
  16337. Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  16338. If such an item isn't in the legend, returns \c nullptr.
  16339. \see hasItemWithPlottable
  16340. */
  16341. QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const
  16342. {
  16343. for (int i=0; i<itemCount(); ++i)
  16344. {
  16345. if (QCPPlottableLegendItem *pli = qobject_cast<QCPPlottableLegendItem*>(item(i)))
  16346. {
  16347. if (pli->plottable() == plottable)
  16348. return pli;
  16349. }
  16350. }
  16351. return nullptr;
  16352. }
  16353. /*!
  16354. Returns the number of items currently in the legend. It is identical to the base class
  16355. QCPLayoutGrid::elementCount(), and unlike the other "item" interface methods of QCPLegend,
  16356. doesn't only address elements which can be cast to QCPAbstractLegendItem.
  16357. Note that if empty cells are in the legend (e.g. by calling methods of the \ref QCPLayoutGrid
  16358. base class which allows creating empty cells), they are included in the returned count.
  16359. \see item
  16360. */
  16361. int QCPLegend::itemCount() const
  16362. {
  16363. return elementCount();
  16364. }
  16365. /*!
  16366. Returns whether the legend contains \a item.
  16367. \see hasItemWithPlottable
  16368. */
  16369. bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const
  16370. {
  16371. for (int i=0; i<itemCount(); ++i)
  16372. {
  16373. if (item == this->item(i))
  16374. return true;
  16375. }
  16376. return false;
  16377. }
  16378. /*!
  16379. Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*).
  16380. If such an item isn't in the legend, returns false.
  16381. \see itemWithPlottable
  16382. */
  16383. bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const
  16384. {
  16385. return itemWithPlottable(plottable);
  16386. }
  16387. /*!
  16388. Adds \a item to the legend, if it's not present already. The element is arranged according to the
  16389. current fill order (\ref setFillOrder) and wrapping (\ref setWrap).
  16390. Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added.
  16391. The legend takes ownership of the item.
  16392. \see removeItem, item, hasItem
  16393. */
  16394. bool QCPLegend::addItem(QCPAbstractLegendItem *item)
  16395. {
  16396. return addElement(item);
  16397. }
  16398. /*! \overload
  16399. Removes the item with the specified \a index from the legend and deletes it.
  16400. After successful removal, the legend is reordered according to the current fill order (\ref
  16401. setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
  16402. was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
  16403. Returns true, if successful. Unlike \ref QCPLayoutGrid::removeAt, this method only removes
  16404. elements derived from \ref QCPAbstractLegendItem.
  16405. \see itemCount, clearItems
  16406. */
  16407. bool QCPLegend::removeItem(int index)
  16408. {
  16409. if (QCPAbstractLegendItem *ali = item(index))
  16410. {
  16411. bool success = remove(ali);
  16412. if (success)
  16413. setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
  16414. return success;
  16415. } else
  16416. return false;
  16417. }
  16418. /*! \overload
  16419. Removes \a item from the legend and deletes it.
  16420. After successful removal, the legend is reordered according to the current fill order (\ref
  16421. setFillOrder) and wrapping (\ref setWrap), so no empty cell remains where the removed \a item
  16422. was. If you don't want this, rather use the raw element interface of \ref QCPLayoutGrid.
  16423. Returns true, if successful.
  16424. \see clearItems
  16425. */
  16426. bool QCPLegend::removeItem(QCPAbstractLegendItem *item)
  16427. {
  16428. bool success = remove(item);
  16429. if (success)
  16430. setFillOrder(fillOrder(), true); // gets rid of empty cell by reordering
  16431. return success;
  16432. }
  16433. /*!
  16434. Removes all items from the legend.
  16435. */
  16436. void QCPLegend::clearItems()
  16437. {
  16438. for (int i=elementCount()-1; i>=0; --i)
  16439. {
  16440. if (item(i))
  16441. removeAt(i); // don't use removeItem() because it would unnecessarily reorder the whole legend for each item
  16442. }
  16443. setFillOrder(fillOrder(), true); // get rid of empty cells by reordering once after all items are removed
  16444. }
  16445. /*!
  16446. Returns the legend items that are currently selected. If no items are selected,
  16447. the list is empty.
  16448. \see QCPAbstractLegendItem::setSelected, setSelectable
  16449. */
  16450. QList<QCPAbstractLegendItem *> QCPLegend::selectedItems() const
  16451. {
  16452. QList<QCPAbstractLegendItem*> result;
  16453. for (int i=0; i<itemCount(); ++i)
  16454. {
  16455. if (QCPAbstractLegendItem *ali = item(i))
  16456. {
  16457. if (ali->selected())
  16458. result.append(ali);
  16459. }
  16460. }
  16461. return result;
  16462. }
  16463. /*! \internal
  16464. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  16465. before drawing main legend elements.
  16466. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  16467. This function takes into account the local setting of the antialiasing flag as well as the
  16468. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  16469. QCustomPlot::setNotAntialiasedElements.
  16470. \seebaseclassmethod
  16471. \see setAntialiased
  16472. */
  16473. void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const
  16474. {
  16475. applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend);
  16476. }
  16477. /*! \internal
  16478. Returns the pen used to paint the border of the legend, taking into account the selection state
  16479. of the legend box.
  16480. */
  16481. QPen QCPLegend::getBorderPen() const
  16482. {
  16483. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen;
  16484. }
  16485. /*! \internal
  16486. Returns the brush used to paint the background of the legend, taking into account the selection
  16487. state of the legend box.
  16488. */
  16489. QBrush QCPLegend::getBrush() const
  16490. {
  16491. return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush;
  16492. }
  16493. /*! \internal
  16494. Draws the legend box with the provided \a painter. The individual legend items are layerables
  16495. themselves, thus are drawn independently.
  16496. */
  16497. void QCPLegend::draw(QCPPainter *painter)
  16498. {
  16499. // draw background rect:
  16500. painter->setBrush(getBrush());
  16501. painter->setPen(getBorderPen());
  16502. painter->drawRect(mOuterRect);
  16503. }
  16504. /* inherits documentation from base class */
  16505. double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16506. {
  16507. if (!mParentPlot) return -1;
  16508. if (onlySelectable && !mSelectableParts.testFlag(spLegendBox))
  16509. return -1;
  16510. if (mOuterRect.contains(pos.toPoint()))
  16511. {
  16512. if (details) details->setValue(spLegendBox);
  16513. return mParentPlot->selectionTolerance()*0.99;
  16514. }
  16515. return -1;
  16516. }
  16517. /* inherits documentation from base class */
  16518. void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  16519. {
  16520. Q_UNUSED(event)
  16521. mSelectedParts = selectedParts(); // in case item selection has changed
  16522. if (details.value<SelectablePart>() == spLegendBox && mSelectableParts.testFlag(spLegendBox))
  16523. {
  16524. SelectableParts selBefore = mSelectedParts;
  16525. 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)
  16526. if (selectionStateChanged)
  16527. *selectionStateChanged = mSelectedParts != selBefore;
  16528. }
  16529. }
  16530. /* inherits documentation from base class */
  16531. void QCPLegend::deselectEvent(bool *selectionStateChanged)
  16532. {
  16533. mSelectedParts = selectedParts(); // in case item selection has changed
  16534. if (mSelectableParts.testFlag(spLegendBox))
  16535. {
  16536. SelectableParts selBefore = mSelectedParts;
  16537. setSelectedParts(selectedParts() & ~spLegendBox);
  16538. if (selectionStateChanged)
  16539. *selectionStateChanged = mSelectedParts != selBefore;
  16540. }
  16541. }
  16542. /* inherits documentation from base class */
  16543. QCP::Interaction QCPLegend::selectionCategory() const
  16544. {
  16545. return QCP::iSelectLegend;
  16546. }
  16547. /* inherits documentation from base class */
  16548. QCP::Interaction QCPAbstractLegendItem::selectionCategory() const
  16549. {
  16550. return QCP::iSelectLegend;
  16551. }
  16552. /* inherits documentation from base class */
  16553. void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot)
  16554. {
  16555. if (parentPlot && !parentPlot->legend)
  16556. parentPlot->legend = this;
  16557. }
  16558. /* end of 'src/layoutelements/layoutelement-legend.cpp' */
  16559. /* including file 'src/layoutelements/layoutelement-textelement.cpp' */
  16560. /* modified 2021-03-29T02:30:44, size 12925 */
  16561. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16562. //////////////////// QCPTextElement
  16563. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16564. /*! \class QCPTextElement
  16565. \brief A layout element displaying a text
  16566. The text may be specified with \ref setText, the formatting can be controlled with \ref setFont,
  16567. \ref setTextColor, and \ref setTextFlags.
  16568. A text element can be added as follows:
  16569. \snippet documentation/doc-code-snippets/mainwindow.cpp qcptextelement-creation
  16570. */
  16571. /* start documentation of signals */
  16572. /*! \fn void QCPTextElement::selectionChanged(bool selected)
  16573. This signal is emitted when the selection state has changed to \a selected, either by user
  16574. interaction or by a direct call to \ref setSelected.
  16575. \see setSelected, setSelectable
  16576. */
  16577. /*! \fn void QCPTextElement::clicked(QMouseEvent *event)
  16578. This signal is emitted when the text element is clicked.
  16579. \see doubleClicked, selectTest
  16580. */
  16581. /*! \fn void QCPTextElement::doubleClicked(QMouseEvent *event)
  16582. This signal is emitted when the text element is double clicked.
  16583. \see clicked, selectTest
  16584. */
  16585. /* end documentation of signals */
  16586. /*! \overload
  16587. Creates a new QCPTextElement instance and sets default values. The initial text is empty (\ref
  16588. setText).
  16589. */
  16590. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot) :
  16591. QCPLayoutElement(parentPlot),
  16592. mText(),
  16593. mTextFlags(Qt::AlignCenter),
  16594. mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16595. mTextColor(Qt::black),
  16596. mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16597. mSelectedTextColor(Qt::blue),
  16598. mSelectable(false),
  16599. mSelected(false)
  16600. {
  16601. if (parentPlot)
  16602. {
  16603. mFont = parentPlot->font();
  16604. mSelectedFont = parentPlot->font();
  16605. }
  16606. setMargins(QMargins(2, 2, 2, 2));
  16607. }
  16608. /*! \overload
  16609. Creates a new QCPTextElement instance and sets default values.
  16610. The initial text is set to \a text.
  16611. */
  16612. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text) :
  16613. QCPLayoutElement(parentPlot),
  16614. mText(text),
  16615. mTextFlags(Qt::AlignCenter),
  16616. mFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16617. mTextColor(Qt::black),
  16618. mSelectedFont(QFont(QLatin1String("sans serif"), 12)), // will be taken from parentPlot if available, see below
  16619. mSelectedTextColor(Qt::blue),
  16620. mSelectable(false),
  16621. mSelected(false)
  16622. {
  16623. if (parentPlot)
  16624. {
  16625. mFont = parentPlot->font();
  16626. mSelectedFont = parentPlot->font();
  16627. }
  16628. setMargins(QMargins(2, 2, 2, 2));
  16629. }
  16630. /*! \overload
  16631. Creates a new QCPTextElement instance and sets default values.
  16632. The initial text is set to \a text with \a pointSize.
  16633. */
  16634. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, double pointSize) :
  16635. QCPLayoutElement(parentPlot),
  16636. mText(text),
  16637. mTextFlags(Qt::AlignCenter),
  16638. mFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below
  16639. mTextColor(Qt::black),
  16640. mSelectedFont(QFont(QLatin1String("sans serif"), int(pointSize))), // will be taken from parentPlot if available, see below
  16641. mSelectedTextColor(Qt::blue),
  16642. mSelectable(false),
  16643. mSelected(false)
  16644. {
  16645. mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer
  16646. if (parentPlot)
  16647. {
  16648. mFont = parentPlot->font();
  16649. mFont.setPointSizeF(pointSize);
  16650. mSelectedFont = parentPlot->font();
  16651. mSelectedFont.setPointSizeF(pointSize);
  16652. }
  16653. setMargins(QMargins(2, 2, 2, 2));
  16654. }
  16655. /*! \overload
  16656. Creates a new QCPTextElement instance and sets default values.
  16657. The initial text is set to \a text with \a pointSize and the specified \a fontFamily.
  16658. */
  16659. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QString &fontFamily, double pointSize) :
  16660. QCPLayoutElement(parentPlot),
  16661. mText(text),
  16662. mTextFlags(Qt::AlignCenter),
  16663. mFont(QFont(fontFamily, int(pointSize))),
  16664. mTextColor(Qt::black),
  16665. mSelectedFont(QFont(fontFamily, int(pointSize))),
  16666. mSelectedTextColor(Qt::blue),
  16667. mSelectable(false),
  16668. mSelected(false)
  16669. {
  16670. mFont.setPointSizeF(pointSize); // set here again as floating point, because constructor above only takes integer
  16671. setMargins(QMargins(2, 2, 2, 2));
  16672. }
  16673. /*! \overload
  16674. Creates a new QCPTextElement instance and sets default values.
  16675. The initial text is set to \a text with the specified \a font.
  16676. */
  16677. QCPTextElement::QCPTextElement(QCustomPlot *parentPlot, const QString &text, const QFont &font) :
  16678. QCPLayoutElement(parentPlot),
  16679. mText(text),
  16680. mTextFlags(Qt::AlignCenter),
  16681. mFont(font),
  16682. mTextColor(Qt::black),
  16683. mSelectedFont(font),
  16684. mSelectedTextColor(Qt::blue),
  16685. mSelectable(false),
  16686. mSelected(false)
  16687. {
  16688. setMargins(QMargins(2, 2, 2, 2));
  16689. }
  16690. /*!
  16691. Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n".
  16692. \see setFont, setTextColor, setTextFlags
  16693. */
  16694. void QCPTextElement::setText(const QString &text)
  16695. {
  16696. mText = text;
  16697. }
  16698. /*!
  16699. Sets options for text alignment and wrapping behaviour. \a flags is a bitwise OR-combination of
  16700. \c Qt::AlignmentFlag and \c Qt::TextFlag enums.
  16701. Possible enums are:
  16702. - Qt::AlignLeft
  16703. - Qt::AlignRight
  16704. - Qt::AlignHCenter
  16705. - Qt::AlignJustify
  16706. - Qt::AlignTop
  16707. - Qt::AlignBottom
  16708. - Qt::AlignVCenter
  16709. - Qt::AlignCenter
  16710. - Qt::TextDontClip
  16711. - Qt::TextSingleLine
  16712. - Qt::TextExpandTabs
  16713. - Qt::TextShowMnemonic
  16714. - Qt::TextWordWrap
  16715. - Qt::TextIncludeTrailingSpaces
  16716. */
  16717. void QCPTextElement::setTextFlags(int flags)
  16718. {
  16719. mTextFlags = flags;
  16720. }
  16721. /*!
  16722. Sets the \a font of the text.
  16723. \see setTextColor, setSelectedFont
  16724. */
  16725. void QCPTextElement::setFont(const QFont &font)
  16726. {
  16727. mFont = font;
  16728. }
  16729. /*!
  16730. Sets the \a color of the text.
  16731. \see setFont, setSelectedTextColor
  16732. */
  16733. void QCPTextElement::setTextColor(const QColor &color)
  16734. {
  16735. mTextColor = color;
  16736. }
  16737. /*!
  16738. Sets the \a font of the text that will be used if the text element is selected (\ref setSelected).
  16739. \see setFont
  16740. */
  16741. void QCPTextElement::setSelectedFont(const QFont &font)
  16742. {
  16743. mSelectedFont = font;
  16744. }
  16745. /*!
  16746. Sets the \a color of the text that will be used if the text element is selected (\ref setSelected).
  16747. \see setTextColor
  16748. */
  16749. void QCPTextElement::setSelectedTextColor(const QColor &color)
  16750. {
  16751. mSelectedTextColor = color;
  16752. }
  16753. /*!
  16754. Sets whether the user may select this text element.
  16755. Note that even when \a selectable is set to <tt>false</tt>, the selection state may be changed
  16756. programmatically via \ref setSelected.
  16757. */
  16758. void QCPTextElement::setSelectable(bool selectable)
  16759. {
  16760. if (mSelectable != selectable)
  16761. {
  16762. mSelectable = selectable;
  16763. emit selectableChanged(mSelectable);
  16764. }
  16765. }
  16766. /*!
  16767. Sets the selection state of this text element to \a selected. If the selection has changed, \ref
  16768. selectionChanged is emitted.
  16769. Note that this function can change the selection state independently of the current \ref
  16770. setSelectable state.
  16771. */
  16772. void QCPTextElement::setSelected(bool selected)
  16773. {
  16774. if (mSelected != selected)
  16775. {
  16776. mSelected = selected;
  16777. emit selectionChanged(mSelected);
  16778. }
  16779. }
  16780. /* inherits documentation from base class */
  16781. void QCPTextElement::applyDefaultAntialiasingHint(QCPPainter *painter) const
  16782. {
  16783. applyAntialiasingHint(painter, mAntialiased, QCP::aeOther);
  16784. }
  16785. /* inherits documentation from base class */
  16786. void QCPTextElement::draw(QCPPainter *painter)
  16787. {
  16788. painter->setFont(mainFont());
  16789. painter->setPen(QPen(mainTextColor()));
  16790. painter->drawText(mRect, mTextFlags, mText, &mTextBoundingRect);
  16791. }
  16792. /* inherits documentation from base class */
  16793. QSize QCPTextElement::minimumOuterSizeHint() const
  16794. {
  16795. QFontMetrics metrics(mFont);
  16796. QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size());
  16797. result.rwidth() += mMargins.left()+mMargins.right();
  16798. result.rheight() += mMargins.top()+mMargins.bottom();
  16799. return result;
  16800. }
  16801. /* inherits documentation from base class */
  16802. QSize QCPTextElement::maximumOuterSizeHint() const
  16803. {
  16804. QFontMetrics metrics(mFont);
  16805. QSize result(metrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip, mText).size());
  16806. result.setWidth(QWIDGETSIZE_MAX);
  16807. result.rheight() += mMargins.top()+mMargins.bottom();
  16808. return result;
  16809. }
  16810. /* inherits documentation from base class */
  16811. void QCPTextElement::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  16812. {
  16813. Q_UNUSED(event)
  16814. Q_UNUSED(details)
  16815. if (mSelectable)
  16816. {
  16817. bool selBefore = mSelected;
  16818. setSelected(additive ? !mSelected : true);
  16819. if (selectionStateChanged)
  16820. *selectionStateChanged = mSelected != selBefore;
  16821. }
  16822. }
  16823. /* inherits documentation from base class */
  16824. void QCPTextElement::deselectEvent(bool *selectionStateChanged)
  16825. {
  16826. if (mSelectable)
  16827. {
  16828. bool selBefore = mSelected;
  16829. setSelected(false);
  16830. if (selectionStateChanged)
  16831. *selectionStateChanged = mSelected != selBefore;
  16832. }
  16833. }
  16834. /*!
  16835. Returns 0.99*selectionTolerance (see \ref QCustomPlot::setSelectionTolerance) when \a pos is
  16836. within the bounding box of the text element's text. Note that this bounding box is updated in the
  16837. draw call.
  16838. If \a pos is outside the text's bounding box or if \a onlySelectable is true and this text
  16839. element is not selectable (\ref setSelectable), returns -1.
  16840. \seebaseclassmethod
  16841. */
  16842. double QCPTextElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  16843. {
  16844. Q_UNUSED(details)
  16845. if (onlySelectable && !mSelectable)
  16846. return -1;
  16847. if (mTextBoundingRect.contains(pos.toPoint()))
  16848. return mParentPlot->selectionTolerance()*0.99;
  16849. else
  16850. return -1;
  16851. }
  16852. /*!
  16853. Accepts the mouse event in order to emit the according click signal in the \ref
  16854. mouseReleaseEvent.
  16855. \seebaseclassmethod
  16856. */
  16857. void QCPTextElement::mousePressEvent(QMouseEvent *event, const QVariant &details)
  16858. {
  16859. Q_UNUSED(details)
  16860. event->accept();
  16861. }
  16862. /*!
  16863. Emits the \ref clicked signal if the cursor hasn't moved by more than a few pixels since the \ref
  16864. mousePressEvent.
  16865. \seebaseclassmethod
  16866. */
  16867. void QCPTextElement::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  16868. {
  16869. if ((QPointF(event->pos())-startPos).manhattanLength() <= 3)
  16870. emit clicked(event);
  16871. }
  16872. /*!
  16873. Emits the \ref doubleClicked signal.
  16874. \seebaseclassmethod
  16875. */
  16876. void QCPTextElement::mouseDoubleClickEvent(QMouseEvent *event, const QVariant &details)
  16877. {
  16878. Q_UNUSED(details)
  16879. emit doubleClicked(event);
  16880. }
  16881. /*! \internal
  16882. Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to
  16883. <tt>true</tt>, else mFont is returned.
  16884. */
  16885. QFont QCPTextElement::mainFont() const
  16886. {
  16887. return mSelected ? mSelectedFont : mFont;
  16888. }
  16889. /*! \internal
  16890. Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to
  16891. <tt>true</tt>, else mTextColor is returned.
  16892. */
  16893. QColor QCPTextElement::mainTextColor() const
  16894. {
  16895. return mSelected ? mSelectedTextColor : mTextColor;
  16896. }
  16897. /* end of 'src/layoutelements/layoutelement-textelement.cpp' */
  16898. /* including file 'src/layoutelements/layoutelement-colorscale.cpp' */
  16899. /* modified 2021-03-29T02:30:44, size 26531 */
  16900. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16901. //////////////////// QCPColorScale
  16902. ////////////////////////////////////////////////////////////////////////////////////////////////////
  16903. /*! \class QCPColorScale
  16904. \brief A color scale for use with color coding data such as QCPColorMap
  16905. This layout element can be placed on the plot to correlate a color gradient with data values. It
  16906. is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps".
  16907. \image html QCPColorScale.png
  16908. The color scale can be either horizontal or vertical, as shown in the image above. The
  16909. orientation and the side where the numbers appear is controlled with \ref setType.
  16910. Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are
  16911. connected, they share their gradient, data range and data scale type (\ref setGradient, \ref
  16912. setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color
  16913. scale, to make them all synchronize these properties.
  16914. To have finer control over the number display and axis behaviour, you can directly access the
  16915. \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if
  16916. you want to change the number of automatically generated ticks, call
  16917. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-tickcount
  16918. Placing a color scale next to the main axis rect works like with any other layout element:
  16919. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-creation
  16920. In this case we have placed it to the right of the default axis rect, so it wasn't necessary to
  16921. call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color
  16922. scale can be set with \ref setLabel.
  16923. For optimum appearance (like in the image above), it may be desirable to line up the axis rect and
  16924. the borders of the color scale. Use a \ref QCPMarginGroup to achieve this:
  16925. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolorscale-margingroup
  16926. Color scales are initialized with a non-zero minimum top and bottom margin (\ref
  16927. setMinimumMargins), because vertical color scales are most common and the minimum top/bottom
  16928. margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a
  16929. horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you
  16930. might want to also change the minimum margins accordingly, e.g. <tt>setMinimumMargins(QMargins(6, 0, 6, 0))</tt>.
  16931. */
  16932. /* start documentation of inline functions */
  16933. /*! \fn QCPAxis *QCPColorScale::axis() const
  16934. Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the
  16935. appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its
  16936. interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref
  16937. setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref
  16938. QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on
  16939. the QCPColorScale or on its QCPAxis.
  16940. If the type of the color scale is changed with \ref setType, the axis returned by this method
  16941. will change, too, to either the left, right, bottom or top axis, depending on which type was set.
  16942. */
  16943. /* end documentation of signals */
  16944. /* start documentation of signals */
  16945. /*! \fn void QCPColorScale::dataRangeChanged(const QCPRange &newRange);
  16946. This signal is emitted when the data range changes.
  16947. \see setDataRange
  16948. */
  16949. /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  16950. This signal is emitted when the data scale type changes.
  16951. \see setDataScaleType
  16952. */
  16953. /*! \fn void QCPColorScale::gradientChanged(const QCPColorGradient &newGradient);
  16954. This signal is emitted when the gradient changes.
  16955. \see setGradient
  16956. */
  16957. /* end documentation of signals */
  16958. /*!
  16959. Constructs a new QCPColorScale.
  16960. */
  16961. QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) :
  16962. QCPLayoutElement(parentPlot),
  16963. mType(QCPAxis::AxisType::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight
  16964. mDataScaleType(QCPAxis::ScaleType::stLinear),
  16965. mGradient( QCPColorGradient::GradientPreset::gpCold),
  16966. mBarWidth(20),
  16967. mAxisRect(new QCPColorScaleAxisRectPrivate(this))
  16968. {
  16969. 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)
  16970. setType(QCPAxis::AxisType::atRight);
  16971. setDataRange(QCPRange(0, 6));
  16972. }
  16973. QCPColorScale::~QCPColorScale()
  16974. {
  16975. delete mAxisRect;
  16976. }
  16977. /* undocumented getter */
  16978. QString QCPColorScale::label() const
  16979. {
  16980. if (!mColorAxis)
  16981. {
  16982. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  16983. return QString();
  16984. }
  16985. return mColorAxis.data()->label();
  16986. }
  16987. /* undocumented getter */
  16988. bool QCPColorScale::rangeDrag() const
  16989. {
  16990. if (!mAxisRect)
  16991. {
  16992. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  16993. return false;
  16994. }
  16995. return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) &&
  16996. mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) &&
  16997. mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
  16998. }
  16999. /* undocumented getter */
  17000. bool QCPColorScale::rangeZoom() const
  17001. {
  17002. if (!mAxisRect)
  17003. {
  17004. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17005. return false;
  17006. }
  17007. return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) &&
  17008. mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) &&
  17009. mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType);
  17010. }
  17011. /*!
  17012. Sets at which side of the color scale the axis is placed, and thus also its orientation.
  17013. Note that after setting \a type to a different value, the axis returned by \ref axis() will
  17014. be a different one. The new axis will adopt the following properties from the previous axis: The
  17015. range, scale type, label and ticker (the latter will be shared and not copied).
  17016. */
  17017. void QCPColorScale::setType(QCPAxis::AxisType type)
  17018. {
  17019. if (!mAxisRect)
  17020. {
  17021. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17022. return;
  17023. }
  17024. if (mType != type)
  17025. {
  17026. mType = type;
  17027. QCPRange rangeTransfer(0, 6);
  17028. QString labelTransfer;
  17029. QSharedPointer<QCPAxisTicker> tickerTransfer;
  17030. // transfer/revert some settings on old axis if it exists:
  17031. bool doTransfer = !mColorAxis.isNull();
  17032. if (doTransfer)
  17033. {
  17034. rangeTransfer = mColorAxis.data()->range();
  17035. labelTransfer = mColorAxis.data()->label();
  17036. tickerTransfer = mColorAxis.data()->ticker();
  17037. mColorAxis.data()->setLabel(QString());
  17038. disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  17039. disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  17040. }
  17041. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::AxisType::atLeft << QCPAxis::AxisType::atRight << QCPAxis::AxisType::atBottom << QCPAxis::AxisType::atTop;
  17042. foreach (QCPAxis::AxisType atype, allAxisTypes)
  17043. {
  17044. mAxisRect.data()->axis(atype)->setTicks(atype == mType);
  17045. mAxisRect.data()->axis(atype)->setTickLabels(atype== mType);
  17046. }
  17047. // set new mColorAxis pointer:
  17048. mColorAxis = mAxisRect.data()->axis(mType);
  17049. // transfer settings to new axis:
  17050. if (doTransfer)
  17051. {
  17052. 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)
  17053. mColorAxis.data()->setLabel(labelTransfer);
  17054. mColorAxis.data()->setTicker(tickerTransfer);
  17055. }
  17056. connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  17057. connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  17058. mAxisRect.data()->setRangeDragAxes(QList<QCPAxis*>() << mColorAxis.data());
  17059. }
  17060. }
  17061. /*!
  17062. Sets the range spanned by the color gradient and that is shown by the axis in the color scale.
  17063. It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is
  17064. also equivalent to directly accessing the \ref axis and setting its range with \ref
  17065. QCPAxis::setRange.
  17066. \see setDataScaleType, setGradient, rescaleDataRange
  17067. */
  17068. void QCPColorScale::setDataRange(const QCPRange &dataRange)
  17069. {
  17070. if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
  17071. {
  17072. mDataRange = dataRange;
  17073. if (mColorAxis)
  17074. mColorAxis.data()->setRange(mDataRange);
  17075. emit dataRangeChanged(mDataRange);
  17076. }
  17077. }
  17078. /*!
  17079. Sets the scale type of the color scale, i.e. whether values are associated with colors linearly
  17080. or logarithmically.
  17081. It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is
  17082. also equivalent to directly accessing the \ref axis and setting its scale type with \ref
  17083. QCPAxis::setScaleType.
  17084. Note that this method controls the coordinate transformation. For logarithmic scales, you will
  17085. likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
  17086. the color scale's \ref axis ticker to an instance of \ref QCPAxisTickerLog :
  17087. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-colorscale
  17088. See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
  17089. creation.
  17090. \see setDataRange, setGradient
  17091. */
  17092. void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType)
  17093. {
  17094. if (mDataScaleType != scaleType)
  17095. {
  17096. mDataScaleType = scaleType;
  17097. if (mColorAxis)
  17098. mColorAxis.data()->setScaleType(mDataScaleType);
  17099. if (mDataScaleType == QCPAxis::ScaleType::stLogarithmic)
  17100. setDataRange(mDataRange.sanitizedForLogScale());
  17101. emit dataScaleTypeChanged(mDataScaleType);
  17102. }
  17103. }
  17104. /*!
  17105. Sets the color gradient that will be used to represent data values.
  17106. It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps.
  17107. \see setDataRange, setDataScaleType
  17108. */
  17109. void QCPColorScale::setGradient(const QCPColorGradient &gradient)
  17110. {
  17111. if (mGradient != gradient)
  17112. {
  17113. mGradient = gradient;
  17114. if (mAxisRect)
  17115. mAxisRect.data()->mGradientImageInvalidated = true;
  17116. emit gradientChanged(mGradient);
  17117. }
  17118. }
  17119. /*!
  17120. Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on
  17121. the internal \ref axis.
  17122. */
  17123. void QCPColorScale::setLabel(const QString &str)
  17124. {
  17125. if (!mColorAxis)
  17126. {
  17127. qDebug() << Q_FUNC_INFO << "internal color axis undefined";
  17128. return;
  17129. }
  17130. mColorAxis.data()->setLabel(str);
  17131. }
  17132. /*!
  17133. Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed
  17134. will have.
  17135. */
  17136. void QCPColorScale::setBarWidth(int width)
  17137. {
  17138. mBarWidth = width;
  17139. }
  17140. /*!
  17141. Sets whether the user can drag the data range (\ref setDataRange).
  17142. Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref
  17143. QCustomPlot::setInteractions) to allow range dragging.
  17144. */
  17145. void QCPColorScale::setRangeDrag(bool enabled)
  17146. {
  17147. if (!mAxisRect)
  17148. {
  17149. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17150. return;
  17151. }
  17152. if (enabled)
  17153. {
  17154. mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType));
  17155. } else
  17156. {
  17157. #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
  17158. mAxisRect.data()->setRangeDrag(nullptr);
  17159. #else
  17160. mAxisRect.data()->setRangeDrag({});
  17161. #endif
  17162. }
  17163. }
  17164. /*!
  17165. Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel.
  17166. Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref
  17167. QCustomPlot::setInteractions) to allow range dragging.
  17168. */
  17169. void QCPColorScale::setRangeZoom(bool enabled)
  17170. {
  17171. if (!mAxisRect)
  17172. {
  17173. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17174. return;
  17175. }
  17176. if (enabled)
  17177. {
  17178. mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType));
  17179. } else
  17180. {
  17181. #if QT_VERSION < QT_VERSION_CHECK(5, 2, 0)
  17182. mAxisRect.data()->setRangeDrag(nullptr);
  17183. #else
  17184. mAxisRect.data()->setRangeZoom({});
  17185. #endif
  17186. }
  17187. }
  17188. /*!
  17189. Returns a list of all the color maps associated with this color scale.
  17190. */
  17191. QList<QCPColorMap*> QCPColorScale::colorMaps() const
  17192. {
  17193. QList<QCPColorMap*> result;
  17194. for (int i=0; i<mParentPlot->plottableCount(); ++i)
  17195. {
  17196. if (QCPColorMap *cm = qobject_cast<QCPColorMap*>(mParentPlot->plottable(i)))
  17197. if (cm->colorScale() == this)
  17198. result.append(cm);
  17199. }
  17200. return result;
  17201. }
  17202. /*!
  17203. Changes the data range such that all color maps associated with this color scale are fully mapped
  17204. to the gradient in the data dimension.
  17205. \see setDataRange
  17206. */
  17207. void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps)
  17208. {
  17209. QList<QCPColorMap*> maps = colorMaps();
  17210. QCPRange newRange;
  17211. bool haveRange = false;
  17212. QCP::SignDomain sign = QCP::SignDomain::sdBoth;
  17213. if (mDataScaleType == QCPAxis::ScaleType::stLogarithmic)
  17214. sign = (mDataRange.upper < 0 ? QCP::SignDomain::sdNegative : QCP::SignDomain::sdPositive);
  17215. foreach (QCPColorMap *map, maps)
  17216. {
  17217. if (!map->realVisibility() && onlyVisibleMaps)
  17218. continue;
  17219. QCPRange mapRange;
  17220. if (map->colorScale() == this)
  17221. {
  17222. bool currentFoundRange = true;
  17223. mapRange = map->data()->dataBounds();
  17224. if (sign == QCP::SignDomain::sdPositive)
  17225. {
  17226. if (mapRange.lower <= 0 && mapRange.upper > 0)
  17227. mapRange.lower = mapRange.upper*1e-3;
  17228. else if (mapRange.lower <= 0 && mapRange.upper <= 0)
  17229. currentFoundRange = false;
  17230. } else if (sign == QCP::SignDomain::sdNegative)
  17231. {
  17232. if (mapRange.upper >= 0 && mapRange.lower < 0)
  17233. mapRange.upper = mapRange.lower*1e-3;
  17234. else if (mapRange.upper >= 0 && mapRange.lower >= 0)
  17235. currentFoundRange = false;
  17236. }
  17237. if (currentFoundRange)
  17238. {
  17239. if (!haveRange)
  17240. newRange = mapRange;
  17241. else
  17242. newRange.expand(mapRange);
  17243. haveRange = true;
  17244. }
  17245. }
  17246. }
  17247. if (haveRange)
  17248. {
  17249. 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
  17250. {
  17251. 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
  17252. if (mDataScaleType == QCPAxis::ScaleType::stLinear)
  17253. {
  17254. newRange.lower = center-mDataRange.size()/2.0;
  17255. newRange.upper = center+mDataRange.size()/2.0;
  17256. } else // mScaleType == stLogarithmic
  17257. {
  17258. newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower);
  17259. newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower);
  17260. }
  17261. }
  17262. setDataRange(newRange);
  17263. }
  17264. }
  17265. /* inherits documentation from base class */
  17266. void QCPColorScale::update(UpdatePhase phase)
  17267. {
  17268. QCPLayoutElement::update(phase);
  17269. if (!mAxisRect)
  17270. {
  17271. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17272. return;
  17273. }
  17274. mAxisRect.data()->update(phase);
  17275. switch (phase)
  17276. {
  17277. case upMargins:
  17278. {
  17279. if (mType == QCPAxis::AxisType::atBottom || mType == QCPAxis::AxisType::atTop)
  17280. {
  17281. setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom());
  17282. setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom());
  17283. } else
  17284. {
  17285. setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), QWIDGETSIZE_MAX);
  17286. setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right(), 0);
  17287. }
  17288. break;
  17289. }
  17290. case upLayout:
  17291. {
  17292. mAxisRect.data()->setOuterRect(rect());
  17293. break;
  17294. }
  17295. default: break;
  17296. }
  17297. }
  17298. /* inherits documentation from base class */
  17299. void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const
  17300. {
  17301. painter->setAntialiasing(false);
  17302. }
  17303. /* inherits documentation from base class */
  17304. void QCPColorScale::mousePressEvent(QMouseEvent *event, const QVariant &details)
  17305. {
  17306. if (!mAxisRect)
  17307. {
  17308. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17309. return;
  17310. }
  17311. mAxisRect.data()->mousePressEvent(event, details);
  17312. }
  17313. /* inherits documentation from base class */
  17314. void QCPColorScale::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  17315. {
  17316. if (!mAxisRect)
  17317. {
  17318. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17319. return;
  17320. }
  17321. mAxisRect.data()->mouseMoveEvent(event, startPos);
  17322. }
  17323. /* inherits documentation from base class */
  17324. void QCPColorScale::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  17325. {
  17326. if (!mAxisRect)
  17327. {
  17328. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17329. return;
  17330. }
  17331. mAxisRect.data()->mouseReleaseEvent(event, startPos);
  17332. }
  17333. /* inherits documentation from base class */
  17334. void QCPColorScale::wheelEvent(QWheelEvent *event)
  17335. {
  17336. if (!mAxisRect)
  17337. {
  17338. qDebug() << Q_FUNC_INFO << "internal axis rect was deleted";
  17339. return;
  17340. }
  17341. mAxisRect.data()->wheelEvent(event);
  17342. }
  17343. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17344. //////////////////// QCPColorScaleAxisRectPrivate
  17345. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17346. /*! \class QCPColorScaleAxisRectPrivate
  17347. \internal
  17348. \brief An axis rect subclass for use in a QCPColorScale
  17349. This is a private class and not part of the public QCustomPlot interface.
  17350. It provides the axis rect functionality for the QCPColorScale class.
  17351. */
  17352. /*!
  17353. Creates a new instance, as a child of \a parentColorScale.
  17354. */
  17355. QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) :
  17356. QCPAxisRect(parentColorScale->parentPlot(), true),
  17357. mParentColorScale(parentColorScale),
  17358. mGradientImageInvalidated(true)
  17359. {
  17360. setParentLayerable(parentColorScale);
  17361. setMinimumMargins(QMargins(0, 0, 0, 0));
  17362. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::AxisType::atBottom << QCPAxis::AxisType::atTop << QCPAxis::AxisType::atLeft << QCPAxis::AxisType::atRight;
  17363. foreach (QCPAxis::AxisType type, allAxisTypes)
  17364. {
  17365. axis(type)->setVisible(true);
  17366. axis(type)->grid()->setVisible(false);
  17367. axis(type)->setPadding(0);
  17368. connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts)));
  17369. connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts)));
  17370. }
  17371. connect(axis(QCPAxis::AxisType::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::AxisType::atRight), SLOT(setRange(QCPRange)));
  17372. connect(axis(QCPAxis::AxisType::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::AxisType::atLeft), SLOT(setRange(QCPRange)));
  17373. connect(axis(QCPAxis::AxisType::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::AxisType::atTop), SLOT(setRange(QCPRange)));
  17374. connect(axis(QCPAxis::AxisType::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::AxisType::atBottom), SLOT(setRange(QCPRange)));
  17375. connect(axis(QCPAxis::AxisType::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::AxisType::atRight), SLOT(setScaleType(QCPAxis::ScaleType)));
  17376. connect(axis(QCPAxis::AxisType::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::AxisType::atLeft), SLOT(setScaleType(QCPAxis::ScaleType)));
  17377. connect(axis(QCPAxis::AxisType::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::AxisType::atTop), SLOT(setScaleType(QCPAxis::ScaleType)));
  17378. connect(axis(QCPAxis::AxisType::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::AxisType::atBottom), SLOT(setScaleType(QCPAxis::ScaleType)));
  17379. // make layer transfers of color scale transfer to axis rect and axes
  17380. // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect:
  17381. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*)));
  17382. foreach (QCPAxis::AxisType type, allAxisTypes)
  17383. connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*)));
  17384. }
  17385. /*! \internal
  17386. Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws
  17387. it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation.
  17388. \seebaseclassmethod
  17389. */
  17390. void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter)
  17391. {
  17392. if (mGradientImageInvalidated)
  17393. updateGradientImage();
  17394. bool mirrorHorz = false;
  17395. bool mirrorVert = false;
  17396. if (mParentColorScale->mColorAxis)
  17397. {
  17398. mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::AxisType::atBottom || mParentColorScale->type() == QCPAxis::AxisType::atTop);
  17399. mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::AxisType::atLeft || mParentColorScale->type() == QCPAxis::AxisType::atRight);
  17400. }
  17401. painter->drawImage(rect().adjusted(0, -1, 0, -1), mGradientImage.mirrored(mirrorHorz, mirrorVert));
  17402. QCPAxisRect::draw(painter);
  17403. }
  17404. /*! \internal
  17405. Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to
  17406. generate a gradient image. This gradient image will be used in the \ref draw method.
  17407. */
  17408. void QCPColorScaleAxisRectPrivate::updateGradientImage()
  17409. {
  17410. if (rect().isEmpty())
  17411. return;
  17412. const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
  17413. int n = mParentColorScale->mGradient.levelCount();
  17414. int w, h;
  17415. QVector<double> data(n);
  17416. for (int i=0; i<n; ++i)
  17417. data[i] = i;
  17418. if (mParentColorScale->mType == QCPAxis::AxisType::atBottom || mParentColorScale->mType == QCPAxis::AxisType::atTop)
  17419. {
  17420. w = n;
  17421. h = rect().height();
  17422. mGradientImage = QImage(w, h, format);
  17423. QVector<QRgb*> pixels;
  17424. for (int y=0; y<h; ++y)
  17425. pixels.append(reinterpret_cast<QRgb*>(mGradientImage.scanLine(y)));
  17426. mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, (double)n-1.0), pixels.first(), n);
  17427. for (int y=1; y<h; ++y)
  17428. memcpy(pixels.at(y), pixels.first(), size_t(n)*sizeof(QRgb));
  17429. } else
  17430. {
  17431. w = rect().width();
  17432. h = n;
  17433. mGradientImage = QImage(w, h, format);
  17434. for (int y=0; y<h; ++y)
  17435. {
  17436. QRgb *pixels = reinterpret_cast<QRgb*>(mGradientImage.scanLine(y));
  17437. const QRgb lineColor = mParentColorScale->mGradient.color(data[h - 1.0 - y], QCPRange(0, n-1.0 ));
  17438. for (int x=0; x<w; ++x)
  17439. pixels[x] = lineColor;
  17440. }
  17441. }
  17442. mGradientImageInvalidated = false;
  17443. }
  17444. /*! \internal
  17445. This slot is connected to the selectionChanged signals of the four axes in the constructor. It
  17446. synchronizes the selection state of the axes.
  17447. */
  17448. void QCPColorScaleAxisRectPrivate::axisSelectionChanged(QCPAxis::SelectableParts selectedParts)
  17449. {
  17450. // axis bases of four axes shall always (de-)selected synchronously:
  17451. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::AxisType::atBottom << QCPAxis::AxisType::atTop << QCPAxis::AxisType::atLeft << QCPAxis::AxisType::atRight;
  17452. foreach (QCPAxis::AxisType type, allAxisTypes)
  17453. {
  17454. if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
  17455. if (senderAxis->axisType() == type)
  17456. continue;
  17457. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
  17458. {
  17459. if (selectedParts.testFlag(QCPAxis::spAxis))
  17460. axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis);
  17461. else
  17462. axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis);
  17463. }
  17464. }
  17465. }
  17466. /*! \internal
  17467. This slot is connected to the selectableChanged signals of the four axes in the constructor. It
  17468. synchronizes the selectability of the axes.
  17469. */
  17470. void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts)
  17471. {
  17472. // synchronize axis base selectability:
  17473. const QList<QCPAxis::AxisType> allAxisTypes = QList<QCPAxis::AxisType>() << QCPAxis::AxisType::atBottom << QCPAxis::AxisType::atTop << QCPAxis::AxisType::atLeft << QCPAxis::AxisType::atRight;
  17474. foreach (QCPAxis::AxisType type, allAxisTypes)
  17475. {
  17476. if (QCPAxis *senderAxis = qobject_cast<QCPAxis*>(sender()))
  17477. if (senderAxis->axisType() == type)
  17478. continue;
  17479. if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis))
  17480. {
  17481. if (selectableParts.testFlag(QCPAxis::spAxis))
  17482. axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis);
  17483. else
  17484. axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis);
  17485. }
  17486. }
  17487. }
  17488. /* end of 'src/layoutelements/layoutelement-colorscale.cpp' */
  17489. /* including file 'src/plottables/plottable-graph.cpp' */
  17490. /* modified 2021-03-29T02:30:44, size 74518 */
  17491. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17492. //////////////////// QCPGraphData
  17493. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17494. /*! \class QCPGraphData
  17495. \brief Holds the data of one single data point for QCPGraph.
  17496. The stored data is:
  17497. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  17498. \li \a value: coordinate on the value axis of this data point (this is the \a mainValue)
  17499. The container for storing multiple data points is \ref QCPGraphDataContainer. It is a typedef for
  17500. \ref QCPDataContainer with \ref QCPGraphData as the DataType template parameter. See the
  17501. documentation there for an explanation regarding the data type's generic methods.
  17502. \see QCPGraphDataContainer
  17503. */
  17504. /* start documentation of inline functions */
  17505. /*! \fn double QCPGraphData::sortKey() const
  17506. Returns the \a key member of this data point.
  17507. For a general explanation of what this method is good for in the context of the data container,
  17508. see the documentation of \ref QCPDataContainer.
  17509. */
  17510. /*! \fn static QCPGraphData QCPGraphData::fromSortKey(double sortKey)
  17511. Returns a data point with the specified \a sortKey. All other members are set to zero.
  17512. For a general explanation of what this method is good for in the context of the data container,
  17513. see the documentation of \ref QCPDataContainer.
  17514. */
  17515. /*! \fn static static bool QCPGraphData::sortKeyIsMainKey()
  17516. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  17517. this method returns true.
  17518. For a general explanation of what this method is good for in the context of the data container,
  17519. see the documentation of \ref QCPDataContainer.
  17520. */
  17521. /*! \fn double QCPGraphData::mainKey() const
  17522. Returns the \a key member of this data point.
  17523. For a general explanation of what this method is good for in the context of the data container,
  17524. see the documentation of \ref QCPDataContainer.
  17525. */
  17526. /*! \fn double QCPGraphData::mainValue() const
  17527. Returns the \a value member of this data point.
  17528. For a general explanation of what this method is good for in the context of the data container,
  17529. see the documentation of \ref QCPDataContainer.
  17530. */
  17531. /*! \fn QCPRange QCPGraphData::valueRange() const
  17532. Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
  17533. For a general explanation of what this method is good for in the context of the data container,
  17534. see the documentation of \ref QCPDataContainer.
  17535. */
  17536. /* end documentation of inline functions */
  17537. /*!
  17538. Constructs a data point with key and value set to zero.
  17539. */
  17540. QCPGraphData::QCPGraphData() :
  17541. key(0),
  17542. value(0)
  17543. {
  17544. }
  17545. /*!
  17546. Constructs a data point with the specified \a key and \a value.
  17547. */
  17548. QCPGraphData::QCPGraphData(double key, double value) :
  17549. key(key),
  17550. value(value)
  17551. {
  17552. }
  17553. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17554. //////////////////// QCPGraph
  17555. ////////////////////////////////////////////////////////////////////////////////////////////////////
  17556. /*! \class QCPGraph
  17557. \brief A plottable representing a graph in a plot.
  17558. \image html QCPGraph.png
  17559. Usually you create new graphs by calling QCustomPlot::addGraph. The resulting instance can be
  17560. accessed via QCustomPlot::graph.
  17561. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  17562. also access and modify the data via the \ref data method, which returns a pointer to the internal
  17563. \ref QCPGraphDataContainer.
  17564. Graphs are used to display single-valued data. Single-valued means that there should only be one
  17565. data point per unique key coordinate. In other words, the graph can't have \a loops. If you do
  17566. want to plot non-single-valued curves, rather use the QCPCurve plottable.
  17567. Gaps in the graph line can be created by adding data points with NaN as value
  17568. (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
  17569. separated.
  17570. \section qcpgraph-appearance Changing the appearance
  17571. The appearance of the graph is mainly determined by the line style, scatter style, brush and pen
  17572. of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen).
  17573. \subsection filling Filling under or between graphs
  17574. QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to
  17575. the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill,
  17576. just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent.
  17577. By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill
  17578. between this graph and another one, call \ref setChannelFillGraph with the other graph as
  17579. parameter.
  17580. \see QCustomPlot::addGraph, QCustomPlot::graph
  17581. */
  17582. /* start of documentation of inline functions */
  17583. /*! \fn QSharedPointer<QCPGraphDataContainer> QCPGraph::data() const
  17584. Returns a shared pointer to the internal data storage of type \ref QCPGraphDataContainer. You may
  17585. use it to directly manipulate the data, which may be more convenient and faster than using the
  17586. regular \ref setData or \ref addData methods.
  17587. */
  17588. /* end of documentation of inline functions */
  17589. /*!
  17590. Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  17591. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  17592. the same orientation. If either of these restrictions is violated, a corresponding message is
  17593. printed to the debug output (qDebug), the construction is not aborted, though.
  17594. The created QCPGraph is automatically registered with the QCustomPlot instance inferred from \a
  17595. keyAxis. This QCustomPlot instance takes ownership of the QCPGraph, so do not delete it manually
  17596. but use QCustomPlot::removePlottable() instead.
  17597. To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function.
  17598. */
  17599. QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  17600. QCPAbstractPlottable1D<QCPGraphData>(keyAxis, valueAxis),
  17601. mLineStyle{},
  17602. mScatterSkip{},
  17603. mAdaptiveSampling{}
  17604. {
  17605. // special handling for QCPGraphs to maintain the simple graph interface:
  17606. mParentPlot->registerGraph(this);
  17607. setPen(QPen(Qt::blue, 0));
  17608. setBrush(Qt::NoBrush);
  17609. setLineStyle(LineStyle::lsLine);
  17610. setScatterSkip(0);
  17611. setChannelFillGraph(nullptr);
  17612. setAdaptiveSampling(true);
  17613. }
  17614. QCPGraph::~QCPGraph()
  17615. {
  17616. }
  17617. /*! \overload
  17618. Replaces the current data container with the provided \a data container.
  17619. Since a QSharedPointer is used, multiple QCPGraphs may share the same data container safely.
  17620. Modifying the data in the container will then affect all graphs that share the container. Sharing
  17621. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  17622. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-1
  17623. If you do not wish to share containers, but create a copy from an existing container, rather use
  17624. the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
  17625. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpgraph-datasharing-2
  17626. \see addData
  17627. */
  17628. void QCPGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
  17629. {
  17630. mDataContainer = data;
  17631. }
  17632. /*! \overload
  17633. Replaces the current data with the provided points in \a keys and \a values. The provided
  17634. vectors should have equal length. Else, the number of added points will be the size of the
  17635. smallest vector.
  17636. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  17637. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  17638. \see addData
  17639. */
  17640. void QCPGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  17641. {
  17642. mDataContainer->clear();
  17643. addData(keys, values, alreadySorted);
  17644. }
  17645. /*!
  17646. Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
  17647. \ref lsNone and \ref setScatterStyle to the desired scatter style.
  17648. \see setScatterStyle
  17649. */
  17650. void QCPGraph::setLineStyle(LineStyle ls)
  17651. {
  17652. mLineStyle = ls;
  17653. }
  17654. /*!
  17655. Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
  17656. are drawn (e.g. for line-only-plots with appropriate line style).
  17657. \see QCPScatterStyle, setLineStyle
  17658. */
  17659. void QCPGraph::setScatterStyle(const QCPScatterStyle &style)
  17660. {
  17661. mScatterStyle = style;
  17662. }
  17663. /*!
  17664. If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
  17665. scatter points are skipped/not drawn after every drawn scatter point.
  17666. This can be used to make the data appear sparser while for example still having a smooth line,
  17667. and to improve performance for very high density plots.
  17668. If \a skip is set to 0 (default), all scatter points are drawn.
  17669. \see setScatterStyle
  17670. */
  17671. void QCPGraph::setScatterSkip(int skip)
  17672. {
  17673. mScatterSkip = qMax(0, skip);
  17674. }
  17675. /*!
  17676. Sets the target graph for filling the area between this graph and \a targetGraph with the current
  17677. brush (\ref setBrush).
  17678. When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To
  17679. disable any filling, set the brush to Qt::NoBrush.
  17680. \see setBrush
  17681. */
  17682. void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph)
  17683. {
  17684. // prevent setting channel target to this graph itself:
  17685. if (targetGraph == this)
  17686. {
  17687. qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself";
  17688. mChannelFillGraph = nullptr;
  17689. return;
  17690. }
  17691. // prevent setting channel target to a graph not in the plot:
  17692. if (targetGraph && targetGraph->mParentPlot != mParentPlot)
  17693. {
  17694. qDebug() << Q_FUNC_INFO << "targetGraph not in same plot";
  17695. mChannelFillGraph = nullptr;
  17696. return;
  17697. }
  17698. mChannelFillGraph = targetGraph;
  17699. }
  17700. /*!
  17701. Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive
  17702. sampling technique can drastically improve the replot performance for graphs with a larger number
  17703. of points (e.g. above 10,000), without notably changing the appearance of the graph.
  17704. By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive
  17705. sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no
  17706. disadvantage in almost all cases.
  17707. \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling"
  17708. As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are
  17709. reproduced reliably, as well as the overall shape of the data set. The replot time reduces
  17710. dramatically though. This allows QCustomPlot to display large amounts of data in realtime.
  17711. \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling"
  17712. Care must be taken when using high-density scatter plots in combination with adaptive sampling.
  17713. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still
  17714. gives a significant reduction of replot times, but not quite as much as for line plots. This is
  17715. because scatter plots inherently need more data points to be preserved in order to still resemble
  17716. the original, non-adaptive-sampling plot. As shown above, the results still aren't quite
  17717. identical, as banding occurs for the outer data points. This is in fact intentional, such that
  17718. the boundaries of the data cloud stay visible to the viewer. How strong the banding appears,
  17719. depends on the point density, i.e. the number of points in the plot.
  17720. For some situations with scatter plots it might thus be desirable to manually turn adaptive
  17721. sampling off. For example, when saving the plot to disk. This can be achieved by setting \a
  17722. enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled
  17723. back to true afterwards.
  17724. */
  17725. void QCPGraph::setAdaptiveSampling(bool enabled)
  17726. {
  17727. mAdaptiveSampling = enabled;
  17728. }
  17729. /*! \overload
  17730. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  17731. should have equal length. Else, the number of added points will be the size of the smallest
  17732. vector.
  17733. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  17734. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  17735. Alternatively, you can also access and modify the data directly via the \ref data method, which
  17736. returns a pointer to the internal data container.
  17737. */
  17738. void QCPGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  17739. {
  17740. if (keys.size() != values.size())
  17741. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  17742. const int n = qMin(keys.size(), values.size());
  17743. QVector<QCPGraphData> tempData(n);
  17744. QVector<QCPGraphData>::iterator it = tempData.begin();
  17745. const QVector<QCPGraphData>::iterator itEnd = tempData.end();
  17746. int i = 0;
  17747. while (it != itEnd)
  17748. {
  17749. it->key = keys[i];
  17750. it->value = values[i];
  17751. ++it;
  17752. ++i;
  17753. }
  17754. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  17755. }
  17756. /*! \overload
  17757. Adds the provided data point as \a key and \a value to the current data.
  17758. Alternatively, you can also access and modify the data directly via the \ref data method, which
  17759. returns a pointer to the internal data container.
  17760. */
  17761. void QCPGraph::addData(double key, double value)
  17762. {
  17763. mDataContainer->add(QCPGraphData(key, value));
  17764. }
  17765. /*!
  17766. Implements a selectTest specific to this plottable's point geometry.
  17767. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  17768. point to \a pos.
  17769. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  17770. */
  17771. double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  17772. {
  17773. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  17774. return -1;
  17775. if (!mKeyAxis || !mValueAxis)
  17776. return -1;
  17777. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  17778. {
  17779. QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  17780. double result = pointDistance(pos, closestDataPoint);
  17781. if (details)
  17782. {
  17783. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  17784. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  17785. }
  17786. return result;
  17787. } else
  17788. return -1;
  17789. }
  17790. /* inherits documentation from base class */
  17791. QCPRange QCPGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  17792. {
  17793. return mDataContainer->keyRange(foundRange, inSignDomain);
  17794. }
  17795. /* inherits documentation from base class */
  17796. QCPRange QCPGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  17797. {
  17798. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  17799. }
  17800. /* inherits documentation from base class */
  17801. void QCPGraph::draw(QCPPainter *painter)
  17802. {
  17803. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  17804. if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
  17805. if (mLineStyle == LineStyle::lsNone && mScatterStyle.isNone()) return;
  17806. QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
  17807. // loop over and draw segments of unselected/selected data:
  17808. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  17809. getDataSegments(selectedSegments, unselectedSegments);
  17810. allSegments << unselectedSegments << selectedSegments;
  17811. for (int i=0; i<allSegments.size(); ++i)
  17812. {
  17813. bool isSelectedSegment = i >= unselectedSegments.size();
  17814. // get line pixel points appropriate to line style:
  17815. 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)
  17816. getLines(&lines, lineDataRange);
  17817. // check data validity if flag set:
  17818. #ifdef QCUSTOMPLOT_CHECK_DATA
  17819. QCPGraphDataContainer::const_iterator it;
  17820. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  17821. {
  17822. if (QCP::isInvalidData(it->key, it->value))
  17823. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
  17824. }
  17825. #endif
  17826. // draw fill of graph:
  17827. if (isSelectedSegment && mSelectionDecorator)
  17828. mSelectionDecorator->applyBrush(painter);
  17829. else
  17830. painter->setBrush(mBrush);
  17831. painter->setPen(Qt::NoPen);
  17832. drawFill(painter, &lines);
  17833. // draw line:
  17834. if (mLineStyle != LineStyle::lsNone)
  17835. {
  17836. if (isSelectedSegment && mSelectionDecorator)
  17837. mSelectionDecorator->applyPen(painter);
  17838. else
  17839. painter->setPen(mPen);
  17840. painter->setBrush(Qt::NoBrush);
  17841. if (mLineStyle == LineStyle::lsImpulse)
  17842. drawImpulsePlot(painter, lines);
  17843. else
  17844. drawLinePlot(painter, lines); // also step plots can be drawn as a line plot
  17845. }
  17846. // draw scatters:
  17847. QCPScatterStyle finalScatterStyle = mScatterStyle;
  17848. if (isSelectedSegment && mSelectionDecorator)
  17849. finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
  17850. if (!finalScatterStyle.isNone())
  17851. {
  17852. getScatters(&scatters, allSegments.at(i));
  17853. drawScatterPlot(painter, scatters, finalScatterStyle);
  17854. }
  17855. }
  17856. // draw other selection decoration that isn't just line/scatter pens and brushes:
  17857. if (mSelectionDecorator)
  17858. mSelectionDecorator->drawDecoration(painter, selection());
  17859. }
  17860. /* inherits documentation from base class */
  17861. void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  17862. {
  17863. // draw fill:
  17864. if (mBrush.style() != Qt::NoBrush)
  17865. {
  17866. applyFillAntialiasingHint(painter);
  17867. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  17868. }
  17869. // draw line vertically centered:
  17870. if (mLineStyle != LineStyle::lsNone)
  17871. {
  17872. applyDefaultAntialiasingHint(painter);
  17873. painter->setPen(mPen);
  17874. 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
  17875. }
  17876. // draw scatter symbol:
  17877. if (!mScatterStyle.isNone())
  17878. {
  17879. applyScattersAntialiasingHint(painter);
  17880. // scale scatter pixmap if it's too large to fit in legend icon rect:
  17881. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  17882. {
  17883. QCPScatterStyle scaledStyle(mScatterStyle);
  17884. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  17885. scaledStyle.applyTo(painter, mPen);
  17886. scaledStyle.drawShape(painter, QRectF(rect).center());
  17887. } else
  17888. {
  17889. mScatterStyle.applyTo(painter, mPen);
  17890. mScatterStyle.drawShape(painter, QRectF(rect).center());
  17891. }
  17892. }
  17893. }
  17894. /*! \internal
  17895. This method retrieves an optimized set of data points via \ref getOptimizedLineData, and branches
  17896. out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
  17897. according to the line style of the graph.
  17898. \a lines will be filled with points in pixel coordinates, that can be drawn with the according
  17899. draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
  17900. aren't necessarily the original data points. For example, step line styles require additional
  17901. points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
  17902. lines vector will be empty.
  17903. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  17904. conversion. In this function, the specified range may exceed the total data bounds without harm:
  17905. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  17906. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  17907. getDataSegments.
  17908. \see getScatters
  17909. */
  17910. void QCPGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
  17911. {
  17912. if (!lines) return;
  17913. QCPGraphDataContainer::const_iterator begin, end;
  17914. getVisibleDataBounds(begin, end, dataRange);
  17915. if (begin == end)
  17916. {
  17917. lines->clear();
  17918. return;
  17919. }
  17920. QVector<QCPGraphData> lineData;
  17921. if (mLineStyle != LineStyle::lsNone)
  17922. getOptimizedLineData(&lineData, begin, end);
  17923. if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in lineData (significantly simplifies following processing)
  17924. std::reverse(lineData.begin(), lineData.end());
  17925. switch (mLineStyle)
  17926. {
  17927. case LineStyle::lsNone: lines->clear(); break;
  17928. case LineStyle::lsLine: *lines = dataToLines(lineData); break;
  17929. case LineStyle::lsStepLeft: *lines = dataToStepLeftLines(lineData); break;
  17930. case LineStyle::lsStepRight: *lines = dataToStepRightLines(lineData); break;
  17931. case LineStyle::lsStepCenter: *lines = dataToStepCenterLines(lineData); break;
  17932. case LineStyle::lsImpulse: *lines = dataToImpulseLines(lineData); break;
  17933. }
  17934. }
  17935. /*! \internal
  17936. This method retrieves an optimized set of data points via \ref getOptimizedScatterData and then
  17937. converts them to pixel coordinates. The resulting points are returned in \a scatters, and can be
  17938. passed to \ref drawScatterPlot.
  17939. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  17940. conversion. In this function, the specified range may exceed the total data bounds without harm:
  17941. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  17942. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  17943. getDataSegments.
  17944. */
  17945. void QCPGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
  17946. {
  17947. if (!scatters) return;
  17948. QCPAxis *keyAxis = mKeyAxis.data();
  17949. QCPAxis *valueAxis = mValueAxis.data();
  17950. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; scatters->clear(); return; }
  17951. QCPGraphDataContainer::const_iterator begin, end;
  17952. getVisibleDataBounds(begin, end, dataRange);
  17953. if (begin == end)
  17954. {
  17955. scatters->clear();
  17956. return;
  17957. }
  17958. QVector<QCPGraphData> data;
  17959. getOptimizedScatterData(&data, begin, end);
  17960. if (mKeyAxis->rangeReversed() != (mKeyAxis->orientation() == Qt::Vertical)) // make sure key pixels are sorted ascending in data (significantly simplifies following processing)
  17961. std::reverse(data.begin(), data.end());
  17962. scatters->resize(data.size());
  17963. if (keyAxis->orientation() == Qt::Vertical)
  17964. {
  17965. for (int i=0; i<data.size(); ++i)
  17966. {
  17967. if (!qIsNaN(data.at(i).value))
  17968. {
  17969. (*scatters)[i].setX(valueAxis->coordToPixel(data.at(i).value));
  17970. (*scatters)[i].setY(keyAxis->coordToPixel(data.at(i).key));
  17971. }
  17972. }
  17973. } else
  17974. {
  17975. for (int i=0; i<data.size(); ++i)
  17976. {
  17977. if (!qIsNaN(data.at(i).value))
  17978. {
  17979. (*scatters)[i].setX(keyAxis->coordToPixel(data.at(i).key));
  17980. (*scatters)[i].setY(valueAxis->coordToPixel(data.at(i).value));
  17981. }
  17982. }
  17983. }
  17984. }
  17985. /*! \internal
  17986. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  17987. coordinate points which are suitable for drawing the line style \ref lsLine.
  17988. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  17989. getLines if the line style is set accordingly.
  17990. \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  17991. */
  17992. QVector<QPointF> QCPGraph::dataToLines(const QVector<QCPGraphData> &data) const
  17993. {
  17994. QVector<QPointF> result;
  17995. QCPAxis *keyAxis = mKeyAxis.data();
  17996. QCPAxis *valueAxis = mValueAxis.data();
  17997. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  17998. result.resize(data.size());
  17999. // transform data points to pixels:
  18000. if (keyAxis->orientation() == Qt::Vertical)
  18001. {
  18002. for (int i=0; i<data.size(); ++i)
  18003. {
  18004. result[i].setX(valueAxis->coordToPixel(data.at(i).value));
  18005. result[i].setY(keyAxis->coordToPixel(data.at(i).key));
  18006. }
  18007. } else // key axis is horizontal
  18008. {
  18009. for (int i=0; i<data.size(); ++i)
  18010. {
  18011. result[i].setX(keyAxis->coordToPixel(data.at(i).key));
  18012. result[i].setY(valueAxis->coordToPixel(data.at(i).value));
  18013. }
  18014. }
  18015. return result;
  18016. }
  18017. /*! \internal
  18018. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18019. coordinate points which are suitable for drawing the line style \ref lsStepLeft.
  18020. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18021. getLines if the line style is set accordingly.
  18022. \see dataToLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  18023. */
  18024. QVector<QPointF> QCPGraph::dataToStepLeftLines(const QVector<QCPGraphData> &data) const
  18025. {
  18026. QVector<QPointF> result;
  18027. QCPAxis *keyAxis = mKeyAxis.data();
  18028. QCPAxis *valueAxis = mValueAxis.data();
  18029. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18030. result.resize(data.size()*2);
  18031. // calculate steps from data and transform to pixel coordinates:
  18032. if (keyAxis->orientation() == Qt::Vertical)
  18033. {
  18034. double lastValue = valueAxis->coordToPixel(data.first().value);
  18035. for (int i=0; i<data.size(); ++i)
  18036. {
  18037. const double key = keyAxis->coordToPixel(data.at(i).key);
  18038. result[i*2+0].setX(lastValue);
  18039. result[i*2+0].setY(key);
  18040. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18041. result[i*2+1].setX(lastValue);
  18042. result[i*2+1].setY(key);
  18043. }
  18044. } else // key axis is horizontal
  18045. {
  18046. double lastValue = valueAxis->coordToPixel(data.first().value);
  18047. for (int i=0; i<data.size(); ++i)
  18048. {
  18049. const double key = keyAxis->coordToPixel(data.at(i).key);
  18050. result[i*2+0].setX(key);
  18051. result[i*2+0].setY(lastValue);
  18052. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18053. result[i*2+1].setX(key);
  18054. result[i*2+1].setY(lastValue);
  18055. }
  18056. }
  18057. return result;
  18058. }
  18059. /*! \internal
  18060. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18061. coordinate points which are suitable for drawing the line style \ref lsStepRight.
  18062. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18063. getLines if the line style is set accordingly.
  18064. \see dataToLines, dataToStepLeftLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  18065. */
  18066. QVector<QPointF> QCPGraph::dataToStepRightLines(const QVector<QCPGraphData> &data) const
  18067. {
  18068. QVector<QPointF> result;
  18069. QCPAxis *keyAxis = mKeyAxis.data();
  18070. QCPAxis *valueAxis = mValueAxis.data();
  18071. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18072. result.resize(data.size()*2);
  18073. // calculate steps from data and transform to pixel coordinates:
  18074. if (keyAxis->orientation() == Qt::Vertical)
  18075. {
  18076. double lastKey = keyAxis->coordToPixel(data.first().key);
  18077. for (int i=0; i<data.size(); ++i)
  18078. {
  18079. const double value = valueAxis->coordToPixel(data.at(i).value);
  18080. result[i*2+0].setX(value);
  18081. result[i*2+0].setY(lastKey);
  18082. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18083. result[i*2+1].setX(value);
  18084. result[i*2+1].setY(lastKey);
  18085. }
  18086. } else // key axis is horizontal
  18087. {
  18088. double lastKey = keyAxis->coordToPixel(data.first().key);
  18089. for (int i=0; i<data.size(); ++i)
  18090. {
  18091. const double value = valueAxis->coordToPixel(data.at(i).value);
  18092. result[i*2+0].setX(lastKey);
  18093. result[i*2+0].setY(value);
  18094. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18095. result[i*2+1].setX(lastKey);
  18096. result[i*2+1].setY(value);
  18097. }
  18098. }
  18099. return result;
  18100. }
  18101. /*! \internal
  18102. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18103. coordinate points which are suitable for drawing the line style \ref lsStepCenter.
  18104. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18105. getLines if the line style is set accordingly.
  18106. \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToImpulseLines, getLines, drawLinePlot
  18107. */
  18108. QVector<QPointF> QCPGraph::dataToStepCenterLines(const QVector<QCPGraphData> &data) const
  18109. {
  18110. QVector<QPointF> result;
  18111. QCPAxis *keyAxis = mKeyAxis.data();
  18112. QCPAxis *valueAxis = mValueAxis.data();
  18113. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18114. result.resize(data.size()*2);
  18115. // calculate steps from data and transform to pixel coordinates:
  18116. if (keyAxis->orientation() == Qt::Vertical)
  18117. {
  18118. double lastKey = keyAxis->coordToPixel(data.first().key);
  18119. double lastValue = valueAxis->coordToPixel(data.first().value);
  18120. result[0].setX(lastValue);
  18121. result[0].setY(lastKey);
  18122. for (int i=1; i<data.size(); ++i)
  18123. {
  18124. const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
  18125. result[i*2-1].setX(lastValue);
  18126. result[i*2-1].setY(key);
  18127. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18128. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18129. result[i*2+0].setX(lastValue);
  18130. result[i*2+0].setY(key);
  18131. }
  18132. result[data.size()*2-1].setX(lastValue);
  18133. result[data.size()*2-1].setY(lastKey);
  18134. } else // key axis is horizontal
  18135. {
  18136. double lastKey = keyAxis->coordToPixel(data.first().key);
  18137. double lastValue = valueAxis->coordToPixel(data.first().value);
  18138. result[0].setX(lastKey);
  18139. result[0].setY(lastValue);
  18140. for (int i=1; i<data.size(); ++i)
  18141. {
  18142. const double key = (keyAxis->coordToPixel(data.at(i).key)+lastKey)*0.5;
  18143. result[i*2-1].setX(key);
  18144. result[i*2-1].setY(lastValue);
  18145. lastValue = valueAxis->coordToPixel(data.at(i).value);
  18146. lastKey = keyAxis->coordToPixel(data.at(i).key);
  18147. result[i*2+0].setX(key);
  18148. result[i*2+0].setY(lastValue);
  18149. }
  18150. result[data.size()*2-1].setX(lastKey);
  18151. result[data.size()*2-1].setY(lastValue);
  18152. }
  18153. return result;
  18154. }
  18155. /*! \internal
  18156. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  18157. coordinate points which are suitable for drawing the line style \ref lsImpulse.
  18158. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  18159. getLines if the line style is set accordingly.
  18160. \see dataToLines, dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, getLines, drawImpulsePlot
  18161. */
  18162. QVector<QPointF> QCPGraph::dataToImpulseLines(const QVector<QCPGraphData> &data) const
  18163. {
  18164. QVector<QPointF> result;
  18165. QCPAxis *keyAxis = mKeyAxis.data();
  18166. QCPAxis *valueAxis = mValueAxis.data();
  18167. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  18168. result.resize(data.size()*2);
  18169. // transform data points to pixels:
  18170. if (keyAxis->orientation() == Qt::Vertical)
  18171. {
  18172. for (int i=0; i<data.size(); ++i)
  18173. {
  18174. const double key = keyAxis->coordToPixel(data.at(i).key);
  18175. result[i*2+0].setX(valueAxis->coordToPixel(0));
  18176. result[i*2+0].setY(key);
  18177. result[i*2+1].setX(valueAxis->coordToPixel(data.at(i).value));
  18178. result[i*2+1].setY(key);
  18179. }
  18180. } else // key axis is horizontal
  18181. {
  18182. for (int i=0; i<data.size(); ++i)
  18183. {
  18184. const double key = keyAxis->coordToPixel(data.at(i).key);
  18185. result[i*2+0].setX(key);
  18186. result[i*2+0].setY(valueAxis->coordToPixel(0));
  18187. result[i*2+1].setX(key);
  18188. result[i*2+1].setY(valueAxis->coordToPixel(data.at(i).value));
  18189. }
  18190. }
  18191. return result;
  18192. }
  18193. /*! \internal
  18194. Draws the fill of the graph using the specified \a painter, with the currently set brush.
  18195. Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref
  18196. getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons.
  18197. In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas),
  18198. this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to
  18199. operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN
  18200. segments of the two involved graphs, before passing the overlapping pairs to \ref
  18201. getChannelFillPolygon.
  18202. Pass the points of this graph's line as \a lines, in pixel coordinates.
  18203. \see drawLinePlot, drawImpulsePlot, drawScatterPlot
  18204. */
  18205. void QCPGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
  18206. {
  18207. if (mLineStyle == LineStyle::lsImpulse) return; // fill doesn't make sense for impulse plot
  18208. if (painter->brush().style() == Qt::NoBrush || painter->brush().color().alpha() == 0) return;
  18209. applyFillAntialiasingHint(painter);
  18210. const QVector<QCPDataRange> segments = getNonNanSegments(lines, keyAxis()->orientation());
  18211. if (!mChannelFillGraph)
  18212. {
  18213. // draw base fill under graph, fill goes all the way to the zero-value-line:
  18214. foreach (QCPDataRange segment, segments)
  18215. painter->drawPolygon(getFillPolygon(lines, segment));
  18216. } else
  18217. {
  18218. // draw fill between this graph and mChannelFillGraph:
  18219. QVector<QPointF> otherLines;
  18220. mChannelFillGraph->getLines(&otherLines, QCPDataRange(0, mChannelFillGraph->dataCount()));
  18221. if (!otherLines.isEmpty())
  18222. {
  18223. QVector<QCPDataRange> otherSegments = getNonNanSegments(&otherLines, mChannelFillGraph->keyAxis()->orientation());
  18224. QVector<QPair<QCPDataRange, QCPDataRange> > segmentPairs = getOverlappingSegments(segments, lines, otherSegments, &otherLines);
  18225. for (int i=0; i<segmentPairs.size(); ++i)
  18226. painter->drawPolygon(getChannelFillPolygon(lines, segmentPairs.at(i).first, &otherLines, segmentPairs.at(i).second));
  18227. }
  18228. }
  18229. }
  18230. /*! \internal
  18231. Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
  18232. scatters will be drawn with \a painter and have the appearance as specified in \a style.
  18233. \see drawLinePlot, drawImpulsePlot
  18234. */
  18235. void QCPGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
  18236. {
  18237. applyScattersAntialiasingHint(painter);
  18238. style.applyTo(painter, mPen);
  18239. foreach (const QPointF &scatter, scatters)
  18240. style.drawShape(painter, scatter.x(), scatter.y());
  18241. }
  18242. /*! \internal
  18243. Draws lines between the points in \a lines, given in pixel coordinates.
  18244. \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
  18245. */
  18246. void QCPGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
  18247. {
  18248. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  18249. {
  18250. applyDefaultAntialiasingHint(painter);
  18251. drawPolyline(painter, lines);
  18252. }
  18253. }
  18254. /*! \internal
  18255. Draws impulses from the provided data, i.e. it connects all line pairs in \a lines, given in
  18256. pixel coordinates. The \a lines necessary for impulses are generated by \ref dataToImpulseLines
  18257. from the regular graph data points.
  18258. \see drawLinePlot, drawScatterPlot
  18259. */
  18260. void QCPGraph::drawImpulsePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
  18261. {
  18262. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  18263. {
  18264. applyDefaultAntialiasingHint(painter);
  18265. QPen oldPen = painter->pen();
  18266. QPen newPen = painter->pen();
  18267. newPen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line
  18268. painter->setPen(newPen);
  18269. painter->drawLines(lines);
  18270. painter->setPen(oldPen);
  18271. }
  18272. }
  18273. /*! \internal
  18274. Returns via \a lineData the data points that need to be visualized for this graph when plotting
  18275. graph lines, taking into consideration the currently visible axis ranges and, if \ref
  18276. setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
  18277. further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
  18278. getDataSegments).
  18279. This method is used by \ref getLines to retrieve the basic working set of data.
  18280. \see getOptimizedScatterData
  18281. */
  18282. void QCPGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
  18283. {
  18284. if (!lineData) return;
  18285. QCPAxis *keyAxis = mKeyAxis.data();
  18286. QCPAxis *valueAxis = mValueAxis.data();
  18287. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  18288. if (begin == end) return;
  18289. int dataCount = int(end-begin);
  18290. int maxCount = (std::numeric_limits<int>::max)();
  18291. if (mAdaptiveSampling)
  18292. {
  18293. double keyPixelSpan = qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key));
  18294. if (2*keyPixelSpan+2 < static_cast<double>((std::numeric_limits<int>::max)()))
  18295. maxCount = int(2*keyPixelSpan+2);
  18296. }
  18297. if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
  18298. {
  18299. QCPGraphDataContainer::const_iterator it = begin;
  18300. double minValue = it->value;
  18301. double maxValue = it->value;
  18302. QCPGraphDataContainer::const_iterator currentIntervalFirstPoint = it;
  18303. int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
  18304. int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
  18305. double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound));
  18306. double lastIntervalEndKey = currentIntervalStartKey;
  18307. double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
  18308. bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::ScaleType::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
  18309. int intervalDataCount = 1;
  18310. ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect
  18311. while (it != end)
  18312. {
  18313. if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary
  18314. {
  18315. if (it->value < minValue)
  18316. minValue = it->value;
  18317. else if (it->value > maxValue)
  18318. maxValue = it->value;
  18319. ++intervalDataCount;
  18320. } else // new pixel interval started
  18321. {
  18322. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
  18323. {
  18324. if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point
  18325. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
  18326. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
  18327. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
  18328. 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
  18329. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.8, (it-1)->value));
  18330. } else
  18331. lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
  18332. lastIntervalEndKey = (it-1)->key;
  18333. minValue = it->value;
  18334. maxValue = it->value;
  18335. currentIntervalFirstPoint = it;
  18336. currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(it->key)+reversedRound));
  18337. if (keyEpsilonVariable)
  18338. keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
  18339. intervalDataCount = 1;
  18340. }
  18341. ++it;
  18342. }
  18343. // handle last interval:
  18344. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster
  18345. {
  18346. if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point
  18347. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint->value));
  18348. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.25, minValue));
  18349. lineData->append(QCPGraphData(currentIntervalStartKey+keyEpsilon*0.75, maxValue));
  18350. } else
  18351. lineData->append(QCPGraphData(currentIntervalFirstPoint->key, currentIntervalFirstPoint->value));
  18352. } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
  18353. {
  18354. lineData->resize(dataCount);
  18355. std::copy(begin, end, lineData->begin());
  18356. }
  18357. }
  18358. /*! \internal
  18359. Returns via \a scatterData the data points that need to be visualized for this graph when
  18360. plotting scatter points, taking into consideration the currently visible axis ranges and, if \ref
  18361. setAdaptiveSampling is enabled, local point densities. The considered data can be restricted
  18362. further by \a begin and \a end, e.g. to only plot a certain segment of the data (see \ref
  18363. getDataSegments).
  18364. This method is used by \ref getScatters to retrieve the basic working set of data.
  18365. \see getOptimizedLineData
  18366. */
  18367. void QCPGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
  18368. {
  18369. if (!scatterData) return;
  18370. QCPAxis *keyAxis = mKeyAxis.data();
  18371. QCPAxis *valueAxis = mValueAxis.data();
  18372. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  18373. const int scatterModulo = mScatterSkip+1;
  18374. const bool doScatterSkip = mScatterSkip > 0;
  18375. int beginIndex = int(begin-mDataContainer->constBegin());
  18376. int endIndex = int(end-mDataContainer->constBegin());
  18377. while (doScatterSkip && begin != end && beginIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
  18378. {
  18379. ++beginIndex;
  18380. ++begin;
  18381. }
  18382. if (begin == end) return;
  18383. int dataCount = int(end-begin);
  18384. int maxCount = (std::numeric_limits<int>::max)();
  18385. if (mAdaptiveSampling)
  18386. {
  18387. int keyPixelSpan = int(qAbs(keyAxis->coordToPixel(begin->key)-keyAxis->coordToPixel((end-1)->key)));
  18388. maxCount = 2*keyPixelSpan+2;
  18389. }
  18390. if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average
  18391. {
  18392. double valueMaxRange = valueAxis->range().upper;
  18393. double valueMinRange = valueAxis->range().lower;
  18394. QCPGraphDataContainer::const_iterator it = begin;
  18395. int itIndex = int(beginIndex);
  18396. double minValue = it->value;
  18397. double maxValue = it->value;
  18398. QCPGraphDataContainer::const_iterator minValueIt = it;
  18399. QCPGraphDataContainer::const_iterator maxValueIt = it;
  18400. QCPGraphDataContainer::const_iterator currentIntervalStart = it;
  18401. int reversedFactor = keyAxis->pixelOrientation(); // is used to calculate keyEpsilon pixel into the correct direction
  18402. int reversedRound = reversedFactor==-1 ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey
  18403. double currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(begin->key)+reversedRound));
  18404. double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates
  18405. bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::ScaleType::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes)
  18406. int intervalDataCount = 1;
  18407. // advance iterator to second (non-skipped) data point because adaptive sampling works in 1 point retrospect:
  18408. if (!doScatterSkip)
  18409. ++it;
  18410. else
  18411. {
  18412. itIndex += scatterModulo;
  18413. if (itIndex < endIndex) // make sure we didn't jump over end
  18414. it += scatterModulo;
  18415. else
  18416. {
  18417. it = end;
  18418. itIndex = endIndex;
  18419. }
  18420. }
  18421. // main loop over data points:
  18422. while (it != end)
  18423. {
  18424. if (it->key < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary
  18425. {
  18426. if (it->value < minValue && it->value > valueMinRange && it->value < valueMaxRange)
  18427. {
  18428. minValue = it->value;
  18429. minValueIt = it;
  18430. } else if (it->value > maxValue && it->value > valueMinRange && it->value < valueMaxRange)
  18431. {
  18432. maxValue = it->value;
  18433. maxValueIt = it;
  18434. }
  18435. ++intervalDataCount;
  18436. } else // new pixel started
  18437. {
  18438. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  18439. {
  18440. // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
  18441. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
  18442. int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
  18443. QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
  18444. int c = 0;
  18445. while (intervalIt != it)
  18446. {
  18447. if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
  18448. scatterData->append(*intervalIt);
  18449. ++c;
  18450. if (!doScatterSkip)
  18451. ++intervalIt;
  18452. else
  18453. intervalIt += scatterModulo; // since we know indices of "currentIntervalStart", "intervalIt" and "it" are multiples of scatterModulo, we can't accidentally jump over "it" here
  18454. }
  18455. } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
  18456. scatterData->append(*currentIntervalStart);
  18457. minValue = it->value;
  18458. maxValue = it->value;
  18459. currentIntervalStart = it;
  18460. currentIntervalStartKey = keyAxis->pixelToCoord(int(keyAxis->coordToPixel(it->key)+reversedRound));
  18461. if (keyEpsilonVariable)
  18462. keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor));
  18463. intervalDataCount = 1;
  18464. }
  18465. // advance to next data point:
  18466. if (!doScatterSkip)
  18467. ++it;
  18468. else
  18469. {
  18470. itIndex += scatterModulo;
  18471. if (itIndex < endIndex) // make sure we didn't jump over end
  18472. it += scatterModulo;
  18473. else
  18474. {
  18475. it = end;
  18476. itIndex = endIndex;
  18477. }
  18478. }
  18479. }
  18480. // handle last interval:
  18481. if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them
  18482. {
  18483. // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot):
  18484. double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue));
  18485. int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average
  18486. QCPGraphDataContainer::const_iterator intervalIt = currentIntervalStart;
  18487. int intervalItIndex = int(intervalIt-mDataContainer->constBegin());
  18488. int c = 0;
  18489. while (intervalIt != it)
  18490. {
  18491. if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt->value > valueMinRange && intervalIt->value < valueMaxRange)
  18492. scatterData->append(*intervalIt);
  18493. ++c;
  18494. if (!doScatterSkip)
  18495. ++intervalIt;
  18496. 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:
  18497. {
  18498. intervalItIndex += scatterModulo;
  18499. if (intervalItIndex < itIndex)
  18500. intervalIt += scatterModulo;
  18501. else
  18502. {
  18503. intervalIt = it;
  18504. intervalItIndex = itIndex;
  18505. }
  18506. }
  18507. }
  18508. } else if (currentIntervalStart->value > valueMinRange && currentIntervalStart->value < valueMaxRange)
  18509. scatterData->append(*currentIntervalStart);
  18510. } else // don't use adaptive sampling algorithm, transfer points one-to-one from the data container into the output
  18511. {
  18512. QCPGraphDataContainer::const_iterator it = begin;
  18513. int itIndex = beginIndex;
  18514. scatterData->reserve(dataCount);
  18515. while (it != end)
  18516. {
  18517. scatterData->append(*it);
  18518. // advance to next data point:
  18519. if (!doScatterSkip)
  18520. ++it;
  18521. else
  18522. {
  18523. itIndex += scatterModulo;
  18524. if (itIndex < endIndex)
  18525. it += scatterModulo;
  18526. else
  18527. {
  18528. it = end;
  18529. itIndex = endIndex;
  18530. }
  18531. }
  18532. }
  18533. }
  18534. }
  18535. /*!
  18536. This method outputs the currently visible data range via \a begin and \a end. The returned range
  18537. will also never exceed \a rangeRestriction.
  18538. This method takes into account that the drawing of data lines at the axis rect border always
  18539. requires the points just outside the visible axis range. So \a begin and \a end may actually
  18540. indicate a range that contains one additional data point to the left and right of the visible
  18541. axis range.
  18542. */
  18543. void QCPGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
  18544. {
  18545. if (rangeRestriction.isEmpty())
  18546. {
  18547. end = mDataContainer->constEnd();
  18548. begin = end;
  18549. } else
  18550. {
  18551. QCPAxis *keyAxis = mKeyAxis.data();
  18552. QCPAxis *valueAxis = mValueAxis.data();
  18553. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  18554. // get visible data range:
  18555. begin = mDataContainer->findBegin(keyAxis->range().lower);
  18556. end = mDataContainer->findEnd(keyAxis->range().upper);
  18557. // limit lower/upperEnd to rangeRestriction:
  18558. mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
  18559. }
  18560. }
  18561. /*! \internal
  18562. This method goes through the passed points in \a lineData and returns a list of the segments
  18563. which don't contain NaN data points.
  18564. \a keyOrientation defines whether the \a x or \a y member of the passed QPointF is used to check
  18565. for NaN. If \a keyOrientation is \c Qt::Horizontal, the \a y member is checked, if it is \c
  18566. Qt::Vertical, the \a x member is checked.
  18567. \see getOverlappingSegments, drawFill
  18568. */
  18569. QVector<QCPDataRange> QCPGraph::getNonNanSegments(const QVector<QPointF> *lineData, Qt::Orientation keyOrientation) const
  18570. {
  18571. QVector<QCPDataRange> result;
  18572. const int n = lineData->size();
  18573. QCPDataRange currentSegment(-1, -1);
  18574. int i = 0;
  18575. if (keyOrientation == Qt::Horizontal)
  18576. {
  18577. while (i < n)
  18578. {
  18579. while (i < n && qIsNaN(lineData->at(i).y())) // seek next non-NaN data point
  18580. ++i;
  18581. if (i == n)
  18582. break;
  18583. currentSegment.setBegin(i++);
  18584. while (i < n && !qIsNaN(lineData->at(i).y())) // seek next NaN data point or end of data
  18585. ++i;
  18586. currentSegment.setEnd(i++);
  18587. result.append(currentSegment);
  18588. }
  18589. } else // keyOrientation == Qt::Vertical
  18590. {
  18591. while (i < n)
  18592. {
  18593. while (i < n && qIsNaN(lineData->at(i).x())) // seek next non-NaN data point
  18594. ++i;
  18595. if (i == n)
  18596. break;
  18597. currentSegment.setBegin(i++);
  18598. while (i < n && !qIsNaN(lineData->at(i).x())) // seek next NaN data point or end of data
  18599. ++i;
  18600. currentSegment.setEnd(i++);
  18601. result.append(currentSegment);
  18602. }
  18603. }
  18604. return result;
  18605. }
  18606. /*! \internal
  18607. This method takes two segment lists (e.g. created by \ref getNonNanSegments) \a thisSegments and
  18608. \a otherSegments, and their associated point data \a thisData and \a otherData.
  18609. It returns all pairs of segments (the first from \a thisSegments, the second from \a
  18610. otherSegments), which overlap in plot coordinates.
  18611. This method is useful in the case of a channel fill between two graphs, when only those non-NaN
  18612. segments which actually overlap in their key coordinate shall be considered for drawing a channel
  18613. fill polygon.
  18614. It is assumed that the passed segments in \a thisSegments are ordered ascending by index, and
  18615. that the segments don't overlap themselves. The same is assumed for the segments in \a
  18616. otherSegments. This is fulfilled when the segments are obtained via \ref getNonNanSegments.
  18617. \see getNonNanSegments, segmentsIntersect, drawFill, getChannelFillPolygon
  18618. */
  18619. QVector<QPair<QCPDataRange, QCPDataRange> > QCPGraph::getOverlappingSegments(QVector<QCPDataRange> thisSegments, const QVector<QPointF> *thisData, QVector<QCPDataRange> otherSegments, const QVector<QPointF> *otherData) const
  18620. {
  18621. QVector<QPair<QCPDataRange, QCPDataRange> > result;
  18622. if (thisData->isEmpty() || otherData->isEmpty() || thisSegments.isEmpty() || otherSegments.isEmpty())
  18623. return result;
  18624. int thisIndex = 0;
  18625. int otherIndex = 0;
  18626. const bool verticalKey = mKeyAxis->orientation() == Qt::Vertical;
  18627. while (thisIndex < thisSegments.size() && otherIndex < otherSegments.size())
  18628. {
  18629. if (thisSegments.at(thisIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow
  18630. {
  18631. ++thisIndex;
  18632. continue;
  18633. }
  18634. if (otherSegments.at(otherIndex).size() < 2) // segments with fewer than two points won't have a fill anyhow
  18635. {
  18636. ++otherIndex;
  18637. continue;
  18638. }
  18639. double thisLower, thisUpper, otherLower, otherUpper;
  18640. if (!verticalKey)
  18641. {
  18642. thisLower = thisData->at(thisSegments.at(thisIndex).begin()).x();
  18643. thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).x();
  18644. otherLower = otherData->at(otherSegments.at(otherIndex).begin()).x();
  18645. otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).x();
  18646. } else
  18647. {
  18648. thisLower = thisData->at(thisSegments.at(thisIndex).begin()).y();
  18649. thisUpper = thisData->at(thisSegments.at(thisIndex).end()-1).y();
  18650. otherLower = otherData->at(otherSegments.at(otherIndex).begin()).y();
  18651. otherUpper = otherData->at(otherSegments.at(otherIndex).end()-1).y();
  18652. }
  18653. int bPrecedence;
  18654. if (segmentsIntersect(thisLower, thisUpper, otherLower, otherUpper, bPrecedence))
  18655. result.append(QPair<QCPDataRange, QCPDataRange>(thisSegments.at(thisIndex), otherSegments.at(otherIndex)));
  18656. if (bPrecedence <= 0) // otherSegment doesn't reach as far as thisSegment, so continue with next otherSegment, keeping current thisSegment
  18657. ++otherIndex;
  18658. else // otherSegment reaches further than thisSegment, so continue with next thisSegment, keeping current otherSegment
  18659. ++thisIndex;
  18660. }
  18661. return result;
  18662. }
  18663. /*! \internal
  18664. Returns whether the segments defined by the coordinates (aLower, aUpper) and (bLower, bUpper)
  18665. have overlap.
  18666. The output parameter \a bPrecedence indicates whether the \a b segment reaches farther than the
  18667. \a a segment or not. If \a bPrecedence returns 1, segment \a b reaches the farthest to higher
  18668. coordinates (i.e. bUpper > aUpper). If it returns -1, segment \a a reaches the farthest. Only if
  18669. both segment's upper bounds are identical, 0 is returned as \a bPrecedence.
  18670. It is assumed that the lower bounds always have smaller or equal values than the upper bounds.
  18671. \see getOverlappingSegments
  18672. */
  18673. bool QCPGraph::segmentsIntersect(double aLower, double aUpper, double bLower, double bUpper, int &bPrecedence) const
  18674. {
  18675. bPrecedence = 0;
  18676. if (aLower > bUpper)
  18677. {
  18678. bPrecedence = -1;
  18679. return false;
  18680. } else if (bLower > aUpper)
  18681. {
  18682. bPrecedence = 1;
  18683. return false;
  18684. } else
  18685. {
  18686. if (aUpper > bUpper)
  18687. bPrecedence = -1;
  18688. else if (aUpper < bUpper)
  18689. bPrecedence = 1;
  18690. return true;
  18691. }
  18692. }
  18693. /*! \internal
  18694. Returns the point which closes the fill polygon on the zero-value-line parallel to the key axis.
  18695. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates
  18696. is in positive or negative infinity. So this case is handled separately by just closing the fill
  18697. polygon on the axis which lies in the direction towards the zero value.
  18698. \a matchingDataPoint will provide the key (in pixels) of the returned point. Depending on whether
  18699. the key axis of this graph is horizontal or vertical, \a matchingDataPoint will provide the x or
  18700. y value of the returned point, respectively.
  18701. */
  18702. QPointF QCPGraph::getFillBasePoint(QPointF matchingDataPoint) const
  18703. {
  18704. QCPAxis *keyAxis = mKeyAxis.data();
  18705. QCPAxis *valueAxis = mValueAxis.data();
  18706. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  18707. QPointF result;
  18708. if (valueAxis->scaleType() == QCPAxis::ScaleType::stLinear)
  18709. {
  18710. if (keyAxis->orientation() == Qt::Horizontal)
  18711. {
  18712. result.setX(matchingDataPoint.x());
  18713. result.setY(valueAxis->coordToPixel(0));
  18714. } else // keyAxis->orientation() == Qt::Vertical
  18715. {
  18716. result.setX(valueAxis->coordToPixel(0));
  18717. result.setY(matchingDataPoint.y());
  18718. }
  18719. } else // valueAxis->mScaleType == QCPAxis::ScaleType::stLogarithmic
  18720. {
  18721. // In logarithmic scaling we can't just draw to value 0 so we just fill all the way
  18722. // to the axis which is in the direction towards 0
  18723. if (keyAxis->orientation() == Qt::Vertical)
  18724. {
  18725. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  18726. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  18727. result.setX(keyAxis->axisRect()->right());
  18728. else
  18729. result.setX(keyAxis->axisRect()->left());
  18730. result.setY(matchingDataPoint.y());
  18731. } else if (keyAxis->axisType() == QCPAxis::AxisType::atTop || keyAxis->axisType() == QCPAxis::AxisType::atBottom)
  18732. {
  18733. result.setX(matchingDataPoint.x());
  18734. if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) ||
  18735. (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis
  18736. result.setY(keyAxis->axisRect()->top());
  18737. else
  18738. result.setY(keyAxis->axisRect()->bottom());
  18739. }
  18740. }
  18741. return result;
  18742. }
  18743. /*! \internal
  18744. Returns the polygon needed for drawing normal fills between this graph and the key axis.
  18745. Pass the graph's data points (in pixel coordinates) as \a lineData, and specify the \a segment
  18746. which shall be used for the fill. The collection of \a lineData points described by \a segment
  18747. must not contain NaN data points (see \ref getNonNanSegments).
  18748. The returned fill polygon will be closed at the key axis (the zero-value line) for linear value
  18749. axes. For logarithmic value axes the polygon will reach just beyond the corresponding axis rect
  18750. side (see \ref getFillBasePoint).
  18751. For increased performance (due to implicit sharing), keep the returned QPolygonF const.
  18752. \see drawFill, getNonNanSegments
  18753. */
  18754. const QPolygonF QCPGraph::getFillPolygon(const QVector<QPointF> *lineData, QCPDataRange segment) const
  18755. {
  18756. if (segment.size() < 2)
  18757. return QPolygonF();
  18758. QPolygonF result(segment.size()+2);
  18759. result[0] = getFillBasePoint(lineData->at(segment.begin()));
  18760. std::copy(lineData->constBegin()+segment.begin(), lineData->constBegin()+segment.end(), result.begin()+1);
  18761. result[result.size()-1] = getFillBasePoint(lineData->at(segment.end()-1));
  18762. return result;
  18763. }
  18764. /*! \internal
  18765. Returns the polygon needed for drawing (partial) channel fills between this graph and the graph
  18766. specified by \ref setChannelFillGraph.
  18767. The data points of this graph are passed as pixel coordinates via \a thisData, the data of the
  18768. other graph as \a otherData. The returned polygon will be calculated for the specified data
  18769. segments \a thisSegment and \a otherSegment, pertaining to the respective \a thisData and \a
  18770. otherData, respectively.
  18771. The passed \a thisSegment and \a otherSegment should correspond to the segment pairs returned by
  18772. \ref getOverlappingSegments, to make sure only segments that actually have key coordinate overlap
  18773. need to be processed here.
  18774. For increased performance due to implicit sharing, keep the returned QPolygonF const.
  18775. \see drawFill, getOverlappingSegments, getNonNanSegments
  18776. */
  18777. const QPolygonF QCPGraph::getChannelFillPolygon(const QVector<QPointF> *thisData, QCPDataRange thisSegment, const QVector<QPointF> *otherData, QCPDataRange otherSegment) const
  18778. {
  18779. if (!mChannelFillGraph)
  18780. return QPolygonF();
  18781. QCPAxis *keyAxis = mKeyAxis.data();
  18782. QCPAxis *valueAxis = mValueAxis.data();
  18783. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); }
  18784. if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); }
  18785. if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation())
  18786. 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)
  18787. if (thisData->isEmpty()) return QPolygonF();
  18788. QVector<QPointF> thisSegmentData(thisSegment.size());
  18789. QVector<QPointF> otherSegmentData(otherSegment.size());
  18790. std::copy(thisData->constBegin()+thisSegment.begin(), thisData->constBegin()+thisSegment.end(), thisSegmentData.begin());
  18791. std::copy(otherData->constBegin()+otherSegment.begin(), otherData->constBegin()+otherSegment.end(), otherSegmentData.begin());
  18792. // pointers to be able to swap them, depending which data range needs cropping:
  18793. QVector<QPointF> *staticData = &thisSegmentData;
  18794. QVector<QPointF> *croppedData = &otherSegmentData;
  18795. // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType):
  18796. if (keyAxis->orientation() == Qt::Horizontal)
  18797. {
  18798. // x is key
  18799. // crop lower bound:
  18800. if (staticData->first().x() < croppedData->first().x()) // other one must be cropped
  18801. qSwap(staticData, croppedData);
  18802. const int lowBound = findIndexBelowX(croppedData, staticData->first().x());
  18803. if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
  18804. croppedData->remove(0, lowBound);
  18805. // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
  18806. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18807. double slope;
  18808. if (!qFuzzyCompare(croppedData->at(1).x(), croppedData->at(0).x()))
  18809. slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x());
  18810. else
  18811. slope = 0;
  18812. (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x()));
  18813. (*croppedData)[0].setX(staticData->first().x());
  18814. // crop upper bound:
  18815. if (staticData->last().x() > croppedData->last().x()) // other one must be cropped
  18816. qSwap(staticData, croppedData);
  18817. int highBound = findIndexAboveX(croppedData, staticData->last().x());
  18818. if (highBound == -1) return QPolygonF(); // key ranges have no overlap
  18819. croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
  18820. // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
  18821. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18822. const int li = croppedData->size()-1; // last index
  18823. if (!qFuzzyCompare(croppedData->at(li).x(), croppedData->at(li-1).x()))
  18824. slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x());
  18825. else
  18826. slope = 0;
  18827. (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x()));
  18828. (*croppedData)[li].setX(staticData->last().x());
  18829. } else // mKeyAxis->orientation() == Qt::Vertical
  18830. {
  18831. // y is key
  18832. // crop lower bound:
  18833. if (staticData->first().y() < croppedData->first().y()) // other one must be cropped
  18834. qSwap(staticData, croppedData);
  18835. int lowBound = findIndexBelowY(croppedData, staticData->first().y());
  18836. if (lowBound == -1) return QPolygonF(); // key ranges have no overlap
  18837. croppedData->remove(0, lowBound);
  18838. // set lowest point of cropped data to fit exactly key position of first static data point via linear interpolation:
  18839. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18840. double slope;
  18841. if (!qFuzzyCompare(croppedData->at(1).y(), croppedData->at(0).y())) // avoid division by zero in step plots
  18842. slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y());
  18843. else
  18844. slope = 0;
  18845. (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y()));
  18846. (*croppedData)[0].setY(staticData->first().y());
  18847. // crop upper bound:
  18848. if (staticData->last().y() > croppedData->last().y()) // other one must be cropped
  18849. qSwap(staticData, croppedData);
  18850. int highBound = findIndexAboveY(croppedData, staticData->last().y());
  18851. if (highBound == -1) return QPolygonF(); // key ranges have no overlap
  18852. croppedData->remove(highBound+1, croppedData->size()-(highBound+1));
  18853. // set highest point of cropped data to fit exactly key position of last static data point via linear interpolation:
  18854. if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation
  18855. int li = croppedData->size()-1; // last index
  18856. if (!qFuzzyCompare(croppedData->at(li).y(), croppedData->at(li-1).y())) // avoid division by zero in step plots
  18857. slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y());
  18858. else
  18859. slope = 0;
  18860. (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y()));
  18861. (*croppedData)[li].setY(staticData->last().y());
  18862. }
  18863. // return joined:
  18864. for (int i=otherSegmentData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted
  18865. thisSegmentData << otherSegmentData.at(i);
  18866. return QPolygonF(thisSegmentData);
  18867. }
  18868. /*! \internal
  18869. Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in
  18870. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18871. axis is horizontal.
  18872. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18873. */
  18874. int QCPGraph::findIndexAboveX(const QVector<QPointF> *data, double x) const
  18875. {
  18876. for (int i=data->size()-1; i>=0; --i)
  18877. {
  18878. if (data->at(i).x() < x)
  18879. {
  18880. if (i<data->size()-1)
  18881. return i+1;
  18882. else
  18883. return data->size()-1;
  18884. }
  18885. }
  18886. return -1;
  18887. }
  18888. /*! \internal
  18889. Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in
  18890. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18891. axis is horizontal.
  18892. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18893. */
  18894. int QCPGraph::findIndexBelowX(const QVector<QPointF> *data, double x) const
  18895. {
  18896. for (int i=0; i<data->size(); ++i)
  18897. {
  18898. if (data->at(i).x() > x)
  18899. {
  18900. if (i>0)
  18901. return i-1;
  18902. else
  18903. return 0;
  18904. }
  18905. }
  18906. return -1;
  18907. }
  18908. /*! \internal
  18909. Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in
  18910. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18911. axis is vertical.
  18912. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18913. */
  18914. int QCPGraph::findIndexAboveY(const QVector<QPointF> *data, double y) const
  18915. {
  18916. for (int i=data->size()-1; i>=0; --i)
  18917. {
  18918. if (data->at(i).y() < y)
  18919. {
  18920. if (i<data->size()-1)
  18921. return i+1;
  18922. else
  18923. return data->size()-1;
  18924. }
  18925. }
  18926. return -1;
  18927. }
  18928. /*! \internal
  18929. Calculates the minimum distance in pixels the graph's representation has from the given \a
  18930. pixelPoint. This is used to determine whether the graph was clicked or not, e.g. in \ref
  18931. selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that if
  18932. the graph has a line representation, the returned distance may be smaller than the distance to
  18933. the \a closestData point, since the distance to the graph line is also taken into account.
  18934. If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape
  18935. is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns -1.0.
  18936. */
  18937. double QCPGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
  18938. {
  18939. closestData = mDataContainer->constEnd();
  18940. if (mDataContainer->isEmpty())
  18941. return -1.0;
  18942. if (mLineStyle == LineStyle::lsNone && mScatterStyle.isNone())
  18943. return -1.0;
  18944. // calculate minimum distances to graph data points and find closestData iterator:
  18945. double minDistSqr = (std::numeric_limits<double>::max)();
  18946. // determine which key range comes into question, taking selection tolerance around pos into account:
  18947. double posKeyMin, posKeyMax, dummy;
  18948. pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
  18949. pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
  18950. if (posKeyMin > posKeyMax)
  18951. qSwap(posKeyMin, posKeyMax);
  18952. // iterate over found data points and then choose the one with the shortest distance to pos:
  18953. QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
  18954. QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
  18955. for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
  18956. {
  18957. const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
  18958. if (currentDistSqr < minDistSqr)
  18959. {
  18960. minDistSqr = currentDistSqr;
  18961. closestData = it;
  18962. }
  18963. }
  18964. // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
  18965. if (mLineStyle != LineStyle::lsNone)
  18966. {
  18967. // line displayed, calculate distance to line segments:
  18968. QVector<QPointF> lineData;
  18969. 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
  18970. QCPVector2D p(pixelPoint);
  18971. const int step = mLineStyle== LineStyle::lsImpulse ? 2 : 1; // impulse plot differs from other line styles in that the lineData points are only pairwise connected
  18972. for (int i=0; i<lineData.size()-1; i+=step)
  18973. {
  18974. const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
  18975. if (currentDistSqr < minDistSqr)
  18976. minDistSqr = currentDistSqr;
  18977. }
  18978. }
  18979. return qSqrt(minDistSqr);
  18980. }
  18981. /*! \internal
  18982. Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in
  18983. \a data points are ordered ascending, as is ensured by \ref getLines/\ref getScatters if the key
  18984. axis is vertical.
  18985. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon.
  18986. */
  18987. int QCPGraph::findIndexBelowY(const QVector<QPointF> *data, double y) const
  18988. {
  18989. for (int i=0; i<data->size(); ++i)
  18990. {
  18991. if (data->at(i).y() > y)
  18992. {
  18993. if (i>0)
  18994. return i-1;
  18995. else
  18996. return 0;
  18997. }
  18998. }
  18999. return -1;
  19000. }
  19001. /* end of 'src/plottables/plottable-graph.cpp' */
  19002. /* including file 'src/plottables/plottable-curve.cpp' */
  19003. /* modified 2021-03-29T02:30:44, size 63851 */
  19004. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19005. //////////////////// QCPCurveData
  19006. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19007. /*! \class QCPCurveData
  19008. \brief Holds the data of one single data point for QCPCurve.
  19009. The stored data is:
  19010. \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)
  19011. \li \a key: coordinate on the key axis of this curve point (this is the \a mainKey)
  19012. \li \a value: coordinate on the value axis of this curve point (this is the \a mainValue)
  19013. The container for storing multiple data points is \ref QCPCurveDataContainer. It is a typedef for
  19014. \ref QCPDataContainer with \ref QCPCurveData as the DataType template parameter. See the
  19015. documentation there for an explanation regarding the data type's generic methods.
  19016. \see QCPCurveDataContainer
  19017. */
  19018. /* start documentation of inline functions */
  19019. /*! \fn double QCPCurveData::sortKey() const
  19020. Returns the \a t member of this data point.
  19021. For a general explanation of what this method is good for in the context of the data container,
  19022. see the documentation of \ref QCPDataContainer.
  19023. */
  19024. /*! \fn static QCPCurveData QCPCurveData::fromSortKey(double sortKey)
  19025. Returns a data point with the specified \a sortKey (assigned to the data point's \a t member).
  19026. All other members are set to zero.
  19027. For a general explanation of what this method is good for in the context of the data container,
  19028. see the documentation of \ref QCPDataContainer.
  19029. */
  19030. /*! \fn static static bool QCPCurveData::sortKeyIsMainKey()
  19031. Since the member \a key is the data point key coordinate and the member \a t is the data ordering
  19032. parameter, this method returns false.
  19033. For a general explanation of what this method is good for in the context of the data container,
  19034. see the documentation of \ref QCPDataContainer.
  19035. */
  19036. /*! \fn double QCPCurveData::mainKey() const
  19037. Returns the \a key member of this data point.
  19038. For a general explanation of what this method is good for in the context of the data container,
  19039. see the documentation of \ref QCPDataContainer.
  19040. */
  19041. /*! \fn double QCPCurveData::mainValue() const
  19042. Returns the \a value member of this data point.
  19043. For a general explanation of what this method is good for in the context of the data container,
  19044. see the documentation of \ref QCPDataContainer.
  19045. */
  19046. /*! \fn QCPRange QCPCurveData::valueRange() const
  19047. Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
  19048. For a general explanation of what this method is good for in the context of the data container,
  19049. see the documentation of \ref QCPDataContainer.
  19050. */
  19051. /* end documentation of inline functions */
  19052. /*!
  19053. Constructs a curve data point with t, key and value set to zero.
  19054. */
  19055. QCPCurveData::QCPCurveData() :
  19056. t(0),
  19057. key(0),
  19058. value(0)
  19059. {
  19060. }
  19061. /*!
  19062. Constructs a curve data point with the specified \a t, \a key and \a value.
  19063. */
  19064. QCPCurveData::QCPCurveData(double t, double key, double value) :
  19065. t(t),
  19066. key(key),
  19067. value(value)
  19068. {
  19069. }
  19070. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19071. //////////////////// QCPCurve
  19072. ////////////////////////////////////////////////////////////////////////////////////////////////////
  19073. /*! \class QCPCurve
  19074. \brief A plottable representing a parametric curve in a plot.
  19075. \image html QCPCurve.png
  19076. Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate,
  19077. so their visual representation can have \a loops. This is realized by introducing a third
  19078. coordinate \a t, which defines the order of the points described by the other two coordinates \a
  19079. x and \a y.
  19080. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  19081. also access and modify the curve's data via the \ref data method, which returns a pointer to the
  19082. internal \ref QCPCurveDataContainer.
  19083. Gaps in the curve can be created by adding data points with NaN as key and value
  19084. (<tt>qQNaN()</tt> or <tt>std::numeric_limits<double>::quiet_NaN()</tt>) in between the two data points that shall be
  19085. separated.
  19086. \section qcpcurve-appearance Changing the appearance
  19087. The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush).
  19088. \section qcpcurve-usage Usage
  19089. Like all data representing objects in QCustomPlot, the QCPCurve is a plottable
  19090. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  19091. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  19092. Usually, you first create an instance:
  19093. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-1
  19094. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  19095. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  19096. The newly created plottable can be modified, e.g.:
  19097. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-creation-2
  19098. */
  19099. /* start of documentation of inline functions */
  19100. /*! \fn QSharedPointer<QCPCurveDataContainer> QCPCurve::data() const
  19101. Returns a shared pointer to the internal data storage of type \ref QCPCurveDataContainer. You may
  19102. use it to directly manipulate the data, which may be more convenient and faster than using the
  19103. regular \ref setData or \ref addData methods.
  19104. */
  19105. /* end of documentation of inline functions */
  19106. /*!
  19107. Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  19108. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  19109. the same orientation. If either of these restrictions is violated, a corresponding message is
  19110. printed to the debug output (qDebug), the construction is not aborted, though.
  19111. The created QCPCurve is automatically registered with the QCustomPlot instance inferred from \a
  19112. keyAxis. This QCustomPlot instance takes ownership of the QCPCurve, so do not delete it manually
  19113. but use QCustomPlot::removePlottable() instead.
  19114. */
  19115. QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  19116. QCPAbstractPlottable1D<QCPCurveData>(keyAxis, valueAxis),
  19117. mScatterSkip{},
  19118. mLineStyle{}
  19119. {
  19120. // modify inherited properties from abstract plottable:
  19121. setPen(QPen(Qt::blue, 0));
  19122. setBrush(Qt::NoBrush);
  19123. setScatterStyle(QCPScatterStyle());
  19124. setLineStyle(lsLine);
  19125. setScatterSkip(0);
  19126. }
  19127. QCPCurve::~QCPCurve()
  19128. {
  19129. }
  19130. /*! \overload
  19131. Replaces the current data container with the provided \a data container.
  19132. Since a QSharedPointer is used, multiple QCPCurves may share the same data container safely.
  19133. Modifying the data in the container will then affect all curves that share the container. Sharing
  19134. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  19135. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-1
  19136. If you do not wish to share containers, but create a copy from an existing container, rather use
  19137. the \ref QCPDataContainer<DataType>::set method on the curve's data container directly:
  19138. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcurve-datasharing-2
  19139. \see addData
  19140. */
  19141. void QCPCurve::setData(QSharedPointer<QCPCurveDataContainer> data)
  19142. {
  19143. mDataContainer = data;
  19144. }
  19145. /*! \overload
  19146. Replaces the current data with the provided points in \a t, \a keys and \a values. The provided
  19147. vectors should have equal length. Else, the number of added points will be the size of the
  19148. smallest vector.
  19149. If you can guarantee that the passed data points are sorted by \a t in ascending order, you can
  19150. set \a alreadySorted to true, to improve performance by saving a sorting run.
  19151. \see addData
  19152. */
  19153. void QCPCurve::setData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  19154. {
  19155. mDataContainer->clear();
  19156. addData(t, keys, values, alreadySorted);
  19157. }
  19158. /*! \overload
  19159. Replaces the current data with the provided points in \a keys and \a values. The provided vectors
  19160. should have equal length. Else, the number of added points will be the size of the smallest
  19161. vector.
  19162. The t parameter of each data point will be set to the integer index of the respective key/value
  19163. pair.
  19164. \see addData
  19165. */
  19166. void QCPCurve::setData(const QVector<double> &keys, const QVector<double> &values)
  19167. {
  19168. mDataContainer->clear();
  19169. addData(keys, values);
  19170. }
  19171. /*!
  19172. Sets the visual appearance of single data points in the plot. If set to \ref
  19173. QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate
  19174. line style).
  19175. \see QCPScatterStyle, setLineStyle
  19176. */
  19177. void QCPCurve::setScatterStyle(const QCPScatterStyle &style)
  19178. {
  19179. mScatterStyle = style;
  19180. }
  19181. /*!
  19182. If scatters are displayed (scatter style not \ref QCPScatterStyle::ssNone), \a skip number of
  19183. scatter points are skipped/not drawn after every drawn scatter point.
  19184. This can be used to make the data appear sparser while for example still having a smooth line,
  19185. and to improve performance for very high density plots.
  19186. If \a skip is set to 0 (default), all scatter points are drawn.
  19187. \see setScatterStyle
  19188. */
  19189. void QCPCurve::setScatterSkip(int skip)
  19190. {
  19191. mScatterSkip = qMax(0, skip);
  19192. }
  19193. /*!
  19194. Sets how the single data points are connected in the plot or how they are represented visually
  19195. apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref
  19196. setScatterStyle to the desired scatter style.
  19197. \see setScatterStyle
  19198. */
  19199. void QCPCurve::setLineStyle(QCPCurve::LineStyle style)
  19200. {
  19201. mLineStyle = style;
  19202. }
  19203. /*! \overload
  19204. Adds the provided points in \a t, \a keys and \a values to the current data. The provided vectors
  19205. should have equal length. Else, the number of added points will be the size of the smallest
  19206. vector.
  19207. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  19208. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  19209. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19210. returns a pointer to the internal data container.
  19211. */
  19212. void QCPCurve::addData(const QVector<double> &t, const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  19213. {
  19214. if (t.size() != keys.size() || t.size() != values.size())
  19215. qDebug() << Q_FUNC_INFO << "ts, keys and values have different sizes:" << t.size() << keys.size() << values.size();
  19216. const int n = qMin(qMin(t.size(), keys.size()), values.size());
  19217. QVector<QCPCurveData> tempData(n);
  19218. QVector<QCPCurveData>::iterator it = tempData.begin();
  19219. const QVector<QCPCurveData>::iterator itEnd = tempData.end();
  19220. int i = 0;
  19221. while (it != itEnd)
  19222. {
  19223. it->t = t[i];
  19224. it->key = keys[i];
  19225. it->value = values[i];
  19226. ++it;
  19227. ++i;
  19228. }
  19229. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  19230. }
  19231. /*! \overload
  19232. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  19233. should have equal length. Else, the number of added points will be the size of the smallest
  19234. vector.
  19235. The t parameter of each data point will be set to the integer index of the respective key/value
  19236. pair.
  19237. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19238. returns a pointer to the internal data container.
  19239. */
  19240. void QCPCurve::addData(const QVector<double> &keys, const QVector<double> &values)
  19241. {
  19242. if (keys.size() != values.size())
  19243. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  19244. const int n = qMin(keys.size(), values.size());
  19245. double tStart;
  19246. if (!mDataContainer->isEmpty())
  19247. tStart = (mDataContainer->constEnd()-1)->t + 1.0;
  19248. else
  19249. tStart = 0;
  19250. QVector<QCPCurveData> tempData(n);
  19251. QVector<QCPCurveData>::iterator it = tempData.begin();
  19252. const QVector<QCPCurveData>::iterator itEnd = tempData.end();
  19253. int i = 0;
  19254. while (it != itEnd)
  19255. {
  19256. it->t = tStart + i;
  19257. it->key = keys[i];
  19258. it->value = values[i];
  19259. ++it;
  19260. ++i;
  19261. }
  19262. mDataContainer->add(tempData, true); // don't modify tempData beyond this to prevent copy on write
  19263. }
  19264. /*! \overload
  19265. Adds the provided data point as \a t, \a key and \a value to the current data.
  19266. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19267. returns a pointer to the internal data container.
  19268. */
  19269. void QCPCurve::addData(double t, double key, double value)
  19270. {
  19271. mDataContainer->add(QCPCurveData(t, key, value));
  19272. }
  19273. /*! \overload
  19274. Adds the provided data point as \a key and \a value to the current data.
  19275. The t parameter is generated automatically by increments of 1 for each point, starting at the
  19276. highest t of previously existing data or 0, if the curve data is empty.
  19277. Alternatively, you can also access and modify the data directly via the \ref data method, which
  19278. returns a pointer to the internal data container.
  19279. */
  19280. void QCPCurve::addData(double key, double value)
  19281. {
  19282. if (!mDataContainer->isEmpty())
  19283. mDataContainer->add(QCPCurveData((mDataContainer->constEnd()-1)->t + 1.0, key, value));
  19284. else
  19285. mDataContainer->add(QCPCurveData(0.0, key, value));
  19286. }
  19287. /*!
  19288. Implements a selectTest specific to this plottable's point geometry.
  19289. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  19290. point to \a pos.
  19291. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  19292. */
  19293. double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  19294. {
  19295. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  19296. return -1;
  19297. if (!mKeyAxis || !mValueAxis)
  19298. return -1;
  19299. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  19300. {
  19301. QCPCurveDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  19302. double result = pointDistance(pos, closestDataPoint);
  19303. if (details)
  19304. {
  19305. int pointIndex = int( closestDataPoint-mDataContainer->constBegin() );
  19306. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  19307. }
  19308. return result;
  19309. } else
  19310. return -1;
  19311. }
  19312. /* inherits documentation from base class */
  19313. QCPRange QCPCurve::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  19314. {
  19315. return mDataContainer->keyRange(foundRange, inSignDomain);
  19316. }
  19317. /* inherits documentation from base class */
  19318. QCPRange QCPCurve::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  19319. {
  19320. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  19321. }
  19322. /* inherits documentation from base class */
  19323. void QCPCurve::draw(QCPPainter *painter)
  19324. {
  19325. if (mDataContainer->isEmpty()) return;
  19326. // allocate line vector:
  19327. QVector<QPointF> lines, scatters;
  19328. // loop over and draw segments of unselected/selected data:
  19329. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  19330. getDataSegments(selectedSegments, unselectedSegments);
  19331. allSegments << unselectedSegments << selectedSegments;
  19332. for (int i=0; i<allSegments.size(); ++i)
  19333. {
  19334. bool isSelectedSegment = i >= unselectedSegments.size();
  19335. // fill with curve data:
  19336. QPen finalCurvePen = mPen; // determine the final pen already here, because the line optimization depends on its stroke width
  19337. if (isSelectedSegment && mSelectionDecorator)
  19338. finalCurvePen = mSelectionDecorator->pen();
  19339. 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)
  19340. getCurveLines(&lines, lineDataRange, finalCurvePen.widthF());
  19341. // check data validity if flag set:
  19342. #ifdef QCUSTOMPLOT_CHECK_DATA
  19343. for (QCPCurveDataContainer::const_iterator it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  19344. {
  19345. if (QCP::isInvalidData(it->t) ||
  19346. QCP::isInvalidData(it->key, it->value))
  19347. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
  19348. }
  19349. #endif
  19350. // draw curve fill:
  19351. applyFillAntialiasingHint(painter);
  19352. if (isSelectedSegment && mSelectionDecorator)
  19353. mSelectionDecorator->applyBrush(painter);
  19354. else
  19355. painter->setBrush(mBrush);
  19356. painter->setPen(Qt::NoPen);
  19357. if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
  19358. painter->drawPolygon(QPolygonF(lines));
  19359. // draw curve line:
  19360. if (mLineStyle != lsNone)
  19361. {
  19362. painter->setPen(finalCurvePen);
  19363. painter->setBrush(Qt::NoBrush);
  19364. drawCurveLine(painter, lines);
  19365. }
  19366. // draw scatters:
  19367. QCPScatterStyle finalScatterStyle = mScatterStyle;
  19368. if (isSelectedSegment && mSelectionDecorator)
  19369. finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
  19370. if (!finalScatterStyle.isNone())
  19371. {
  19372. getScatters(&scatters, allSegments.at(i), finalScatterStyle.size());
  19373. drawScatterPlot(painter, scatters, finalScatterStyle);
  19374. }
  19375. }
  19376. // draw other selection decoration that isn't just line/scatter pens and brushes:
  19377. if (mSelectionDecorator)
  19378. mSelectionDecorator->drawDecoration(painter, selection());
  19379. }
  19380. /* inherits documentation from base class */
  19381. void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  19382. {
  19383. // draw fill:
  19384. if (mBrush.style() != Qt::NoBrush)
  19385. {
  19386. applyFillAntialiasingHint(painter);
  19387. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  19388. }
  19389. // draw line vertically centered:
  19390. if (mLineStyle != lsNone)
  19391. {
  19392. applyDefaultAntialiasingHint(painter);
  19393. painter->setPen(mPen);
  19394. 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
  19395. }
  19396. // draw scatter symbol:
  19397. if (!mScatterStyle.isNone())
  19398. {
  19399. applyScattersAntialiasingHint(painter);
  19400. // scale scatter pixmap if it's too large to fit in legend icon rect:
  19401. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  19402. {
  19403. QCPScatterStyle scaledStyle(mScatterStyle);
  19404. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  19405. scaledStyle.applyTo(painter, mPen);
  19406. scaledStyle.drawShape(painter, QRectF(rect).center());
  19407. } else
  19408. {
  19409. mScatterStyle.applyTo(painter, mPen);
  19410. mScatterStyle.drawShape(painter, QRectF(rect).center());
  19411. }
  19412. }
  19413. }
  19414. /*! \internal
  19415. Draws lines between the points in \a lines, given in pixel coordinates.
  19416. \see drawScatterPlot, getCurveLines
  19417. */
  19418. void QCPCurve::drawCurveLine(QCPPainter *painter, const QVector<QPointF> &lines) const
  19419. {
  19420. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  19421. {
  19422. applyDefaultAntialiasingHint(painter);
  19423. drawPolyline(painter, lines);
  19424. }
  19425. }
  19426. /*! \internal
  19427. Draws scatter symbols at every point passed in \a points, given in pixel coordinates. The
  19428. scatters will be drawn with \a painter and have the appearance as specified in \a style.
  19429. \see drawCurveLine, getCurveLines
  19430. */
  19431. void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &points, const QCPScatterStyle &style) const
  19432. {
  19433. // draw scatter point symbols:
  19434. applyScattersAntialiasingHint(painter);
  19435. style.applyTo(painter, mPen);
  19436. foreach (const QPointF &point, points)
  19437. if (!qIsNaN(point.x()) && !qIsNaN(point.y()))
  19438. style.drawShape(painter, point);
  19439. }
  19440. /*! \internal
  19441. Called by \ref draw to generate points in pixel coordinates which represent the line of the
  19442. curve.
  19443. Line segments that aren't visible in the current axis rect are handled in an optimized way. They
  19444. are projected onto a rectangle slightly larger than the visible axis rect and simplified
  19445. regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside
  19446. the visible axis rect by generating new temporary points on the outer rect if necessary.
  19447. \a lines will be filled with points in pixel coordinates, that can be drawn with \ref
  19448. drawCurveLine.
  19449. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  19450. conversion. In this function, the specified range may exceed the total data bounds without harm:
  19451. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  19452. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  19453. getDataSegments.
  19454. \a penWidth specifies the pen width that will be used to later draw the lines generated by this
  19455. function. This is needed here to calculate an accordingly wider margin around the axis rect when
  19456. performing the line optimization.
  19457. Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref
  19458. getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints.
  19459. \see drawCurveLine, drawScatterPlot
  19460. */
  19461. void QCPCurve::getCurveLines(QVector<QPointF> *lines, const QCPDataRange &dataRange, double penWidth) const
  19462. {
  19463. if (!lines) return;
  19464. lines->clear();
  19465. QCPAxis *keyAxis = mKeyAxis.data();
  19466. QCPAxis *valueAxis = mValueAxis.data();
  19467. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  19468. // add margins to rect to compensate for stroke width
  19469. const double strokeMargin = qMax(qreal(1.0), qreal(penWidth*0.75)); // stroke radius + 50% safety
  19470. const double keyMin = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*keyAxis->pixelOrientation());
  19471. const double keyMax = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*keyAxis->pixelOrientation());
  19472. const double valueMin = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)-strokeMargin*valueAxis->pixelOrientation());
  19473. const double valueMax = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)+strokeMargin*valueAxis->pixelOrientation());
  19474. QCPCurveDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  19475. QCPCurveDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  19476. mDataContainer->limitIteratorsToDataRange(itBegin, itEnd, dataRange);
  19477. if (itBegin == itEnd)
  19478. return;
  19479. QCPCurveDataContainer::const_iterator it = itBegin;
  19480. QCPCurveDataContainer::const_iterator prevIt = itEnd-1;
  19481. int prevRegion = getRegion(prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin);
  19482. 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)
  19483. while (it != itEnd)
  19484. {
  19485. const int currentRegion = getRegion(it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19486. if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R
  19487. {
  19488. if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal
  19489. {
  19490. QPointF crossA, crossB;
  19491. if (prevRegion == 5) // we're coming from R, so add this point optimized
  19492. {
  19493. lines->append(getOptimizedPoint(currentRegion, it->key, it->value, prevIt->key, prevIt->value, keyMin, valueMax, keyMax, valueMin));
  19494. // 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
  19495. *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19496. } else if (mayTraverse(prevRegion, currentRegion) &&
  19497. getTraverse(prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin, crossA, crossB))
  19498. {
  19499. // add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point:
  19500. QVector<QPointF> beforeTraverseCornerPoints, afterTraverseCornerPoints;
  19501. getTraverseCornerPoints(prevRegion, currentRegion, keyMin, valueMax, keyMax, valueMin, beforeTraverseCornerPoints, afterTraverseCornerPoints);
  19502. if (it != itBegin)
  19503. {
  19504. *lines << beforeTraverseCornerPoints;
  19505. lines->append(crossA);
  19506. lines->append(crossB);
  19507. *lines << afterTraverseCornerPoints;
  19508. } else
  19509. {
  19510. lines->append(crossB);
  19511. *lines << afterTraverseCornerPoints;
  19512. trailingPoints << beforeTraverseCornerPoints << crossA ;
  19513. }
  19514. } 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)
  19515. {
  19516. *lines << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19517. }
  19518. } else // segment does end in R, so we add previous point optimized and this point at original position
  19519. {
  19520. 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
  19521. trailingPoints << getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin);
  19522. else
  19523. lines->append(getOptimizedPoint(prevRegion, prevIt->key, prevIt->value, it->key, it->value, keyMin, valueMax, keyMax, valueMin));
  19524. lines->append(coordsToPixels(it->key, it->value));
  19525. }
  19526. } else // region didn't change
  19527. {
  19528. if (currentRegion == 5) // still in R, keep adding original points
  19529. {
  19530. lines->append(coordsToPixels(it->key, it->value));
  19531. } else // still outside R, no need to add anything
  19532. {
  19533. // see how this is not doing anything? That's the main optimization...
  19534. }
  19535. }
  19536. prevIt = it;
  19537. prevRegion = currentRegion;
  19538. ++it;
  19539. }
  19540. *lines << trailingPoints;
  19541. }
  19542. /*! \internal
  19543. Called by \ref draw to generate points in pixel coordinates which represent the scatters of the
  19544. curve. If a scatter skip is configured (\ref setScatterSkip), the returned points are accordingly
  19545. sparser.
  19546. Scatters that aren't visible in the current axis rect are optimized away.
  19547. \a scatters will be filled with points in pixel coordinates, that can be drawn with \ref
  19548. drawScatterPlot.
  19549. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  19550. conversion.
  19551. \a scatterWidth specifies the scatter width that will be used to later draw the scatters at pixel
  19552. coordinates generated by this function. This is needed here to calculate an accordingly wider
  19553. margin around the axis rect when performing the data point reduction.
  19554. \see draw, drawScatterPlot
  19555. */
  19556. void QCPCurve::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange, double scatterWidth) const
  19557. {
  19558. if (!scatters) return;
  19559. scatters->clear();
  19560. QCPAxis *keyAxis = mKeyAxis.data();
  19561. QCPAxis *valueAxis = mValueAxis.data();
  19562. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  19563. QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
  19564. QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
  19565. mDataContainer->limitIteratorsToDataRange(begin, end, dataRange);
  19566. if (begin == end)
  19567. return;
  19568. const int scatterModulo = mScatterSkip+1;
  19569. const bool doScatterSkip = mScatterSkip > 0;
  19570. int endIndex = int( end-mDataContainer->constBegin() );
  19571. QCPRange keyRange = keyAxis->range();
  19572. QCPRange valueRange = valueAxis->range();
  19573. // extend range to include width of scatter symbols:
  19574. keyRange.lower = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.lower)-scatterWidth*keyAxis->pixelOrientation());
  19575. keyRange.upper = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyRange.upper)+scatterWidth*keyAxis->pixelOrientation());
  19576. valueRange.lower = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.lower)-scatterWidth*valueAxis->pixelOrientation());
  19577. valueRange.upper = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueRange.upper)+scatterWidth*valueAxis->pixelOrientation());
  19578. QCPCurveDataContainer::const_iterator it = begin;
  19579. int itIndex = int( begin-mDataContainer->constBegin() );
  19580. while (doScatterSkip && it != end && itIndex % scatterModulo != 0) // advance begin iterator to first non-skipped scatter
  19581. {
  19582. ++itIndex;
  19583. ++it;
  19584. }
  19585. if (keyAxis->orientation() == Qt::Vertical)
  19586. {
  19587. while (it != end)
  19588. {
  19589. if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
  19590. scatters->append(QPointF(valueAxis->coordToPixel(it->value), keyAxis->coordToPixel(it->key)));
  19591. // advance iterator to next (non-skipped) data point:
  19592. if (!doScatterSkip)
  19593. ++it;
  19594. else
  19595. {
  19596. itIndex += scatterModulo;
  19597. if (itIndex < endIndex) // make sure we didn't jump over end
  19598. it += scatterModulo;
  19599. else
  19600. {
  19601. it = end;
  19602. itIndex = endIndex;
  19603. }
  19604. }
  19605. }
  19606. } else
  19607. {
  19608. while (it != end)
  19609. {
  19610. if (!qIsNaN(it->value) && keyRange.contains(it->key) && valueRange.contains(it->value))
  19611. scatters->append(QPointF(keyAxis->coordToPixel(it->key), valueAxis->coordToPixel(it->value)));
  19612. // advance iterator to next (non-skipped) data point:
  19613. if (!doScatterSkip)
  19614. ++it;
  19615. else
  19616. {
  19617. itIndex += scatterModulo;
  19618. if (itIndex < endIndex) // make sure we didn't jump over end
  19619. it += scatterModulo;
  19620. else
  19621. {
  19622. it = end;
  19623. itIndex = endIndex;
  19624. }
  19625. }
  19626. }
  19627. }
  19628. }
  19629. /*! \internal
  19630. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19631. It returns the region of the given point (\a key, \a value) with respect to a rectangle defined
  19632. by \a keyMin, \a keyMax, \a valueMin, and \a valueMax.
  19633. The regions are enumerated from top to bottom (\a valueMin to \a valueMax) and left to right (\a
  19634. keyMin to \a keyMax):
  19635. <table style="width:10em; text-align:center">
  19636. <tr><td>1</td><td>4</td><td>7</td></tr>
  19637. <tr><td>2</td><td style="border:1px solid black">5</td><td>8</td></tr>
  19638. <tr><td>3</td><td>6</td><td>9</td></tr>
  19639. </table>
  19640. With the rectangle being region 5, and the outer regions extending infinitely outwards. In the
  19641. curve optimization algorithm, region 5 is considered to be the visible portion of the plot.
  19642. */
  19643. int QCPCurve::getRegion(double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
  19644. {
  19645. if (key < keyMin) // region 123
  19646. {
  19647. if (value > valueMax)
  19648. return 1;
  19649. else if (value < valueMin)
  19650. return 3;
  19651. else
  19652. return 2;
  19653. } else if (key > keyMax) // region 789
  19654. {
  19655. if (value > valueMax)
  19656. return 7;
  19657. else if (value < valueMin)
  19658. return 9;
  19659. else
  19660. return 8;
  19661. } else // region 456
  19662. {
  19663. if (value > valueMax)
  19664. return 4;
  19665. else if (value < valueMin)
  19666. return 6;
  19667. else
  19668. return 5;
  19669. }
  19670. }
  19671. /*! \internal
  19672. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19673. This method is used in case the current segment passes from inside the visible rect (region 5,
  19674. see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by
  19675. the line connecting (\a key, \a value) with (\a otherKey, \a otherValue).
  19676. It returns the intersection point of the segment with the border of region 5.
  19677. For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or
  19678. whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or
  19679. leaving it. It is important though that \a otherRegion correctly identifies the other region not
  19680. equal to 5.
  19681. */
  19682. QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin) const
  19683. {
  19684. // The intersection point interpolation here is done in pixel coordinates, so we don't need to
  19685. // differentiate between different axis scale types. Note that the nomenclature
  19686. // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be
  19687. // different in pixel coordinates (horz/vert key axes, reversed ranges)
  19688. const double keyMinPx = mKeyAxis->coordToPixel(keyMin);
  19689. const double keyMaxPx = mKeyAxis->coordToPixel(keyMax);
  19690. const double valueMinPx = mValueAxis->coordToPixel(valueMin);
  19691. const double valueMaxPx = mValueAxis->coordToPixel(valueMax);
  19692. const double otherValuePx = mValueAxis->coordToPixel(otherValue);
  19693. const double valuePx = mValueAxis->coordToPixel(value);
  19694. const double otherKeyPx = mKeyAxis->coordToPixel(otherKey);
  19695. const double keyPx = mKeyAxis->coordToPixel(key);
  19696. double intersectKeyPx = keyMinPx; // initial key just a fail-safe
  19697. double intersectValuePx = valueMinPx; // initial value just a fail-safe
  19698. switch (otherRegion)
  19699. {
  19700. case 1: // top and left edge
  19701. {
  19702. intersectValuePx = valueMaxPx;
  19703. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19704. 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)
  19705. {
  19706. intersectKeyPx = keyMinPx;
  19707. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19708. }
  19709. break;
  19710. }
  19711. case 2: // left edge
  19712. {
  19713. intersectKeyPx = keyMinPx;
  19714. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19715. break;
  19716. }
  19717. case 3: // bottom and left edge
  19718. {
  19719. intersectValuePx = valueMinPx;
  19720. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19721. 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)
  19722. {
  19723. intersectKeyPx = keyMinPx;
  19724. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19725. }
  19726. break;
  19727. }
  19728. case 4: // top edge
  19729. {
  19730. intersectValuePx = valueMaxPx;
  19731. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19732. break;
  19733. }
  19734. case 5:
  19735. {
  19736. break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table
  19737. }
  19738. case 6: // bottom edge
  19739. {
  19740. intersectValuePx = valueMinPx;
  19741. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19742. break;
  19743. }
  19744. case 7: // top and right edge
  19745. {
  19746. intersectValuePx = valueMaxPx;
  19747. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19748. 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)
  19749. {
  19750. intersectKeyPx = keyMaxPx;
  19751. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19752. }
  19753. break;
  19754. }
  19755. case 8: // right edge
  19756. {
  19757. intersectKeyPx = keyMaxPx;
  19758. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19759. break;
  19760. }
  19761. case 9: // bottom and right edge
  19762. {
  19763. intersectValuePx = valueMinPx;
  19764. intersectKeyPx = otherKeyPx + (keyPx-otherKeyPx)/(valuePx-otherValuePx)*(intersectValuePx-otherValuePx);
  19765. 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)
  19766. {
  19767. intersectKeyPx = keyMaxPx;
  19768. intersectValuePx = otherValuePx + (valuePx-otherValuePx)/(keyPx-otherKeyPx)*(intersectKeyPx-otherKeyPx);
  19769. }
  19770. break;
  19771. }
  19772. }
  19773. if (mKeyAxis->orientation() == Qt::Horizontal)
  19774. return {intersectKeyPx, intersectValuePx};
  19775. else
  19776. return {intersectValuePx, intersectKeyPx};
  19777. }
  19778. /*! \internal
  19779. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19780. In situations where a single segment skips over multiple regions it might become necessary to add
  19781. extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment
  19782. doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts.
  19783. This method provides these points that must be added, assuming the original segment doesn't
  19784. start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by
  19785. \ref getTraverseCornerPoints.)
  19786. For example, consider a segment which directly goes from region 4 to 2 but originally is far out
  19787. to the top left such that it doesn't cross region 5. Naively optimizing these points by
  19788. projecting them on the top and left borders of region 5 will create a segment that surely crosses
  19789. 5, creating a visual artifact in the plot. This method prevents this by providing extra points at
  19790. the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without
  19791. traversing 5.
  19792. */
  19793. 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
  19794. {
  19795. QVector<QPointF> result;
  19796. switch (prevRegion)
  19797. {
  19798. case 1:
  19799. {
  19800. switch (currentRegion)
  19801. {
  19802. case 2: { result << coordsToPixels(keyMin, valueMax); break; }
  19803. case 4: { result << coordsToPixels(keyMin, valueMax); break; }
  19804. case 3: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); break; }
  19805. case 7: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); break; }
  19806. case 6: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19807. case 8: { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19808. 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
  19809. if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
  19810. { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
  19811. else
  19812. { result << coordsToPixels(keyMin, valueMax) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); }
  19813. break;
  19814. }
  19815. }
  19816. break;
  19817. }
  19818. case 2:
  19819. {
  19820. switch (currentRegion)
  19821. {
  19822. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19823. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19824. case 4: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19825. case 6: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19826. case 7: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
  19827. case 9: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
  19828. }
  19829. break;
  19830. }
  19831. case 3:
  19832. {
  19833. switch (currentRegion)
  19834. {
  19835. case 2: { result << coordsToPixels(keyMin, valueMin); break; }
  19836. case 6: { result << coordsToPixels(keyMin, valueMin); break; }
  19837. case 1: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); break; }
  19838. case 9: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); break; }
  19839. case 4: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19840. case 8: { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19841. 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
  19842. if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
  19843. { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
  19844. else
  19845. { result << coordsToPixels(keyMin, valueMin) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); }
  19846. break;
  19847. }
  19848. }
  19849. break;
  19850. }
  19851. case 4:
  19852. {
  19853. switch (currentRegion)
  19854. {
  19855. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19856. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19857. case 2: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19858. case 8: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19859. case 3: { result << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
  19860. case 9: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMax, valueMin); break; }
  19861. }
  19862. break;
  19863. }
  19864. case 5:
  19865. {
  19866. switch (currentRegion)
  19867. {
  19868. case 1: { result << coordsToPixels(keyMin, valueMax); break; }
  19869. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19870. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19871. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19872. }
  19873. break;
  19874. }
  19875. case 6:
  19876. {
  19877. switch (currentRegion)
  19878. {
  19879. case 3: { result << coordsToPixels(keyMin, valueMin); break; }
  19880. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19881. case 2: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19882. case 8: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19883. case 1: { result << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
  19884. case 7: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMax, valueMax); break; }
  19885. }
  19886. break;
  19887. }
  19888. case 7:
  19889. {
  19890. switch (currentRegion)
  19891. {
  19892. case 4: { result << coordsToPixels(keyMax, valueMax); break; }
  19893. case 8: { result << coordsToPixels(keyMax, valueMax); break; }
  19894. case 1: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); break; }
  19895. case 9: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); break; }
  19896. case 2: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); break; }
  19897. case 6: { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19898. 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
  19899. if ((value-prevValue)/(key-prevKey)*(keyMax-key)+value < valueMin) // segment passes below R
  19900. { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
  19901. else
  19902. { result << coordsToPixels(keyMax, valueMax) << coordsToPixels(keyMin, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); }
  19903. break;
  19904. }
  19905. }
  19906. break;
  19907. }
  19908. case 8:
  19909. {
  19910. switch (currentRegion)
  19911. {
  19912. case 7: { result << coordsToPixels(keyMax, valueMax); break; }
  19913. case 9: { result << coordsToPixels(keyMax, valueMin); break; }
  19914. case 4: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19915. case 6: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); break; }
  19916. case 1: { result << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); break; }
  19917. case 3: { result << coordsToPixels(keyMax, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMin); break; }
  19918. }
  19919. break;
  19920. }
  19921. case 9:
  19922. {
  19923. switch (currentRegion)
  19924. {
  19925. case 6: { result << coordsToPixels(keyMax, valueMin); break; }
  19926. case 8: { result << coordsToPixels(keyMax, valueMin); break; }
  19927. case 3: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); break; }
  19928. case 7: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); break; }
  19929. case 2: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); break; }
  19930. case 4: { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); break; }
  19931. 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
  19932. if ((value-prevValue)/(key-prevKey)*(keyMin-key)+value < valueMin) // segment passes below R
  19933. { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMin, valueMin); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
  19934. else
  19935. { result << coordsToPixels(keyMax, valueMin) << coordsToPixels(keyMax, valueMax); result.append(result.last()); result << coordsToPixels(keyMin, valueMax); }
  19936. break;
  19937. }
  19938. }
  19939. break;
  19940. }
  19941. }
  19942. return result;
  19943. }
  19944. /*! \internal
  19945. This function is part of the curve optimization algorithm of \ref getCurveLines.
  19946. This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref
  19947. getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion
  19948. nor \a currentRegion is 5 itself.
  19949. If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the
  19950. segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref
  19951. getTraverse).
  19952. */
  19953. bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const
  19954. {
  19955. switch (prevRegion)
  19956. {
  19957. case 1:
  19958. {
  19959. switch (currentRegion)
  19960. {
  19961. case 4:
  19962. case 7:
  19963. case 2:
  19964. case 3: return false;
  19965. default: return true;
  19966. }
  19967. }
  19968. case 2:
  19969. {
  19970. switch (currentRegion)
  19971. {
  19972. case 1:
  19973. case 3: return false;
  19974. default: return true;
  19975. }
  19976. }
  19977. case 3:
  19978. {
  19979. switch (currentRegion)
  19980. {
  19981. case 1:
  19982. case 2:
  19983. case 6:
  19984. case 9: return false;
  19985. default: return true;
  19986. }
  19987. }
  19988. case 4:
  19989. {
  19990. switch (currentRegion)
  19991. {
  19992. case 1:
  19993. case 7: return false;
  19994. default: return true;
  19995. }
  19996. }
  19997. case 5: return false; // should never occur
  19998. case 6:
  19999. {
  20000. switch (currentRegion)
  20001. {
  20002. case 3:
  20003. case 9: return false;
  20004. default: return true;
  20005. }
  20006. }
  20007. case 7:
  20008. {
  20009. switch (currentRegion)
  20010. {
  20011. case 1:
  20012. case 4:
  20013. case 8:
  20014. case 9: return false;
  20015. default: return true;
  20016. }
  20017. }
  20018. case 8:
  20019. {
  20020. switch (currentRegion)
  20021. {
  20022. case 7:
  20023. case 9: return false;
  20024. default: return true;
  20025. }
  20026. }
  20027. case 9:
  20028. {
  20029. switch (currentRegion)
  20030. {
  20031. case 3:
  20032. case 6:
  20033. case 8:
  20034. case 7: return false;
  20035. default: return true;
  20036. }
  20037. }
  20038. default: return true;
  20039. }
  20040. }
  20041. /*! \internal
  20042. This function is part of the curve optimization algorithm of \ref getCurveLines.
  20043. This method assumes that the \ref mayTraverse test has returned true, so there is a chance the
  20044. segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible
  20045. region 5.
  20046. The return value of this method indicates whether the segment actually traverses region 5 or not.
  20047. If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and
  20048. exit points of region 5. They will become the optimized points for that segment.
  20049. */
  20050. bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double keyMin, double valueMax, double keyMax, double valueMin, QPointF &crossA, QPointF &crossB) const
  20051. {
  20052. // The intersection point interpolation here is done in pixel coordinates, so we don't need to
  20053. // differentiate between different axis scale types. Note that the nomenclature
  20054. // top/left/bottom/right/min/max is with respect to the rect in plot coordinates, wich may be
  20055. // different in pixel coordinates (horz/vert key axes, reversed ranges)
  20056. QList<QPointF> intersections;
  20057. const double valueMinPx = mValueAxis->coordToPixel(valueMin);
  20058. const double valueMaxPx = mValueAxis->coordToPixel(valueMax);
  20059. const double keyMinPx = mKeyAxis->coordToPixel(keyMin);
  20060. const double keyMaxPx = mKeyAxis->coordToPixel(keyMax);
  20061. const double keyPx = mKeyAxis->coordToPixel(key);
  20062. const double valuePx = mValueAxis->coordToPixel(value);
  20063. const double prevKeyPx = mKeyAxis->coordToPixel(prevKey);
  20064. const double prevValuePx = mValueAxis->coordToPixel(prevValue);
  20065. if (qFuzzyIsNull(keyPx-prevKeyPx)) // line is parallel to value axis
  20066. {
  20067. // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here
  20068. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMinPx) : QPointF(valueMinPx, keyPx)); // direction will be taken care of at end of method
  20069. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyPx, valueMaxPx) : QPointF(valueMaxPx, keyPx));
  20070. } else if (qFuzzyIsNull(valuePx-prevValuePx)) // line is parallel to key axis
  20071. {
  20072. // due to region filter in mayTraverse(), if line is parallel to value or key axis, region 5 is traversed here
  20073. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, valuePx) : QPointF(valuePx, keyMinPx)); // direction will be taken care of at end of method
  20074. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, valuePx) : QPointF(valuePx, keyMaxPx));
  20075. } else // line is skewed
  20076. {
  20077. double gamma;
  20078. double keyPerValuePx = (keyPx-prevKeyPx)/(valuePx-prevValuePx);
  20079. // check top of rect:
  20080. gamma = prevKeyPx + (valueMaxPx-prevValuePx)*keyPerValuePx;
  20081. if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed
  20082. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMaxPx) : QPointF(valueMaxPx, gamma));
  20083. // check bottom of rect:
  20084. gamma = prevKeyPx + (valueMinPx-prevValuePx)*keyPerValuePx;
  20085. if (gamma >= qMin(keyMinPx, keyMaxPx) && gamma <= qMax(keyMinPx, keyMaxPx)) // qMin/qMax necessary since axes may be reversed
  20086. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(gamma, valueMinPx) : QPointF(valueMinPx, gamma));
  20087. const double valuePerKeyPx = 1.0/keyPerValuePx;
  20088. // check left of rect:
  20089. gamma = prevValuePx + (keyMinPx-prevKeyPx)*valuePerKeyPx;
  20090. if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed
  20091. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMinPx, gamma) : QPointF(gamma, keyMinPx));
  20092. // check right of rect:
  20093. gamma = prevValuePx + (keyMaxPx-prevKeyPx)*valuePerKeyPx;
  20094. if (gamma >= qMin(valueMinPx, valueMaxPx) && gamma <= qMax(valueMinPx, valueMaxPx)) // qMin/qMax necessary since axes may be reversed
  20095. intersections.append(mKeyAxis->orientation() == Qt::Horizontal ? QPointF(keyMaxPx, gamma) : QPointF(gamma, keyMaxPx));
  20096. }
  20097. // handle cases where found points isn't exactly 2:
  20098. if (intersections.size() > 2)
  20099. {
  20100. // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between:
  20101. double distSqrMax = 0;
  20102. QPointF pv1, pv2;
  20103. for (int i=0; i<intersections.size()-1; ++i)
  20104. {
  20105. for (int k=i+1; k<intersections.size(); ++k)
  20106. {
  20107. QPointF distPoint = intersections.at(i)-intersections.at(k);
  20108. double distSqr = distPoint.x()*distPoint.x()+distPoint.y()+distPoint.y();
  20109. if (distSqr > distSqrMax)
  20110. {
  20111. pv1 = intersections.at(i);
  20112. pv2 = intersections.at(k);
  20113. distSqrMax = distSqr;
  20114. }
  20115. }
  20116. }
  20117. intersections = QList<QPointF>() << pv1 << pv2;
  20118. } else if (intersections.size() != 2)
  20119. {
  20120. // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment
  20121. return false;
  20122. }
  20123. // possibly re-sort points so optimized point segment has same direction as original segment:
  20124. double xDelta = keyPx-prevKeyPx;
  20125. double yDelta = valuePx-prevValuePx;
  20126. if (mKeyAxis->orientation() != Qt::Horizontal)
  20127. qSwap(xDelta, yDelta);
  20128. 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
  20129. intersections.move(0, 1);
  20130. crossA = intersections.at(0);
  20131. crossB = intersections.at(1);
  20132. return true;
  20133. }
  20134. /*! \internal
  20135. This function is part of the curve optimization algorithm of \ref getCurveLines.
  20136. This method assumes that the \ref getTraverse test has returned true, so the segment definitely
  20137. traverses the visible region 5 when going from \a prevRegion to \a currentRegion.
  20138. In certain situations it is not sufficient to merely generate the entry and exit points of the
  20139. segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in
  20140. addition to traversing region 5, skips another region outside of region 5, which makes it
  20141. necessary to add an optimized corner point there (very similar to the job \ref
  20142. getOptimizedCornerPoints does for segments that are completely in outside regions and don't
  20143. traverse 5).
  20144. As an example, consider a segment going from region 1 to region 6, traversing the lower left
  20145. corner of region 5. In this configuration, the segment additionally crosses the border between
  20146. region 1 and 2 before entering region 5. This makes it necessary to add an additional point in
  20147. the top left corner, before adding the optimized traverse points. So in this case, the output
  20148. parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be
  20149. empty.
  20150. In some cases, such as when going from region 1 to 9, it may even be necessary to add additional
  20151. corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse
  20152. return the respective corner points.
  20153. */
  20154. void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double keyMin, double valueMax, double keyMax, double valueMin, QVector<QPointF> &beforeTraverse, QVector<QPointF> &afterTraverse) const
  20155. {
  20156. switch (prevRegion)
  20157. {
  20158. case 1:
  20159. {
  20160. switch (currentRegion)
  20161. {
  20162. case 6: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
  20163. case 9: { beforeTraverse << coordsToPixels(keyMin, valueMax); afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  20164. case 8: { beforeTraverse << coordsToPixels(keyMin, valueMax); break; }
  20165. }
  20166. break;
  20167. }
  20168. case 2:
  20169. {
  20170. switch (currentRegion)
  20171. {
  20172. case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  20173. case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  20174. }
  20175. break;
  20176. }
  20177. case 3:
  20178. {
  20179. switch (currentRegion)
  20180. {
  20181. case 4: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
  20182. case 7: { beforeTraverse << coordsToPixels(keyMin, valueMin); afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  20183. case 8: { beforeTraverse << coordsToPixels(keyMin, valueMin); break; }
  20184. }
  20185. break;
  20186. }
  20187. case 4:
  20188. {
  20189. switch (currentRegion)
  20190. {
  20191. case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  20192. case 9: { afterTraverse << coordsToPixels(keyMax, valueMin); break; }
  20193. }
  20194. break;
  20195. }
  20196. case 5: { break; } // shouldn't happen because this method only handles full traverses
  20197. case 6:
  20198. {
  20199. switch (currentRegion)
  20200. {
  20201. case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  20202. case 7: { afterTraverse << coordsToPixels(keyMax, valueMax); break; }
  20203. }
  20204. break;
  20205. }
  20206. case 7:
  20207. {
  20208. switch (currentRegion)
  20209. {
  20210. case 2: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
  20211. case 3: { beforeTraverse << coordsToPixels(keyMax, valueMax); afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  20212. case 6: { beforeTraverse << coordsToPixels(keyMax, valueMax); break; }
  20213. }
  20214. break;
  20215. }
  20216. case 8:
  20217. {
  20218. switch (currentRegion)
  20219. {
  20220. case 1: { afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  20221. case 3: { afterTraverse << coordsToPixels(keyMin, valueMin); break; }
  20222. }
  20223. break;
  20224. }
  20225. case 9:
  20226. {
  20227. switch (currentRegion)
  20228. {
  20229. case 2: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
  20230. case 1: { beforeTraverse << coordsToPixels(keyMax, valueMin); afterTraverse << coordsToPixels(keyMin, valueMax); break; }
  20231. case 4: { beforeTraverse << coordsToPixels(keyMax, valueMin); break; }
  20232. }
  20233. break;
  20234. }
  20235. }
  20236. }
  20237. /*! \internal
  20238. Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a
  20239. pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in
  20240. \ref selectTest. The closest data point to \a pixelPoint is returned in \a closestData. Note that
  20241. if the curve has a line representation, the returned distance may be smaller than the distance to
  20242. the \a closestData point, since the distance to the curve line is also taken into account.
  20243. If either the curve has no data or if the line style is \ref lsNone and the scatter style's shape
  20244. is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the curve), returns
  20245. -1.0.
  20246. */
  20247. double QCPCurve::pointDistance(const QPointF &pixelPoint, QCPCurveDataContainer::const_iterator &closestData) const
  20248. {
  20249. closestData = mDataContainer->constEnd();
  20250. if (mDataContainer->isEmpty())
  20251. return -1.0;
  20252. if (mLineStyle == LineStyle::lsNone && mScatterStyle.isNone())
  20253. return -1.0;
  20254. if (mDataContainer->size() == 1)
  20255. {
  20256. QPointF dataPoint = coordsToPixels(mDataContainer->constBegin()->key, mDataContainer->constBegin()->value);
  20257. closestData = mDataContainer->constBegin();
  20258. return QCPVector2D(dataPoint-pixelPoint).length();
  20259. }
  20260. // calculate minimum distances to curve data points and find closestData iterator:
  20261. double minDistSqr = (std::numeric_limits<double>::max)();
  20262. // iterate over found data points and then choose the one with the shortest distance to pos:
  20263. QCPCurveDataContainer::const_iterator begin = mDataContainer->constBegin();
  20264. QCPCurveDataContainer::const_iterator end = mDataContainer->constEnd();
  20265. for (QCPCurveDataContainer::const_iterator it=begin; it!=end; ++it)
  20266. {
  20267. const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
  20268. if (currentDistSqr < minDistSqr)
  20269. {
  20270. minDistSqr = currentDistSqr;
  20271. closestData = it;
  20272. }
  20273. }
  20274. // calculate distance to line if there is one (if so, will probably be smaller than distance to closest data point):
  20275. if (mLineStyle != lsNone)
  20276. {
  20277. QVector<QPointF> lines;
  20278. 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
  20279. for (int i=0; i<lines.size()-1; ++i)
  20280. {
  20281. double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(lines.at(i), lines.at(i+1));
  20282. if (currentDistSqr < minDistSqr)
  20283. minDistSqr = currentDistSqr;
  20284. }
  20285. }
  20286. return qSqrt(minDistSqr);
  20287. }
  20288. /* end of 'src/plottables/plottable-curve.cpp' */
  20289. /* including file 'src/plottables/plottable-bars.cpp' */
  20290. /* modified 2021-03-29T02:30:44, size 43907 */
  20291. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20292. //////////////////// QCPBarsGroup
  20293. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20294. /*! \class QCPBarsGroup
  20295. \brief Groups multiple QCPBars together so they appear side by side
  20296. \image html QCPBarsGroup.png
  20297. When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable
  20298. to have them appearing next to each other at each key. This is what adding the respective QCPBars
  20299. plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each
  20300. other, see \ref QCPBars::moveAbove.)
  20301. \section qcpbarsgroup-usage Usage
  20302. To add a QCPBars plottable to the group, create a new group and then add the respective bars
  20303. intances:
  20304. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbarsgroup-creation
  20305. Alternatively to appending to the group like shown above, you can also set the group on the
  20306. QCPBars plottable via \ref QCPBars::setBarsGroup.
  20307. The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The
  20308. bars in this group appear in the plot in the order they were appended. To insert a bars plottable
  20309. at a certain index position, or to reposition a bars plottable which is already in the group, use
  20310. \ref insert.
  20311. To remove specific bars from the group, use either \ref remove or call \ref
  20312. QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable.
  20313. To clear the entire group, call \ref clear, or simply delete the group.
  20314. \section qcpbarsgroup-example Example
  20315. The image above is generated with the following code:
  20316. \snippet documentation/doc-image-generator/mainwindow.cpp qcpbarsgroup-example
  20317. */
  20318. /* start of documentation of inline functions */
  20319. /*! \fn QList<QCPBars*> QCPBarsGroup::bars() const
  20320. Returns all bars currently in this group.
  20321. \see bars(int index)
  20322. */
  20323. /*! \fn int QCPBarsGroup::size() const
  20324. Returns the number of QCPBars plottables that are part of this group.
  20325. */
  20326. /*! \fn bool QCPBarsGroup::isEmpty() const
  20327. Returns whether this bars group is empty.
  20328. \see size
  20329. */
  20330. /*! \fn bool QCPBarsGroup::contains(QCPBars *bars)
  20331. Returns whether the specified \a bars plottable is part of this group.
  20332. */
  20333. /* end of documentation of inline functions */
  20334. /*!
  20335. Constructs a new bars group for the specified QCustomPlot instance.
  20336. */
  20337. QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) :
  20338. QObject(parentPlot),
  20339. mParentPlot(parentPlot),
  20340. mSpacingType(stAbsolute),
  20341. mSpacing(4)
  20342. {
  20343. }
  20344. QCPBarsGroup::~QCPBarsGroup()
  20345. {
  20346. clear();
  20347. }
  20348. /*!
  20349. Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType.
  20350. The actual spacing can then be specified with \ref setSpacing.
  20351. \see setSpacing
  20352. */
  20353. void QCPBarsGroup::setSpacingType(SpacingType spacingType)
  20354. {
  20355. mSpacingType = spacingType;
  20356. }
  20357. /*!
  20358. Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is
  20359. defined by the current \ref SpacingType, which can be set with \ref setSpacingType.
  20360. \see setSpacingType
  20361. */
  20362. void QCPBarsGroup::setSpacing(double spacing)
  20363. {
  20364. mSpacing = spacing;
  20365. }
  20366. /*!
  20367. Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars
  20368. exists, returns \c nullptr.
  20369. \see bars(), size
  20370. */
  20371. QCPBars *QCPBarsGroup::bars(int index) const
  20372. {
  20373. if (index >= 0 && index < mBars.size())
  20374. {
  20375. return mBars.at(index);
  20376. } else
  20377. {
  20378. qDebug() << Q_FUNC_INFO << "index out of bounds:" << index;
  20379. return nullptr;
  20380. }
  20381. }
  20382. /*!
  20383. Removes all QCPBars plottables from this group.
  20384. \see isEmpty
  20385. */
  20386. void QCPBarsGroup::clear()
  20387. {
  20388. const QList<QCPBars*> oldBars = mBars;
  20389. foreach (QCPBars *bars, oldBars)
  20390. bars->setBarsGroup(nullptr); // removes itself from mBars via removeBars
  20391. }
  20392. /*!
  20393. Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref
  20394. QCPBars::setBarsGroup on the \a bars instance.
  20395. \see insert, remove
  20396. */
  20397. void QCPBarsGroup::append(QCPBars *bars)
  20398. {
  20399. if (!bars)
  20400. {
  20401. qDebug() << Q_FUNC_INFO << "bars is 0";
  20402. return;
  20403. }
  20404. if (!mBars.contains(bars))
  20405. bars->setBarsGroup(this);
  20406. else
  20407. qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast<quintptr>(bars);
  20408. }
  20409. /*!
  20410. Inserts the specified \a bars plottable into this group at the specified index position \a i.
  20411. This gives you full control over the ordering of the bars.
  20412. \a bars may already be part of this group. In that case, \a bars is just moved to the new index
  20413. position.
  20414. \see append, remove
  20415. */
  20416. void QCPBarsGroup::insert(int i, QCPBars *bars)
  20417. {
  20418. if (!bars)
  20419. {
  20420. qDebug() << Q_FUNC_INFO << "bars is 0";
  20421. return;
  20422. }
  20423. // first append to bars list normally:
  20424. if (!mBars.contains(bars))
  20425. bars->setBarsGroup(this);
  20426. // then move to according position:
  20427. mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1));
  20428. }
  20429. /*!
  20430. Removes the specified \a bars plottable from this group.
  20431. \see contains, clear
  20432. */
  20433. void QCPBarsGroup::remove(QCPBars *bars)
  20434. {
  20435. if (!bars)
  20436. {
  20437. qDebug() << Q_FUNC_INFO << "bars is 0";
  20438. return;
  20439. }
  20440. if (mBars.contains(bars))
  20441. bars->setBarsGroup(nullptr);
  20442. else
  20443. qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast<quintptr>(bars);
  20444. }
  20445. /*! \internal
  20446. Adds the specified \a bars to the internal mBars list of bars. This method does not change the
  20447. barsGroup property on \a bars.
  20448. \see unregisterBars
  20449. */
  20450. void QCPBarsGroup::registerBars(QCPBars *bars)
  20451. {
  20452. if (!mBars.contains(bars))
  20453. mBars.append(bars);
  20454. }
  20455. /*! \internal
  20456. Removes the specified \a bars from the internal mBars list of bars. This method does not change
  20457. the barsGroup property on \a bars.
  20458. \see registerBars
  20459. */
  20460. void QCPBarsGroup::unregisterBars(QCPBars *bars)
  20461. {
  20462. mBars.removeOne(bars);
  20463. }
  20464. /*! \internal
  20465. Returns the pixel offset in the key dimension the specified \a bars plottable should have at the
  20466. given key coordinate \a keyCoord. The offset is relative to the pixel position of the key
  20467. coordinate \a keyCoord.
  20468. */
  20469. double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord)
  20470. {
  20471. // find list of all base bars in case some mBars are stacked:
  20472. QList<const QCPBars*> baseBars;
  20473. foreach (const QCPBars *b, mBars)
  20474. {
  20475. while (b->barBelow())
  20476. b = b->barBelow();
  20477. if (!baseBars.contains(b))
  20478. baseBars.append(b);
  20479. }
  20480. // find base bar this "bars" is stacked on:
  20481. const QCPBars *thisBase = bars;
  20482. while (thisBase->barBelow())
  20483. thisBase = thisBase->barBelow();
  20484. // determine key pixel offset of this base bars considering all other base bars in this barsgroup:
  20485. double result = 0;
  20486. int index = baseBars.indexOf(thisBase);
  20487. if (index >= 0)
  20488. {
  20489. if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose)
  20490. {
  20491. return result;
  20492. } else
  20493. {
  20494. double lowerPixelWidth, upperPixelWidth;
  20495. int startIndex;
  20496. int dir = (index <= (baseBars.size()-1)/2) ? -1 : 1; // if bar is to lower keys of center, dir is negative
  20497. if (baseBars.size() % 2 == 0) // even number of bars
  20498. {
  20499. startIndex = baseBars.size()/2 + (dir < 0 ? -1 : 0);
  20500. result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing
  20501. } else // uneven number of bars
  20502. {
  20503. startIndex = (baseBars.size()-1)/2+dir;
  20504. baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  20505. result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar
  20506. result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing
  20507. }
  20508. for (int i = startIndex; i != index; i += dir) // add widths and spacings of bars in between center and our bars
  20509. {
  20510. baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  20511. result += qAbs(upperPixelWidth-lowerPixelWidth);
  20512. result += getPixelSpacing(baseBars.at(i), keyCoord);
  20513. }
  20514. // finally half of our bars width:
  20515. baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth);
  20516. result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5;
  20517. // correct sign of result depending on orientation and direction of key axis:
  20518. result *= dir*thisBase->keyAxis()->pixelOrientation();
  20519. }
  20520. }
  20521. return result;
  20522. }
  20523. /*! \internal
  20524. Returns the spacing in pixels which is between this \a bars and the following one, both at the
  20525. key coordinate \a keyCoord.
  20526. \note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only
  20527. needed to get access to the key axis transformation and axis rect for the modes \ref
  20528. stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in
  20529. \ref stPlotCoords on a logarithmic axis.
  20530. */
  20531. double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord)
  20532. {
  20533. switch (mSpacingType)
  20534. {
  20535. case stAbsolute:
  20536. {
  20537. return mSpacing;
  20538. }
  20539. case stAxisRectRatio:
  20540. {
  20541. if (bars->keyAxis()->orientation() == Qt::Horizontal)
  20542. return bars->keyAxis()->axisRect()->width()*mSpacing;
  20543. else
  20544. return bars->keyAxis()->axisRect()->height()*mSpacing;
  20545. }
  20546. case stPlotCoords:
  20547. {
  20548. double keyPixel = bars->keyAxis()->coordToPixel(keyCoord);
  20549. return qAbs(bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel);
  20550. }
  20551. }
  20552. return 0;
  20553. }
  20554. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20555. //////////////////// QCPBarsData
  20556. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20557. /*! \class QCPBarsData
  20558. \brief Holds the data of one single data point (one bar) for QCPBars.
  20559. The stored data is:
  20560. \li \a key: coordinate on the key axis of this bar (this is the \a mainKey and the \a sortKey)
  20561. \li \a value: height coordinate on the value axis of this bar (this is the \a mainValue)
  20562. The container for storing multiple data points is \ref QCPBarsDataContainer. It is a typedef for
  20563. \ref QCPDataContainer with \ref QCPBarsData as the DataType template parameter. See the
  20564. documentation there for an explanation regarding the data type's generic methods.
  20565. \see QCPBarsDataContainer
  20566. */
  20567. /* start documentation of inline functions */
  20568. /*! \fn double QCPBarsData::sortKey() const
  20569. Returns the \a key member of this data point.
  20570. For a general explanation of what this method is good for in the context of the data container,
  20571. see the documentation of \ref QCPDataContainer.
  20572. */
  20573. /*! \fn static QCPBarsData QCPBarsData::fromSortKey(double sortKey)
  20574. Returns a data point with the specified \a sortKey. All other members are set to zero.
  20575. For a general explanation of what this method is good for in the context of the data container,
  20576. see the documentation of \ref QCPDataContainer.
  20577. */
  20578. /*! \fn static static bool QCPBarsData::sortKeyIsMainKey()
  20579. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  20580. this method returns true.
  20581. For a general explanation of what this method is good for in the context of the data container,
  20582. see the documentation of \ref QCPDataContainer.
  20583. */
  20584. /*! \fn double QCPBarsData::mainKey() const
  20585. Returns the \a key member of this data point.
  20586. For a general explanation of what this method is good for in the context of the data container,
  20587. see the documentation of \ref QCPDataContainer.
  20588. */
  20589. /*! \fn double QCPBarsData::mainValue() const
  20590. Returns the \a value member of this data point.
  20591. For a general explanation of what this method is good for in the context of the data container,
  20592. see the documentation of \ref QCPDataContainer.
  20593. */
  20594. /*! \fn QCPRange QCPBarsData::valueRange() const
  20595. Returns a QCPRange with both lower and upper boundary set to \a value of this data point.
  20596. For a general explanation of what this method is good for in the context of the data container,
  20597. see the documentation of \ref QCPDataContainer.
  20598. */
  20599. /* end documentation of inline functions */
  20600. /*!
  20601. Constructs a bar data point with key and value set to zero.
  20602. */
  20603. QCPBarsData::QCPBarsData() :
  20604. key(0),
  20605. value(0)
  20606. {
  20607. }
  20608. /*!
  20609. Constructs a bar data point with the specified \a key and \a value.
  20610. */
  20611. QCPBarsData::QCPBarsData(double key, double value) :
  20612. key(key),
  20613. value(value)
  20614. {
  20615. }
  20616. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20617. //////////////////// QCPBars
  20618. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20619. /*! \class QCPBars
  20620. \brief A plottable representing a bar chart in a plot.
  20621. \image html QCPBars.png
  20622. To plot data, assign it with the \ref setData or \ref addData functions.
  20623. \section qcpbars-appearance Changing the appearance
  20624. The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush).
  20625. The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth.
  20626. Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other
  20627. (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear
  20628. stacked.
  20629. If you would like to group multiple QCPBars plottables together so they appear side by side as
  20630. shown below, use QCPBarsGroup.
  20631. \image html QCPBarsGroup.png
  20632. \section qcpbars-usage Usage
  20633. Like all data representing objects in QCustomPlot, the QCPBars is a plottable
  20634. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  20635. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  20636. Usually, you first create an instance:
  20637. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-1
  20638. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  20639. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  20640. The newly created plottable can be modified, e.g.:
  20641. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-creation-2
  20642. */
  20643. /* start of documentation of inline functions */
  20644. /*! \fn QSharedPointer<QCPBarsDataContainer> QCPBars::data() const
  20645. Returns a shared pointer to the internal data storage of type \ref QCPBarsDataContainer. You may
  20646. use it to directly manipulate the data, which may be more convenient and faster than using the
  20647. regular \ref setData or \ref addData methods.
  20648. */
  20649. /*! \fn QCPBars *QCPBars::barBelow() const
  20650. Returns the bars plottable that is directly below this bars plottable.
  20651. If there is no such plottable, returns \c nullptr.
  20652. \see barAbove, moveBelow, moveAbove
  20653. */
  20654. /*! \fn QCPBars *QCPBars::barAbove() const
  20655. Returns the bars plottable that is directly above this bars plottable.
  20656. If there is no such plottable, returns \c nullptr.
  20657. \see barBelow, moveBelow, moveAbove
  20658. */
  20659. /* end of documentation of inline functions */
  20660. /*!
  20661. Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  20662. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  20663. the same orientation. If either of these restrictions is violated, a corresponding message is
  20664. printed to the debug output (qDebug), the construction is not aborted, though.
  20665. The created QCPBars is automatically registered with the QCustomPlot instance inferred from \a
  20666. keyAxis. This QCustomPlot instance takes ownership of the QCPBars, so do not delete it manually
  20667. but use QCustomPlot::removePlottable() instead.
  20668. */
  20669. QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  20670. QCPAbstractPlottable1D<QCPBarsData>(keyAxis, valueAxis),
  20671. mWidth(0.75),
  20672. mWidthType(wtPlotCoords),
  20673. mBarsGroup(nullptr),
  20674. mBaseValue(0),
  20675. mStackingGap(1)
  20676. {
  20677. // modify inherited properties from abstract plottable:
  20678. mPen.setColor(Qt::blue);
  20679. mPen.setStyle(Qt::SolidLine);
  20680. mBrush.setColor(QColor(40, 50, 255, 30));
  20681. mBrush.setStyle(Qt::SolidPattern);
  20682. mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
  20683. }
  20684. QCPBars::~QCPBars()
  20685. {
  20686. setBarsGroup(nullptr);
  20687. if (mBarBelow || mBarAbove)
  20688. connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking
  20689. }
  20690. /*! \overload
  20691. Replaces the current data container with the provided \a data container.
  20692. Since a QSharedPointer is used, multiple QCPBars may share the same data container safely.
  20693. Modifying the data in the container will then affect all bars that share the container. Sharing
  20694. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  20695. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-1
  20696. If you do not wish to share containers, but create a copy from an existing container, rather use
  20697. the \ref QCPDataContainer<DataType>::set method on the bar's data container directly:
  20698. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpbars-datasharing-2
  20699. \see addData
  20700. */
  20701. void QCPBars::setData(QSharedPointer<QCPBarsDataContainer> data)
  20702. {
  20703. mDataContainer = data;
  20704. }
  20705. /*! \overload
  20706. Replaces the current data with the provided points in \a keys and \a values. The provided
  20707. vectors should have equal length. Else, the number of added points will be the size of the
  20708. smallest vector.
  20709. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  20710. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  20711. \see addData
  20712. */
  20713. void QCPBars::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  20714. {
  20715. mDataContainer->clear();
  20716. addData(keys, values, alreadySorted);
  20717. }
  20718. /*!
  20719. Sets the width of the bars.
  20720. How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...),
  20721. depends on the currently set width type, see \ref setWidthType and \ref WidthType.
  20722. */
  20723. void QCPBars::setWidth(double width)
  20724. {
  20725. mWidth = width;
  20726. }
  20727. /*!
  20728. Sets how the width of the bars is defined. See the documentation of \ref WidthType for an
  20729. explanation of the possible values for \a widthType.
  20730. The default value is \ref wtPlotCoords.
  20731. \see setWidth
  20732. */
  20733. void QCPBars::setWidthType(QCPBars::WidthType widthType)
  20734. {
  20735. mWidthType = widthType;
  20736. }
  20737. /*!
  20738. Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref
  20739. QCPBarsGroup::append.
  20740. To remove this QCPBars from any group, set \a barsGroup to \c nullptr.
  20741. */
  20742. void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup)
  20743. {
  20744. // deregister at old group:
  20745. if (mBarsGroup)
  20746. mBarsGroup->unregisterBars(this);
  20747. mBarsGroup = barsGroup;
  20748. // register at new group:
  20749. if (mBarsGroup)
  20750. mBarsGroup->registerBars(this);
  20751. }
  20752. /*!
  20753. Sets the base value of this bars plottable.
  20754. The base value defines where on the value coordinate the bars start. How far the bars extend from
  20755. the base value is given by their individual value data. For example, if the base value is set to
  20756. 1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at
  20757. 3.
  20758. For stacked bars, only the base value of the bottom-most QCPBars has meaning.
  20759. The default base value is 0.
  20760. */
  20761. void QCPBars::setBaseValue(double baseValue)
  20762. {
  20763. mBaseValue = baseValue;
  20764. }
  20765. /*!
  20766. If this bars plottable is stacked on top of another bars plottable (\ref moveAbove), this method
  20767. allows specifying a distance in \a pixels, by which the drawn bar rectangles will be separated by
  20768. the bars below it.
  20769. */
  20770. void QCPBars::setStackingGap(double pixels)
  20771. {
  20772. mStackingGap = pixels;
  20773. }
  20774. /*! \overload
  20775. Adds the provided points in \a keys and \a values to the current data. The provided vectors
  20776. should have equal length. Else, the number of added points will be the size of the smallest
  20777. vector.
  20778. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  20779. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  20780. Alternatively, you can also access and modify the data directly via the \ref data method, which
  20781. returns a pointer to the internal data container.
  20782. */
  20783. void QCPBars::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  20784. {
  20785. if (keys.size() != values.size())
  20786. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  20787. const int n = qMin(keys.size(), values.size());
  20788. QVector<QCPBarsData> tempData(n);
  20789. QVector<QCPBarsData>::iterator it = tempData.begin();
  20790. const QVector<QCPBarsData>::iterator itEnd = tempData.end();
  20791. int i = 0;
  20792. while (it != itEnd)
  20793. {
  20794. it->key = keys[i];
  20795. it->value = values[i];
  20796. ++it;
  20797. ++i;
  20798. }
  20799. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  20800. }
  20801. /*! \overload
  20802. Adds the provided data point as \a key and \a value to the current data.
  20803. Alternatively, you can also access and modify the data directly via the \ref data method, which
  20804. returns a pointer to the internal data container.
  20805. */
  20806. void QCPBars::addData(double key, double value)
  20807. {
  20808. mDataContainer->add(QCPBarsData(key, value));
  20809. }
  20810. /*!
  20811. Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear
  20812. below the bars of \a bars. The move target \a bars must use the same key and value axis as this
  20813. plottable.
  20814. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  20815. has a bars object below itself, this bars object is inserted between the two. If this bars object
  20816. is already between two other bars, the two other bars will be stacked on top of each other after
  20817. the operation.
  20818. To remove this bars plottable from any stacking, set \a bars to \c nullptr.
  20819. \see moveBelow, barAbove, barBelow
  20820. */
  20821. void QCPBars::moveBelow(QCPBars *bars)
  20822. {
  20823. if (bars == this) return;
  20824. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
  20825. {
  20826. qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  20827. return;
  20828. }
  20829. // remove from stacking:
  20830. connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
  20831. // if new bar given, insert this bar below it:
  20832. if (bars)
  20833. {
  20834. if (bars->mBarBelow)
  20835. connectBars(bars->mBarBelow.data(), this);
  20836. connectBars(this, bars);
  20837. }
  20838. }
  20839. /*!
  20840. Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear
  20841. above the bars of \a bars. The move target \a bars must use the same key and value axis as this
  20842. plottable.
  20843. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already
  20844. has a bars object above itself, this bars object is inserted between the two. If this bars object
  20845. is already between two other bars, the two other bars will be stacked on top of each other after
  20846. the operation.
  20847. To remove this bars plottable from any stacking, set \a bars to \c nullptr.
  20848. \see moveBelow, barBelow, barAbove
  20849. */
  20850. void QCPBars::moveAbove(QCPBars *bars)
  20851. {
  20852. if (bars == this) return;
  20853. if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data()))
  20854. {
  20855. qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars";
  20856. return;
  20857. }
  20858. // remove from stacking:
  20859. connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0
  20860. // if new bar given, insert this bar above it:
  20861. if (bars)
  20862. {
  20863. if (bars->mBarAbove)
  20864. connectBars(this, bars->mBarAbove.data());
  20865. connectBars(bars, this);
  20866. }
  20867. }
  20868. /*!
  20869. \copydoc QCPPlottableInterface1D::selectTestRect
  20870. */
  20871. QCPDataSelection QCPBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
  20872. {
  20873. QCPDataSelection result;
  20874. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  20875. return result;
  20876. if (!mKeyAxis || !mValueAxis)
  20877. return result;
  20878. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  20879. getVisibleDataBounds(visibleBegin, visibleEnd);
  20880. for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  20881. {
  20882. if (rect.intersects(getBarRect(it->key, it->value)))
  20883. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  20884. }
  20885. result.simplify();
  20886. return result;
  20887. }
  20888. /*!
  20889. Implements a selectTest specific to this plottable's point geometry.
  20890. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  20891. point to \a pos.
  20892. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  20893. */
  20894. double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  20895. {
  20896. Q_UNUSED(details)
  20897. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  20898. return -1;
  20899. if (!mKeyAxis || !mValueAxis)
  20900. return -1;
  20901. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  20902. {
  20903. // get visible data range:
  20904. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  20905. getVisibleDataBounds(visibleBegin, visibleEnd);
  20906. for (QCPBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  20907. {
  20908. if (getBarRect(it->key, it->value).contains(pos))
  20909. {
  20910. if (details)
  20911. {
  20912. int pointIndex = int(it-mDataContainer->constBegin());
  20913. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  20914. }
  20915. return mParentPlot->selectionTolerance()*0.99;
  20916. }
  20917. }
  20918. }
  20919. return -1;
  20920. }
  20921. /* inherits documentation from base class */
  20922. QCPRange QCPBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  20923. {
  20924. /* Note: If this QCPBars uses absolute pixels as width (or is in a QCPBarsGroup with spacing in
  20925. absolute pixels), using this method to adapt the key axis range to fit the bars into the
  20926. currently visible axis range will not work perfectly. Because in the moment the axis range is
  20927. changed to the new range, the fixed pixel widths/spacings will represent different coordinate
  20928. spans than before, which in turn would require a different key range to perfectly fit, and so on.
  20929. The only solution would be to iteratively approach the perfect fitting axis range, but the
  20930. mismatch isn't large enough in most applications, to warrant this here. If a user does need a
  20931. better fit, he should call the corresponding axis rescale multiple times in a row.
  20932. */
  20933. QCPRange range;
  20934. range = mDataContainer->keyRange(foundRange, inSignDomain);
  20935. // determine exact range of bars by including bar width and barsgroup offset:
  20936. if (foundRange && mKeyAxis)
  20937. {
  20938. double lowerPixelWidth, upperPixelWidth, keyPixel;
  20939. // lower range bound:
  20940. getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth);
  20941. keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth;
  20942. if (mBarsGroup)
  20943. keyPixel += mBarsGroup->keyPixelOffset(this, range.lower);
  20944. const double lowerCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
  20945. if (!qIsNaN(lowerCorrected) && qIsFinite(lowerCorrected) && range.lower > lowerCorrected)
  20946. range.lower = lowerCorrected;
  20947. // upper range bound:
  20948. getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth);
  20949. keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth;
  20950. if (mBarsGroup)
  20951. keyPixel += mBarsGroup->keyPixelOffset(this, range.upper);
  20952. const double upperCorrected = mKeyAxis.data()->pixelToCoord(keyPixel);
  20953. if (!qIsNaN(upperCorrected) && qIsFinite(upperCorrected) && range.upper < upperCorrected)
  20954. range.upper = upperCorrected;
  20955. }
  20956. return range;
  20957. }
  20958. /* inherits documentation from base class */
  20959. QCPRange QCPBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  20960. {
  20961. // Note: can't simply use mDataContainer->valueRange here because we need to
  20962. // take into account bar base value and possible stacking of multiple bars
  20963. QCPRange range;
  20964. range.lower = mBaseValue;
  20965. range.upper = mBaseValue;
  20966. bool haveLower = true; // set to true, because baseValue should always be visible in bar charts
  20967. bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts
  20968. QCPBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  20969. QCPBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  20970. if (inKeyRange != QCPRange())
  20971. {
  20972. itBegin = mDataContainer->findBegin(inKeyRange.lower, false);
  20973. itEnd = mDataContainer->findEnd(inKeyRange.upper, false);
  20974. }
  20975. for (QCPBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
  20976. {
  20977. const double current = it->value + getStackedBaseValue(it->key, it->value >= 0);
  20978. if (qIsNaN(current)) continue;
  20979. if (inSignDomain == QCP::SignDomain::sdBoth || (inSignDomain == QCP::SignDomain::sdNegative && current < 0) || (inSignDomain == QCP::SignDomain::sdPositive && current > 0))
  20980. {
  20981. if (current < range.lower || !haveLower)
  20982. {
  20983. range.lower = current;
  20984. haveLower = true;
  20985. }
  20986. if (current > range.upper || !haveUpper)
  20987. {
  20988. range.upper = current;
  20989. haveUpper = true;
  20990. }
  20991. }
  20992. }
  20993. foundRange = true; // return true because bar charts always have the 0-line visible
  20994. return range;
  20995. }
  20996. /* inherits documentation from base class */
  20997. QPointF QCPBars::dataPixelPosition(int index) const
  20998. {
  20999. if (index >= 0 && index < mDataContainer->size())
  21000. {
  21001. QCPAxis *keyAxis = mKeyAxis.data();
  21002. QCPAxis *valueAxis = mValueAxis.data();
  21003. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  21004. const QCPDataContainer<QCPBarsData>::const_iterator it = mDataContainer->constBegin()+index;
  21005. const double valuePixel = valueAxis->coordToPixel(getStackedBaseValue(it->key, it->value >= 0) + it->value);
  21006. const double keyPixel = keyAxis->coordToPixel(it->key) + (mBarsGroup ? mBarsGroup->keyPixelOffset(this, it->key) : 0);
  21007. if (keyAxis->orientation() == Qt::Horizontal)
  21008. return {keyPixel, valuePixel};
  21009. else
  21010. return {valuePixel, keyPixel};
  21011. } else
  21012. {
  21013. qDebug() << Q_FUNC_INFO << "Index out of bounds" << index;
  21014. return {};
  21015. }
  21016. }
  21017. /* inherits documentation from base class */
  21018. void QCPBars::draw(QCPPainter *painter)
  21019. {
  21020. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  21021. if (mDataContainer->isEmpty()) return;
  21022. QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  21023. getVisibleDataBounds(visibleBegin, visibleEnd);
  21024. // loop over and draw segments of unselected/selected data:
  21025. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  21026. getDataSegments(selectedSegments, unselectedSegments);
  21027. allSegments << unselectedSegments << selectedSegments;
  21028. for (int i=0; i<allSegments.size(); ++i)
  21029. {
  21030. bool isSelectedSegment = i >= unselectedSegments.size();
  21031. QCPBarsDataContainer::const_iterator begin = visibleBegin;
  21032. QCPBarsDataContainer::const_iterator end = visibleEnd;
  21033. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  21034. if (begin == end)
  21035. continue;
  21036. for (QCPBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  21037. {
  21038. // check data validity if flag set:
  21039. #ifdef QCUSTOMPLOT_CHECK_DATA
  21040. if (QCP::isInvalidData(it->key, it->value))
  21041. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
  21042. #endif
  21043. // draw bar:
  21044. if (isSelectedSegment && mSelectionDecorator)
  21045. {
  21046. mSelectionDecorator->applyBrush(painter);
  21047. mSelectionDecorator->applyPen(painter);
  21048. } else
  21049. {
  21050. painter->setBrush(mBrush);
  21051. painter->setPen(mPen);
  21052. }
  21053. applyDefaultAntialiasingHint(painter);
  21054. painter->drawPolygon(getBarRect(it->key, it->value));
  21055. }
  21056. }
  21057. // draw other selection decoration that isn't just line/scatter pens and brushes:
  21058. if (mSelectionDecorator)
  21059. mSelectionDecorator->drawDecoration(painter, selection());
  21060. }
  21061. /* inherits documentation from base class */
  21062. void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  21063. {
  21064. // draw filled rect:
  21065. applyDefaultAntialiasingHint(painter);
  21066. painter->setBrush(mBrush);
  21067. painter->setPen(mPen);
  21068. QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
  21069. r.moveCenter(rect.center());
  21070. painter->drawRect(r);
  21071. }
  21072. /*! \internal
  21073. called by \ref draw to determine which data (key) range is visible at the current key axis range
  21074. setting, so only that needs to be processed. It also takes into account the bar width.
  21075. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  21076. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  21077. lower may still be just outside the visible range.
  21078. \a end returns an iterator one higher than the highest visible data point. Same as before, \a end
  21079. may also lie just outside of the visible range.
  21080. if the plottable contains no data, both \a begin and \a end point to constEnd.
  21081. */
  21082. void QCPBars::getVisibleDataBounds(QCPBarsDataContainer::const_iterator &begin, QCPBarsDataContainer::const_iterator &end) const
  21083. {
  21084. if (!mKeyAxis)
  21085. {
  21086. qDebug() << Q_FUNC_INFO << "invalid key axis";
  21087. begin = mDataContainer->constEnd();
  21088. end = mDataContainer->constEnd();
  21089. return;
  21090. }
  21091. if (mDataContainer->isEmpty())
  21092. {
  21093. begin = mDataContainer->constEnd();
  21094. end = mDataContainer->constEnd();
  21095. return;
  21096. }
  21097. // get visible data range as QMap iterators
  21098. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower);
  21099. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper);
  21100. double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower);
  21101. double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper);
  21102. bool isVisible = false;
  21103. // walk left from begin to find lower bar that actually is completely outside visible pixel range:
  21104. QCPBarsDataContainer::const_iterator it = begin;
  21105. while (it != mDataContainer->constBegin())
  21106. {
  21107. --it;
  21108. const QRectF barRect = getBarRect(it->key, it->value);
  21109. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  21110. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.left() <= lowerPixelBound));
  21111. else // keyaxis is vertical
  21112. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.bottom() >= lowerPixelBound));
  21113. if (isVisible)
  21114. begin = it;
  21115. else
  21116. break;
  21117. }
  21118. // walk right from ubound to find upper bar that actually is completely outside visible pixel range:
  21119. it = end;
  21120. while (it != mDataContainer->constEnd())
  21121. {
  21122. const QRectF barRect = getBarRect(it->key, it->value);
  21123. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  21124. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.right() >= upperPixelBound));
  21125. else // keyaxis is vertical
  21126. isVisible = ((!mKeyAxis.data()->rangeReversed() && barRect.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barRect.top() <= upperPixelBound));
  21127. if (isVisible)
  21128. end = it+1;
  21129. else
  21130. break;
  21131. ++it;
  21132. }
  21133. }
  21134. /*! \internal
  21135. Returns the rect in pixel coordinates of a single bar with the specified \a key and \a value. The
  21136. rect is shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref
  21137. setBaseValue), and to have non-overlapping border lines with the bars stacked below.
  21138. */
  21139. QRectF QCPBars::getBarRect(double key, double value) const
  21140. {
  21141. QCPAxis *keyAxis = mKeyAxis.data();
  21142. QCPAxis *valueAxis = mValueAxis.data();
  21143. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  21144. double lowerPixelWidth, upperPixelWidth;
  21145. getPixelWidth(key, lowerPixelWidth, upperPixelWidth);
  21146. double base = getStackedBaseValue(key, value >= 0);
  21147. double basePixel = valueAxis->coordToPixel(base);
  21148. double valuePixel = valueAxis->coordToPixel(base+value);
  21149. double keyPixel = keyAxis->coordToPixel(key);
  21150. if (mBarsGroup)
  21151. keyPixel += mBarsGroup->keyPixelOffset(this, key);
  21152. double bottomOffset = (mBarBelow && mPen != Qt::NoPen ? 1 : 0)*(mPen.isCosmetic() ? 1 : mPen.widthF());
  21153. bottomOffset += mBarBelow ? mStackingGap : 0;
  21154. bottomOffset *= (value<0 ? -1 : 1)*valueAxis->pixelOrientation();
  21155. if (qAbs(valuePixel-basePixel) <= qAbs(bottomOffset))
  21156. bottomOffset = valuePixel-basePixel;
  21157. if (keyAxis->orientation() == Qt::Horizontal)
  21158. {
  21159. return QRectF(QPointF(keyPixel+lowerPixelWidth, valuePixel), QPointF(keyPixel+upperPixelWidth, basePixel+bottomOffset)).normalized();
  21160. } else
  21161. {
  21162. return QRectF(QPointF(basePixel+bottomOffset, keyPixel+lowerPixelWidth), QPointF(valuePixel, keyPixel+upperPixelWidth)).normalized();
  21163. }
  21164. }
  21165. /*! \internal
  21166. This function is used to determine the width of the bar at coordinate \a key, according to the
  21167. specified width (\ref setWidth) and width type (\ref setWidthType).
  21168. The output parameters \a lower and \a upper return the number of pixels the bar extends to lower
  21169. and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a
  21170. lower is negative and \a upper positive).
  21171. */
  21172. void QCPBars::getPixelWidth(double key, double &lower, double &upper) const
  21173. {
  21174. lower = 0;
  21175. upper = 0;
  21176. switch (mWidthType)
  21177. {
  21178. case wtAbsolute:
  21179. {
  21180. upper = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  21181. lower = -upper;
  21182. break;
  21183. }
  21184. case wtAxisRectRatio:
  21185. {
  21186. if (mKeyAxis && mKeyAxis.data()->axisRect())
  21187. {
  21188. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  21189. upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  21190. else
  21191. upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  21192. lower = -upper;
  21193. } else
  21194. qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
  21195. break;
  21196. }
  21197. case wtPlotCoords:
  21198. {
  21199. if (mKeyAxis)
  21200. {
  21201. double keyPixel = mKeyAxis.data()->coordToPixel(key);
  21202. upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
  21203. lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel;
  21204. // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by
  21205. // coordinate transform which includes range direction
  21206. } else
  21207. qDebug() << Q_FUNC_INFO << "No key axis defined";
  21208. break;
  21209. }
  21210. }
  21211. }
  21212. /*! \internal
  21213. This function is called to find at which value to start drawing the base of a bar at \a key, when
  21214. it is stacked on top of another QCPBars (e.g. with \ref moveAbove).
  21215. positive and negative bars are separated per stack (positive are stacked above baseValue upwards,
  21216. negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the
  21217. bar for which we need the base value is negative, set \a positive to false.
  21218. */
  21219. double QCPBars::getStackedBaseValue(double key, bool positive) const
  21220. {
  21221. if (mBarBelow)
  21222. {
  21223. double max = 0; // don't initialize with mBaseValue here because only base value of bottom-most bar has meaning in a bar stack
  21224. // find bars of mBarBelow that are approximately at key and find largest one:
  21225. double epsilon = qAbs(key)*(sizeof(key)==4 ? 1e-6 : 1e-14); // should be safe even when changed to use float at some point
  21226. if (key == 0)
  21227. epsilon = (sizeof(key)==4 ? 1e-6 : 1e-14);
  21228. QCPBarsDataContainer::const_iterator it = mBarBelow.data()->mDataContainer->findBegin(key-epsilon);
  21229. QCPBarsDataContainer::const_iterator itEnd = mBarBelow.data()->mDataContainer->findEnd(key+epsilon);
  21230. while (it != itEnd)
  21231. {
  21232. if (it->key > key-epsilon && it->key < key+epsilon)
  21233. {
  21234. if ((positive && it->value > max) ||
  21235. (!positive && it->value < max))
  21236. max = it->value;
  21237. }
  21238. ++it;
  21239. }
  21240. // recurse down the bar-stack to find the total height:
  21241. return max + mBarBelow.data()->getStackedBaseValue(key, positive);
  21242. } else
  21243. return mBaseValue;
  21244. }
  21245. /*! \internal
  21246. Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s)
  21247. currently above lower and below upper will become disconnected to lower/upper.
  21248. If lower is zero, upper will be disconnected at the bottom.
  21249. If upper is zero, lower will be disconnected at the top.
  21250. */
  21251. void QCPBars::connectBars(QCPBars *lower, QCPBars *upper)
  21252. {
  21253. if (!lower && !upper) return;
  21254. if (!lower) // disconnect upper at bottom
  21255. {
  21256. // disconnect old bar below upper:
  21257. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  21258. upper->mBarBelow.data()->mBarAbove = nullptr;
  21259. upper->mBarBelow = nullptr;
  21260. } else if (!upper) // disconnect lower at top
  21261. {
  21262. // disconnect old bar above lower:
  21263. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  21264. lower->mBarAbove.data()->mBarBelow = nullptr;
  21265. lower->mBarAbove = nullptr;
  21266. } else // connect lower and upper
  21267. {
  21268. // disconnect old bar above lower:
  21269. if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower)
  21270. lower->mBarAbove.data()->mBarBelow = nullptr;
  21271. // disconnect old bar below upper:
  21272. if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper)
  21273. upper->mBarBelow.data()->mBarAbove = nullptr;
  21274. lower->mBarAbove = upper;
  21275. upper->mBarBelow = lower;
  21276. }
  21277. }
  21278. /* end of 'src/plottables/plottable-bars.cpp' */
  21279. /* including file 'src/plottables/plottable-statisticalbox.cpp' */
  21280. /* modified 2021-03-29T02:30:44, size 28951 */
  21281. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21282. //////////////////// QCPStatisticalBoxData
  21283. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21284. /*! \class QCPStatisticalBoxData
  21285. \brief Holds the data of one single data point for QCPStatisticalBox.
  21286. The stored data is:
  21287. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  21288. \li \a minimum: the position of the lower whisker, typically the minimum measurement of the
  21289. sample that's not considered an outlier.
  21290. \li \a lowerQuartile: the lower end of the box. The lower and the upper quartiles are the two
  21291. statistical quartiles around the median of the sample, they should contain 50% of the sample
  21292. data.
  21293. \li \a median: the value of the median mark inside the quartile box. The median separates the
  21294. sample data in half (50% of the sample data is below/above the median). (This is the \a mainValue)
  21295. \li \a upperQuartile: the upper end of the box. The lower and the upper quartiles are the two
  21296. statistical quartiles around the median of the sample, they should contain 50% of the sample
  21297. data.
  21298. \li \a maximum: the position of the upper whisker, typically the maximum measurement of the
  21299. sample that's not considered an outlier.
  21300. \li \a outliers: a QVector of outlier values that will be drawn as scatter points at the \a key
  21301. coordinate of this data point (see \ref QCPStatisticalBox::setOutlierStyle)
  21302. The container for storing multiple data points is \ref QCPStatisticalBoxDataContainer. It is a
  21303. typedef for \ref QCPDataContainer with \ref QCPStatisticalBoxData as the DataType template
  21304. parameter. See the documentation there for an explanation regarding the data type's generic
  21305. methods.
  21306. \see QCPStatisticalBoxDataContainer
  21307. */
  21308. /* start documentation of inline functions */
  21309. /*! \fn double QCPStatisticalBoxData::sortKey() const
  21310. Returns the \a key member of this data point.
  21311. For a general explanation of what this method is good for in the context of the data container,
  21312. see the documentation of \ref QCPDataContainer.
  21313. */
  21314. /*! \fn static QCPStatisticalBoxData QCPStatisticalBoxData::fromSortKey(double sortKey)
  21315. Returns a data point with the specified \a sortKey. All other members are set to zero.
  21316. For a general explanation of what this method is good for in the context of the data container,
  21317. see the documentation of \ref QCPDataContainer.
  21318. */
  21319. /*! \fn static static bool QCPStatisticalBoxData::sortKeyIsMainKey()
  21320. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  21321. this method returns true.
  21322. For a general explanation of what this method is good for in the context of the data container,
  21323. see the documentation of \ref QCPDataContainer.
  21324. */
  21325. /*! \fn double QCPStatisticalBoxData::mainKey() const
  21326. Returns the \a key member of this data point.
  21327. For a general explanation of what this method is good for in the context of the data container,
  21328. see the documentation of \ref QCPDataContainer.
  21329. */
  21330. /*! \fn double QCPStatisticalBoxData::mainValue() const
  21331. Returns the \a median member of this data point.
  21332. For a general explanation of what this method is good for in the context of the data container,
  21333. see the documentation of \ref QCPDataContainer.
  21334. */
  21335. /*! \fn QCPRange QCPStatisticalBoxData::valueRange() const
  21336. Returns a QCPRange spanning from the \a minimum to the \a maximum member of this statistical box
  21337. data point, possibly further expanded by outliers.
  21338. For a general explanation of what this method is good for in the context of the data container,
  21339. see the documentation of \ref QCPDataContainer.
  21340. */
  21341. /* end documentation of inline functions */
  21342. /*!
  21343. Constructs a data point with key and all values set to zero.
  21344. */
  21345. QCPStatisticalBoxData::QCPStatisticalBoxData() :
  21346. key(0),
  21347. minimum(0),
  21348. lowerQuartile(0),
  21349. median(0),
  21350. upperQuartile(0),
  21351. maximum(0)
  21352. {
  21353. }
  21354. /*!
  21355. Constructs a data point with the specified \a key, \a minimum, \a lowerQuartile, \a median, \a
  21356. upperQuartile, \a maximum and optionally a number of \a outliers.
  21357. */
  21358. QCPStatisticalBoxData::QCPStatisticalBoxData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers) :
  21359. key(key),
  21360. minimum(minimum),
  21361. lowerQuartile(lowerQuartile),
  21362. median(median),
  21363. upperQuartile(upperQuartile),
  21364. maximum(maximum),
  21365. outliers(outliers)
  21366. {
  21367. }
  21368. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21369. //////////////////// QCPStatisticalBox
  21370. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21371. /*! \class QCPStatisticalBox
  21372. \brief A plottable representing a single statistical box in a plot.
  21373. \image html QCPStatisticalBox.png
  21374. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can
  21375. also access and modify the data via the \ref data method, which returns a pointer to the internal
  21376. \ref QCPStatisticalBoxDataContainer.
  21377. Additionally each data point can itself have a list of outliers, drawn as scatter points at the
  21378. key coordinate of the respective statistical box data point. They can either be set by using the
  21379. respective \ref addData(double,double,double,double,double,double,const QVector<double>&)
  21380. "addData" method or accessing the individual data points through \ref data, and setting the
  21381. <tt>QVector<double> outliers</tt> of the data points directly.
  21382. \section qcpstatisticalbox-appearance Changing the appearance
  21383. The appearance of each data point box, ranging from the lower to the upper quartile, is
  21384. controlled via \ref setPen and \ref setBrush. You may change the width of the boxes with \ref
  21385. setWidth in plot coordinates.
  21386. Each data point's visual representation also consists of two whiskers. Whiskers are the lines
  21387. which reach from the upper quartile to the maximum, and from the lower quartile to the minimum.
  21388. The appearance of the whiskers can be modified with: \ref setWhiskerPen, \ref setWhiskerBarPen,
  21389. \ref setWhiskerWidth. The whisker width is the width of the bar perpendicular to the whisker at
  21390. the top (for maximum) and bottom (for minimum). If the whisker pen is changed, make sure to set
  21391. the \c capStyle to \c Qt::FlatCap. Otherwise the backbone line might exceed the whisker bars by a
  21392. few pixels due to the pen cap being not perfectly flat.
  21393. The median indicator line inside the box has its own pen, \ref setMedianPen.
  21394. The outlier data points are drawn as normal scatter points. Their look can be controlled with
  21395. \ref setOutlierStyle
  21396. \section qcpstatisticalbox-usage Usage
  21397. Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable
  21398. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  21399. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  21400. Usually, you first create an instance:
  21401. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-1
  21402. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  21403. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  21404. The newly created plottable can be modified, e.g.:
  21405. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-creation-2
  21406. */
  21407. /* start documentation of inline functions */
  21408. /*! \fn QSharedPointer<QCPStatisticalBoxDataContainer> QCPStatisticalBox::data() const
  21409. Returns a shared pointer to the internal data storage of type \ref
  21410. QCPStatisticalBoxDataContainer. You may use it to directly manipulate the data, which may be more
  21411. convenient and faster than using the regular \ref setData or \ref addData methods.
  21412. */
  21413. /* end documentation of inline functions */
  21414. /*!
  21415. Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its
  21416. value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and
  21417. not have the same orientation. If either of these restrictions is violated, a corresponding
  21418. message is printed to the debug output (qDebug), the construction is not aborted, though.
  21419. The created QCPStatisticalBox is automatically registered with the QCustomPlot instance inferred
  21420. from \a keyAxis. This QCustomPlot instance takes ownership of the QCPStatisticalBox, so do not
  21421. delete it manually but use QCustomPlot::removePlottable() instead.
  21422. */
  21423. QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  21424. QCPAbstractPlottable1D<QCPStatisticalBoxData>(keyAxis, valueAxis),
  21425. mWidth(0.5),
  21426. mWhiskerWidth(0.2),
  21427. mWhiskerPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap),
  21428. mWhiskerBarPen(Qt::black),
  21429. mWhiskerAntialiased(false),
  21430. mMedianPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap),
  21431. mOutlierStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)
  21432. {
  21433. setPen(QPen(Qt::black));
  21434. setBrush(Qt::NoBrush);
  21435. }
  21436. /*! \overload
  21437. Replaces the current data container with the provided \a data container.
  21438. Since a QSharedPointer is used, multiple QCPStatisticalBoxes may share the same data container
  21439. safely. Modifying the data in the container will then affect all statistical boxes that share the
  21440. container. Sharing can be achieved by simply exchanging the data containers wrapped in shared
  21441. pointers:
  21442. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-1
  21443. If you do not wish to share containers, but create a copy from an existing container, rather use
  21444. the \ref QCPDataContainer<DataType>::set method on the statistical box data container directly:
  21445. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpstatisticalbox-datasharing-2
  21446. \see addData
  21447. */
  21448. void QCPStatisticalBox::setData(QSharedPointer<QCPStatisticalBoxDataContainer> data)
  21449. {
  21450. mDataContainer = data;
  21451. }
  21452. /*! \overload
  21453. Replaces the current data with the provided points in \a keys, \a minimum, \a lowerQuartile, \a
  21454. median, \a upperQuartile and \a maximum. The provided vectors should have equal length. Else, the
  21455. number of added points will be the size of the smallest vector.
  21456. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  21457. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  21458. \see addData
  21459. */
  21460. 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)
  21461. {
  21462. mDataContainer->clear();
  21463. addData(keys, minimum, lowerQuartile, median, upperQuartile, maximum, alreadySorted);
  21464. }
  21465. /*!
  21466. Sets the width of the boxes in key coordinates.
  21467. \see setWhiskerWidth
  21468. */
  21469. void QCPStatisticalBox::setWidth(double width)
  21470. {
  21471. mWidth = width;
  21472. }
  21473. /*!
  21474. Sets the width of the whiskers in key coordinates.
  21475. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  21476. quartile to the minimum.
  21477. \see setWidth
  21478. */
  21479. void QCPStatisticalBox::setWhiskerWidth(double width)
  21480. {
  21481. mWhiskerWidth = width;
  21482. }
  21483. /*!
  21484. Sets the pen used for drawing the whisker backbone.
  21485. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  21486. quartile to the minimum.
  21487. Make sure to set the \c capStyle of the passed \a pen to \c Qt::FlatCap. Otherwise the backbone
  21488. line might exceed the whisker bars by a few pixels due to the pen cap being not perfectly flat.
  21489. \see setWhiskerBarPen
  21490. */
  21491. void QCPStatisticalBox::setWhiskerPen(const QPen &pen)
  21492. {
  21493. mWhiskerPen = pen;
  21494. }
  21495. /*!
  21496. Sets the pen used for drawing the whisker bars. Those are the lines parallel to the key axis at
  21497. each end of the whisker backbone.
  21498. Whiskers are the lines which reach from the upper quartile to the maximum, and from the lower
  21499. quartile to the minimum.
  21500. \see setWhiskerPen
  21501. */
  21502. void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen)
  21503. {
  21504. mWhiskerBarPen = pen;
  21505. }
  21506. /*!
  21507. Sets whether the statistical boxes whiskers are drawn with antialiasing or not.
  21508. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and
  21509. QCustomPlot::setNotAntialiasedElements.
  21510. */
  21511. void QCPStatisticalBox::setWhiskerAntialiased(bool enabled)
  21512. {
  21513. mWhiskerAntialiased = enabled;
  21514. }
  21515. /*!
  21516. Sets the pen used for drawing the median indicator line inside the statistical boxes.
  21517. */
  21518. void QCPStatisticalBox::setMedianPen(const QPen &pen)
  21519. {
  21520. mMedianPen = pen;
  21521. }
  21522. /*!
  21523. Sets the appearance of the outlier data points.
  21524. Outliers can be specified with the method
  21525. \ref addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
  21526. */
  21527. void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style)
  21528. {
  21529. mOutlierStyle = style;
  21530. }
  21531. /*! \overload
  21532. Adds the provided points in \a keys, \a minimum, \a lowerQuartile, \a median, \a upperQuartile and
  21533. \a maximum to the current data. The provided vectors should have equal length. Else, the number
  21534. of added points will be the size of the smallest vector.
  21535. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  21536. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  21537. Alternatively, you can also access and modify the data directly via the \ref data method, which
  21538. returns a pointer to the internal data container.
  21539. */
  21540. 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)
  21541. {
  21542. if (keys.size() != minimum.size() || minimum.size() != lowerQuartile.size() || lowerQuartile.size() != median.size() ||
  21543. median.size() != upperQuartile.size() || upperQuartile.size() != maximum.size() || maximum.size() != keys.size())
  21544. qDebug() << Q_FUNC_INFO << "keys, minimum, lowerQuartile, median, upperQuartile, maximum have different sizes:"
  21545. << keys.size() << minimum.size() << lowerQuartile.size() << median.size() << upperQuartile.size() << maximum.size();
  21546. const int n = qMin(keys.size(), qMin(minimum.size(), qMin(lowerQuartile.size(), qMin(median.size(), qMin(upperQuartile.size(), maximum.size())))));
  21547. QVector<QCPStatisticalBoxData> tempData(n);
  21548. QVector<QCPStatisticalBoxData>::iterator it = tempData.begin();
  21549. const QVector<QCPStatisticalBoxData>::iterator itEnd = tempData.end();
  21550. int i = 0;
  21551. while (it != itEnd)
  21552. {
  21553. it->key = keys[i];
  21554. it->minimum = minimum[i];
  21555. it->lowerQuartile = lowerQuartile[i];
  21556. it->median = median[i];
  21557. it->upperQuartile = upperQuartile[i];
  21558. it->maximum = maximum[i];
  21559. ++it;
  21560. ++i;
  21561. }
  21562. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  21563. }
  21564. /*! \overload
  21565. Adds the provided data point as \a key, \a minimum, \a lowerQuartile, \a median, \a upperQuartile
  21566. and \a maximum to the current data.
  21567. Alternatively, you can also access and modify the data directly via the \ref data method, which
  21568. returns a pointer to the internal data container.
  21569. */
  21570. void QCPStatisticalBox::addData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum, const QVector<double> &outliers)
  21571. {
  21572. mDataContainer->add(QCPStatisticalBoxData(key, minimum, lowerQuartile, median, upperQuartile, maximum, outliers));
  21573. }
  21574. /*!
  21575. \copydoc QCPPlottableInterface1D::selectTestRect
  21576. */
  21577. QCPDataSelection QCPStatisticalBox::selectTestRect(const QRectF &rect, bool onlySelectable) const
  21578. {
  21579. QCPDataSelection result;
  21580. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  21581. return result;
  21582. if (!mKeyAxis || !mValueAxis)
  21583. return result;
  21584. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  21585. getVisibleDataBounds(visibleBegin, visibleEnd);
  21586. for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  21587. {
  21588. if (rect.intersects(getQuartileBox(it)))
  21589. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  21590. }
  21591. result.simplify();
  21592. return result;
  21593. }
  21594. /*!
  21595. Implements a selectTest specific to this plottable's point geometry.
  21596. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  21597. point to \a pos.
  21598. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  21599. */
  21600. double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  21601. {
  21602. Q_UNUSED(details)
  21603. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  21604. return -1;
  21605. if (!mKeyAxis || !mValueAxis)
  21606. return -1;
  21607. if (mKeyAxis->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  21608. {
  21609. // get visible data range:
  21610. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  21611. QCPStatisticalBoxDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  21612. getVisibleDataBounds(visibleBegin, visibleEnd);
  21613. double minDistSqr = (std::numeric_limits<double>::max)();
  21614. for (QCPStatisticalBoxDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  21615. {
  21616. if (getQuartileBox(it).contains(pos)) // quartile box
  21617. {
  21618. double currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  21619. if (currentDistSqr < minDistSqr)
  21620. {
  21621. minDistSqr = currentDistSqr;
  21622. closestDataPoint = it;
  21623. }
  21624. } else // whiskers
  21625. {
  21626. const QVector<QLineF> whiskerBackbones = getWhiskerBackboneLines(it);
  21627. const QCPVector2D posVec(pos);
  21628. foreach (const QLineF &backbone, whiskerBackbones)
  21629. {
  21630. double currentDistSqr = posVec.distanceSquaredToLine(backbone);
  21631. if (currentDistSqr < minDistSqr)
  21632. {
  21633. minDistSqr = currentDistSqr;
  21634. closestDataPoint = it;
  21635. }
  21636. }
  21637. }
  21638. }
  21639. if (details)
  21640. {
  21641. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  21642. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  21643. }
  21644. return qSqrt(minDistSqr);
  21645. }
  21646. return -1;
  21647. }
  21648. /* inherits documentation from base class */
  21649. QCPRange QCPStatisticalBox::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  21650. {
  21651. QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
  21652. // determine exact range by including width of bars/flags:
  21653. if (foundRange)
  21654. {
  21655. if (inSignDomain != QCP::SignDomain::sdPositive || range.lower-mWidth*0.5 > 0)
  21656. range.lower -= mWidth*0.5;
  21657. if (inSignDomain != QCP::SignDomain::sdNegative || range.upper+mWidth*0.5 < 0)
  21658. range.upper += mWidth*0.5;
  21659. }
  21660. return range;
  21661. }
  21662. /* inherits documentation from base class */
  21663. QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  21664. {
  21665. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  21666. }
  21667. /* inherits documentation from base class */
  21668. void QCPStatisticalBox::draw(QCPPainter *painter)
  21669. {
  21670. if (mDataContainer->isEmpty()) return;
  21671. QCPAxis *keyAxis = mKeyAxis.data();
  21672. QCPAxis *valueAxis = mValueAxis.data();
  21673. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  21674. QCPStatisticalBoxDataContainer::const_iterator visibleBegin, visibleEnd;
  21675. getVisibleDataBounds(visibleBegin, visibleEnd);
  21676. // loop over and draw segments of unselected/selected data:
  21677. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  21678. getDataSegments(selectedSegments, unselectedSegments);
  21679. allSegments << unselectedSegments << selectedSegments;
  21680. for (int i=0; i<allSegments.size(); ++i)
  21681. {
  21682. bool isSelectedSegment = i >= unselectedSegments.size();
  21683. QCPStatisticalBoxDataContainer::const_iterator begin = visibleBegin;
  21684. QCPStatisticalBoxDataContainer::const_iterator end = visibleEnd;
  21685. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  21686. if (begin == end)
  21687. continue;
  21688. for (QCPStatisticalBoxDataContainer::const_iterator it=begin; it!=end; ++it)
  21689. {
  21690. // check data validity if flag set:
  21691. # ifdef QCUSTOMPLOT_CHECK_DATA
  21692. if (QCP::isInvalidData(it->key, it->minimum) ||
  21693. QCP::isInvalidData(it->lowerQuartile, it->median) ||
  21694. QCP::isInvalidData(it->upperQuartile, it->maximum))
  21695. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "of drawn range has invalid data." << "Plottable name:" << name();
  21696. for (int i=0; i<it->outliers.size(); ++i)
  21697. if (QCP::isInvalidData(it->outliers.at(i)))
  21698. qDebug() << Q_FUNC_INFO << "Data point outlier at" << it->key << "of drawn range invalid." << "Plottable name:" << name();
  21699. # endif
  21700. if (isSelectedSegment && mSelectionDecorator)
  21701. {
  21702. mSelectionDecorator->applyPen(painter);
  21703. mSelectionDecorator->applyBrush(painter);
  21704. } else
  21705. {
  21706. painter->setPen(mPen);
  21707. painter->setBrush(mBrush);
  21708. }
  21709. QCPScatterStyle finalOutlierStyle = mOutlierStyle;
  21710. if (isSelectedSegment && mSelectionDecorator)
  21711. finalOutlierStyle = mSelectionDecorator->getFinalScatterStyle(mOutlierStyle);
  21712. drawStatisticalBox(painter, it, finalOutlierStyle);
  21713. }
  21714. }
  21715. // draw other selection decoration that isn't just line/scatter pens and brushes:
  21716. if (mSelectionDecorator)
  21717. mSelectionDecorator->drawDecoration(painter, selection());
  21718. }
  21719. /* inherits documentation from base class */
  21720. void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  21721. {
  21722. // draw filled rect:
  21723. applyDefaultAntialiasingHint(painter);
  21724. painter->setPen(mPen);
  21725. painter->setBrush(mBrush);
  21726. QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67);
  21727. r.moveCenter(rect.center());
  21728. painter->drawRect(r);
  21729. }
  21730. /*!
  21731. Draws the graphical representation of a single statistical box with the data given by the
  21732. iterator \a it with the provided \a painter.
  21733. If the statistical box has a set of outlier data points, they are drawn with \a outlierStyle.
  21734. \see getQuartileBox, getWhiskerBackboneLines, getWhiskerBarLines
  21735. */
  21736. void QCPStatisticalBox::drawStatisticalBox(QCPPainter *painter, QCPStatisticalBoxDataContainer::const_iterator it, const QCPScatterStyle &outlierStyle) const
  21737. {
  21738. // draw quartile box:
  21739. applyDefaultAntialiasingHint(painter);
  21740. const QRectF quartileBox = getQuartileBox(it);
  21741. painter->drawRect(quartileBox);
  21742. // draw median line with cliprect set to quartile box:
  21743. painter->save();
  21744. painter->setClipRect(quartileBox, Qt::IntersectClip);
  21745. painter->setPen(mMedianPen);
  21746. painter->drawLine(QLineF(coordsToPixels(it->key-mWidth*0.5, it->median), coordsToPixels(it->key+mWidth*0.5, it->median)));
  21747. painter->restore();
  21748. // draw whisker lines:
  21749. applyAntialiasingHint(painter, mWhiskerAntialiased, QCP::aePlottables);
  21750. painter->setPen(mWhiskerPen);
  21751. painter->drawLines(getWhiskerBackboneLines(it));
  21752. painter->setPen(mWhiskerBarPen);
  21753. painter->drawLines(getWhiskerBarLines(it));
  21754. // draw outliers:
  21755. applyScattersAntialiasingHint(painter);
  21756. outlierStyle.applyTo(painter, mPen);
  21757. for (int i=0; i<it->outliers.size(); ++i)
  21758. outlierStyle.drawShape(painter, coordsToPixels(it->key, it->outliers.at(i)));
  21759. }
  21760. /*! \internal
  21761. called by \ref draw to determine which data (key) range is visible at the current key axis range
  21762. setting, so only that needs to be processed. It also takes into account the bar width.
  21763. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  21764. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  21765. lower may still be just outside the visible range.
  21766. \a end returns an iterator one higher than the highest visible data point. Same as before, \a end
  21767. may also lie just outside of the visible range.
  21768. if the plottable contains no data, both \a begin and \a end point to constEnd.
  21769. */
  21770. void QCPStatisticalBox::getVisibleDataBounds(QCPStatisticalBoxDataContainer::const_iterator &begin, QCPStatisticalBoxDataContainer::const_iterator &end) const
  21771. {
  21772. if (!mKeyAxis)
  21773. {
  21774. qDebug() << Q_FUNC_INFO << "invalid key axis";
  21775. begin = mDataContainer->constEnd();
  21776. end = mDataContainer->constEnd();
  21777. return;
  21778. }
  21779. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of box to include partially visible data points
  21780. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of box to include partially visible data points
  21781. }
  21782. /*! \internal
  21783. Returns the box in plot coordinates (keys in x, values in y of the returned rect) that covers the
  21784. value range from the lower to the upper quartile, of the data given by \a it.
  21785. \see drawStatisticalBox, getWhiskerBackboneLines, getWhiskerBarLines
  21786. */
  21787. QRectF QCPStatisticalBox::getQuartileBox(QCPStatisticalBoxDataContainer::const_iterator it) const
  21788. {
  21789. QRectF result;
  21790. result.setTopLeft(coordsToPixels(it->key-mWidth*0.5, it->upperQuartile));
  21791. result.setBottomRight(coordsToPixels(it->key+mWidth*0.5, it->lowerQuartile));
  21792. return result;
  21793. }
  21794. /*! \internal
  21795. Returns the whisker backbones (keys in x, values in y of the returned lines) that cover the value
  21796. range from the minimum to the lower quartile, and from the upper quartile to the maximum of the
  21797. data given by \a it.
  21798. \see drawStatisticalBox, getQuartileBox, getWhiskerBarLines
  21799. */
  21800. QVector<QLineF> QCPStatisticalBox::getWhiskerBackboneLines(QCPStatisticalBoxDataContainer::const_iterator it) const
  21801. {
  21802. QVector<QLineF> result(2);
  21803. result[0].setPoints(coordsToPixels(it->key, it->lowerQuartile), coordsToPixels(it->key, it->minimum)); // min backbone
  21804. result[1].setPoints(coordsToPixels(it->key, it->upperQuartile), coordsToPixels(it->key, it->maximum)); // max backbone
  21805. return result;
  21806. }
  21807. /*! \internal
  21808. Returns the whisker bars (keys in x, values in y of the returned lines) that are placed at the
  21809. end of the whisker backbones, at the minimum and maximum of the data given by \a it.
  21810. \see drawStatisticalBox, getQuartileBox, getWhiskerBackboneLines
  21811. */
  21812. QVector<QLineF> QCPStatisticalBox::getWhiskerBarLines(QCPStatisticalBoxDataContainer::const_iterator it) const
  21813. {
  21814. QVector<QLineF> result(2);
  21815. result[0].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->minimum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->minimum)); // min bar
  21816. result[1].setPoints(coordsToPixels(it->key-mWhiskerWidth*0.5, it->maximum), coordsToPixels(it->key+mWhiskerWidth*0.5, it->maximum)); // max bar
  21817. return result;
  21818. }
  21819. /* end of 'src/plottables/plottable-statisticalbox.cpp' */
  21820. /* including file 'src/plottables/plottable-colormap.cpp' */
  21821. /* modified 2021-03-29T02:30:44, size 48149 */
  21822. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21823. //////////////////// QCPColorMapData
  21824. ////////////////////////////////////////////////////////////////////////////////////////////////////
  21825. /*! \class QCPColorMapData
  21826. \brief Holds the two-dimensional data of a QCPColorMap plottable.
  21827. This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref
  21828. QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a
  21829. color, depending on the value.
  21830. The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize).
  21831. Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref
  21832. setKeyRange, \ref setValueRange).
  21833. The data cells can be accessed in two ways: They can be directly addressed by an integer index
  21834. with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot
  21835. coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are
  21836. provided by the functions \ref coordToCell and \ref cellToCoord.
  21837. A \ref QCPColorMapData also holds an on-demand two-dimensional array of alpha values which (if
  21838. allocated) has the same size as the data map. It can be accessed via \ref setAlpha, \ref
  21839. fillAlpha and \ref clearAlpha. The memory for the alpha map is only allocated if needed, i.e. on
  21840. the first call of \ref setAlpha. \ref clearAlpha restores full opacity and frees the alpha map.
  21841. This class also buffers the minimum and maximum values that are in the data set, to provide
  21842. QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value
  21843. that is greater than the current maximum increases this maximum to the new value. However,
  21844. setting the cell that currently holds the maximum value to a smaller value doesn't decrease the
  21845. maximum again, because finding the true new maximum would require going through the entire data
  21846. array, which might be time consuming. The same holds for the data minimum. This functionality is
  21847. given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the
  21848. true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience
  21849. parameter \a recalculateDataBounds which may be set to true to automatically call \ref
  21850. recalculateDataBounds internally.
  21851. */
  21852. /* start of documentation of inline functions */
  21853. /*! \fn bool QCPColorMapData::isEmpty() const
  21854. Returns whether this instance carries no data. This is equivalent to having a size where at least
  21855. one of the dimensions is 0 (see \ref setSize).
  21856. */
  21857. /* end of documentation of inline functions */
  21858. /*!
  21859. Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction
  21860. and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap
  21861. at the coordinates \a keyRange and \a valueRange.
  21862. \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange
  21863. */
  21864. QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) :
  21865. mKeySize(0),
  21866. mValueSize(0),
  21867. mKeyRange(keyRange),
  21868. mValueRange(valueRange),
  21869. mIsEmpty(true),
  21870. mData(nullptr),
  21871. mAlpha(nullptr),
  21872. mDataModified(true)
  21873. {
  21874. setSize(keySize, valueSize);
  21875. fill(0);
  21876. }
  21877. QCPColorMapData::~QCPColorMapData()
  21878. {
  21879. delete[] mData;
  21880. delete[] mAlpha;
  21881. }
  21882. /*!
  21883. Constructs a new QCPColorMapData instance copying the data and range of \a other.
  21884. */
  21885. QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) :
  21886. mKeySize(0),
  21887. mValueSize(0),
  21888. mIsEmpty(true),
  21889. mData(nullptr),
  21890. mAlpha(nullptr),
  21891. mDataModified(true)
  21892. {
  21893. *this = other;
  21894. }
  21895. /*!
  21896. Overwrites this color map data instance with the data stored in \a other. The alpha map state is
  21897. transferred, too.
  21898. */
  21899. QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other)
  21900. {
  21901. if (&other != this)
  21902. {
  21903. const int keySize = other.keySize();
  21904. const int valueSize = other.valueSize();
  21905. if (!other.mAlpha && mAlpha)
  21906. clearAlpha();
  21907. setSize(keySize, valueSize);
  21908. if (other.mAlpha && !mAlpha)
  21909. createAlpha(false);
  21910. setRange(other.keyRange(), other.valueRange());
  21911. if (!isEmpty())
  21912. {
  21913. memcpy(mData, other.mData, sizeof(mData[0])*size_t((double)keySize* (double)valueSize));
  21914. if (mAlpha)
  21915. memcpy(mAlpha, other.mAlpha, sizeof(mAlpha[0])*size_t((double)keySize* (double)valueSize));
  21916. }
  21917. mDataBounds = other.mDataBounds;
  21918. mDataModified = true;
  21919. }
  21920. return *this;
  21921. }
  21922. /* undocumented getter */
  21923. double QCPColorMapData::data(double key, double value)
  21924. {
  21925. int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*((double)mKeySize-1.0)+0.5 );
  21926. int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*((double)mValueSize-1.0)+0.5 );
  21927. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  21928. return mData[valueCell*mKeySize + keyCell];
  21929. else
  21930. return 0;
  21931. }
  21932. /* undocumented getter */
  21933. double QCPColorMapData::cell(int keyIndex, int valueIndex)
  21934. {
  21935. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  21936. return mData[valueIndex*mKeySize + keyIndex];
  21937. else
  21938. return 0;
  21939. }
  21940. /*!
  21941. Returns the alpha map value of the cell with the indices \a keyIndex and \a valueIndex.
  21942. If this color map data doesn't have an alpha map (because \ref setAlpha was never called after
  21943. creation or after a call to \ref clearAlpha), returns 255, which corresponds to full opacity.
  21944. \see setAlpha
  21945. */
  21946. unsigned char QCPColorMapData::alpha(int keyIndex, int valueIndex)
  21947. {
  21948. if (mAlpha && keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  21949. return mAlpha[valueIndex*mKeySize + keyIndex];
  21950. else
  21951. return 255;
  21952. }
  21953. /*!
  21954. Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in
  21955. the value dimension.
  21956. The current data is discarded and the map cells are set to 0, unless the map had already the
  21957. requested size.
  21958. Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref
  21959. isEmpty returns true.
  21960. \see setRange, setKeySize, setValueSize
  21961. */
  21962. void QCPColorMapData::setSize(int keySize, int valueSize)
  21963. {
  21964. if (keySize != mKeySize || valueSize != mValueSize)
  21965. {
  21966. mKeySize = keySize;
  21967. mValueSize = valueSize;
  21968. delete[] mData;
  21969. mIsEmpty = mKeySize == 0 || mValueSize == 0;
  21970. if (!mIsEmpty)
  21971. {
  21972. #ifdef __EXCEPTIONS
  21973. try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
  21974. #endif
  21975. mData = new double[size_t((double)mKeySize* (double)mValueSize)];
  21976. #ifdef __EXCEPTIONS
  21977. } catch (...) { mData = nullptr; }
  21978. #endif
  21979. if (mData)
  21980. fill(0);
  21981. else
  21982. qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
  21983. } else
  21984. mData = nullptr;
  21985. if (mAlpha) // if we had an alpha map, recreate it with new size
  21986. createAlpha();
  21987. mDataModified = true;
  21988. }
  21989. }
  21990. /*!
  21991. Resizes the data array to have \a keySize cells in the key dimension.
  21992. The current data is discarded and the map cells are set to 0, unless the map had already the
  21993. requested size.
  21994. Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true.
  21995. \see setKeyRange, setSize, setValueSize
  21996. */
  21997. void QCPColorMapData::setKeySize(int keySize)
  21998. {
  21999. setSize(keySize, mValueSize);
  22000. }
  22001. /*!
  22002. Resizes the data array to have \a valueSize cells in the value dimension.
  22003. The current data is discarded and the map cells are set to 0, unless the map had already the
  22004. requested size.
  22005. Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true.
  22006. \see setValueRange, setSize, setKeySize
  22007. */
  22008. void QCPColorMapData::setValueSize(int valueSize)
  22009. {
  22010. setSize(mKeySize, valueSize);
  22011. }
  22012. /*!
  22013. Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area
  22014. covered by the color map in plot coordinates.
  22015. The outer cells will be centered on the range boundaries given to this function. For example, if
  22016. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  22017. be cells centered on the key coordinates 2, 2.5 and 3.
  22018. \see setSize
  22019. */
  22020. void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange)
  22021. {
  22022. setKeyRange(keyRange);
  22023. setValueRange(valueRange);
  22024. }
  22025. /*!
  22026. Sets the coordinate range the data shall be distributed over in the key dimension. Together with
  22027. the value range, This defines the rectangular area covered by the color map in plot coordinates.
  22028. The outer cells will be centered on the range boundaries given to this function. For example, if
  22029. the key size (\ref setKeySize) is 3 and \a keyRange is set to <tt>QCPRange(2, 3)</tt> there will
  22030. be cells centered on the key coordinates 2, 2.5 and 3.
  22031. \see setRange, setValueRange, setSize
  22032. */
  22033. void QCPColorMapData::setKeyRange(const QCPRange &keyRange)
  22034. {
  22035. mKeyRange = keyRange;
  22036. }
  22037. /*!
  22038. Sets the coordinate range the data shall be distributed over in the value dimension. Together with
  22039. the key range, This defines the rectangular area covered by the color map in plot coordinates.
  22040. The outer cells will be centered on the range boundaries given to this function. For example, if
  22041. the value size (\ref setValueSize) is 3 and \a valueRange is set to <tt>QCPRange(2, 3)</tt> there
  22042. will be cells centered on the value coordinates 2, 2.5 and 3.
  22043. \see setRange, setKeyRange, setSize
  22044. */
  22045. void QCPColorMapData::setValueRange(const QCPRange &valueRange)
  22046. {
  22047. mValueRange = valueRange;
  22048. }
  22049. /*!
  22050. Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a
  22051. z.
  22052. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22053. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22054. you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
  22055. determine the cell index. Rather directly access the cell index with \ref
  22056. QCPColorMapData::setCell.
  22057. \see setCell, setRange
  22058. */
  22059. void QCPColorMapData::setData(double key, double value, double z)
  22060. {
  22061. int keyCell = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*((double)mKeySize- (double)1)+0.5 );
  22062. int valueCell = int( (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5 );
  22063. if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize)
  22064. {
  22065. mData[valueCell*mKeySize + keyCell] = z;
  22066. if (z < mDataBounds.lower)
  22067. mDataBounds.lower = z;
  22068. if (z > mDataBounds.upper)
  22069. mDataBounds.upper = z;
  22070. mDataModified = true;
  22071. }
  22072. }
  22073. /*!
  22074. Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices
  22075. enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see
  22076. \ref setSize).
  22077. In the standard plot configuration (horizontal key axis and vertical value axis, both not
  22078. range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with
  22079. indices (keySize-1, valueSize-1) is in the top right corner of the color map.
  22080. \see setData, setSize
  22081. */
  22082. void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z)
  22083. {
  22084. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  22085. {
  22086. mData[valueIndex*mKeySize + keyIndex] = z;
  22087. if (z < mDataBounds.lower)
  22088. mDataBounds.lower = z;
  22089. if (z > mDataBounds.upper)
  22090. mDataBounds.upper = z;
  22091. mDataModified = true;
  22092. } else
  22093. qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
  22094. }
  22095. /*!
  22096. Sets the alpha of the color map cell given by \a keyIndex and \a valueIndex to \a alpha. A value
  22097. of 0 for \a alpha results in a fully transparent cell, and a value of 255 results in a fully
  22098. opaque cell.
  22099. If an alpha map doesn't exist yet for this color map data, it will be created here. If you wish
  22100. to restore full opacity and free any allocated memory of the alpha map, call \ref clearAlpha.
  22101. Note that the cell-wise alpha which can be configured here is independent of any alpha configured
  22102. in the color map's gradient (\ref QCPColorGradient). If a cell is affected both by the cell-wise
  22103. and gradient alpha, the alpha values will be blended accordingly during rendering of the color
  22104. map.
  22105. \see fillAlpha, clearAlpha
  22106. */
  22107. void QCPColorMapData::setAlpha(int keyIndex, int valueIndex, unsigned char alpha)
  22108. {
  22109. if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize)
  22110. {
  22111. if (mAlpha || createAlpha())
  22112. {
  22113. mAlpha[valueIndex*mKeySize + keyIndex] = alpha;
  22114. mDataModified = true;
  22115. }
  22116. } else
  22117. qDebug() << Q_FUNC_INFO << "index out of bounds:" << keyIndex << valueIndex;
  22118. }
  22119. /*!
  22120. Goes through the data and updates the buffered minimum and maximum data values.
  22121. Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange
  22122. and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten
  22123. with a smaller or larger value respectively, since the buffered maximum/minimum values have been
  22124. updated the last time. Why this is the case is explained in the class description (\ref
  22125. QCPColorMapData).
  22126. Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a
  22127. recalculateDataBounds for convenience. Setting this to true will call this method for you, before
  22128. doing the rescale.
  22129. */
  22130. void QCPColorMapData::recalculateDataBounds()
  22131. {
  22132. if (mKeySize > 0 && mValueSize > 0)
  22133. {
  22134. double minHeight = mData[0];
  22135. double maxHeight = mData[0];
  22136. const int dataCount = mValueSize*mKeySize;
  22137. for (int i=0; i<dataCount; ++i)
  22138. {
  22139. if (mData[i] > maxHeight)
  22140. maxHeight = mData[i];
  22141. if (mData[i] < minHeight)
  22142. minHeight = mData[i];
  22143. }
  22144. mDataBounds.lower = minHeight;
  22145. mDataBounds.upper = maxHeight;
  22146. }
  22147. }
  22148. /*!
  22149. Frees the internal data memory.
  22150. This is equivalent to calling \ref setSize "setSize(0, 0)".
  22151. */
  22152. void QCPColorMapData::clear()
  22153. {
  22154. setSize(0, 0);
  22155. }
  22156. /*!
  22157. Frees the internal alpha map. The color map will have full opacity again.
  22158. */
  22159. void QCPColorMapData::clearAlpha()
  22160. {
  22161. if (mAlpha)
  22162. {
  22163. delete[] mAlpha;
  22164. mAlpha = nullptr;
  22165. mDataModified = true;
  22166. }
  22167. }
  22168. /*!
  22169. Sets all cells to the value \a z.
  22170. */
  22171. void QCPColorMapData::fill(double z)
  22172. {
  22173. const int dataCount = mValueSize*mKeySize;
  22174. for (int i=0; i<dataCount; ++i)
  22175. mData[i] = z;
  22176. mDataBounds = QCPRange(z, z);
  22177. mDataModified = true;
  22178. }
  22179. /*!
  22180. Sets the opacity of all color map cells to \a alpha. A value of 0 for \a alpha results in a fully
  22181. transparent color map, and a value of 255 results in a fully opaque color map.
  22182. If you wish to restore opacity to 100% and free any used memory for the alpha map, rather use
  22183. \ref clearAlpha.
  22184. \see setAlpha
  22185. */
  22186. void QCPColorMapData::fillAlpha(unsigned char alpha)
  22187. {
  22188. if (mAlpha || createAlpha(false))
  22189. {
  22190. const int dataCount = mValueSize*mKeySize;
  22191. for (int i=0; i<dataCount; ++i)
  22192. mAlpha[i] = alpha;
  22193. mDataModified = true;
  22194. }
  22195. }
  22196. /*!
  22197. Transforms plot coordinates given by \a key and \a value to cell indices of this QCPColorMapData
  22198. instance. The resulting cell indices are returned via the output parameters \a keyIndex and \a
  22199. valueIndex.
  22200. The retrieved key/value cell indices can then be used for example with \ref setCell.
  22201. If you are only interested in a key or value index, you may pass \c nullptr as \a valueIndex or
  22202. \a keyIndex.
  22203. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22204. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22205. you shouldn't use the \ref QCPColorMapData::coordToCell method as it uses a linear transformation to
  22206. determine the cell index.
  22207. \see cellToCoord, QCPAxis::coordToPixel
  22208. */
  22209. void QCPColorMapData::coordToCell(double key, double value, int *keyIndex, int *valueIndex) const
  22210. {
  22211. if (keyIndex)
  22212. *keyIndex = int( (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize - 1.0)+0.5 );
  22213. if (valueIndex)
  22214. *valueIndex = int( (value- mValueRange.lower) / (mValueRange.upper-mValueRange.lower)*(mValueSize -1.0 )+0.5 );
  22215. }
  22216. /*!
  22217. Transforms cell indices given by \a keyIndex and \a valueIndex to cell indices of this QCPColorMapData
  22218. instance. The resulting coordinates are returned via the output parameters \a key and \a
  22219. value.
  22220. If you are only interested in a key or value coordinate, you may pass \c nullptr as \a key or \a
  22221. value.
  22222. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22223. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22224. you shouldn't use the \ref QCPColorMapData::cellToCoord method as it uses a linear transformation to
  22225. determine the cell index.
  22226. \see coordToCell, QCPAxis::pixelToCoord
  22227. */
  22228. void QCPColorMapData::cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const
  22229. {
  22230. if (key)
  22231. *key = keyIndex/double(mKeySize-1.0)*(mKeyRange.upper-mKeyRange.lower)+mKeyRange.lower;
  22232. if (value)
  22233. *value = valueIndex/double(mValueSize-1.0)*(mValueRange.upper-mValueRange.lower)+mValueRange.lower;
  22234. }
  22235. /*! \internal
  22236. Allocates the internal alpha map with the current data map key/value size and, if \a
  22237. initializeOpaque is true, initializes all values to 255. If \a initializeOpaque is false, the
  22238. values are not initialized at all. In this case, the alpha map should be initialized manually,
  22239. e.g. with \ref fillAlpha.
  22240. If an alpha map exists already, it is deleted first. If this color map is empty (has either key
  22241. or value size zero, see \ref isEmpty), the alpha map is cleared.
  22242. The return value indicates the existence of the alpha map after the call. So this method returns
  22243. true if the data map isn't empty and an alpha map was successfully allocated.
  22244. */
  22245. bool QCPColorMapData::createAlpha(bool initializeOpaque)
  22246. {
  22247. clearAlpha();
  22248. if (isEmpty())
  22249. return false;
  22250. #ifdef __EXCEPTIONS
  22251. try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message
  22252. #endif
  22253. mAlpha = new unsigned char[size_t((double) mKeySize* (double)mValueSize)];
  22254. #ifdef __EXCEPTIONS
  22255. } catch (...) { mAlpha = nullptr; }
  22256. #endif
  22257. if (mAlpha)
  22258. {
  22259. if (initializeOpaque)
  22260. fillAlpha(255);
  22261. return true;
  22262. } else
  22263. {
  22264. qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize;
  22265. return false;
  22266. }
  22267. }
  22268. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22269. //////////////////// QCPColorMap
  22270. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22271. /*! \class QCPColorMap
  22272. \brief A plottable representing a two-dimensional color map in a plot.
  22273. \image html QCPColorMap.png
  22274. The data is stored in the class \ref QCPColorMapData, which can be accessed via the data()
  22275. method.
  22276. A color map has three dimensions to represent a data point: The \a key dimension, the \a value
  22277. dimension and the \a data dimension. As with other plottables such as graphs, \a key and \a value
  22278. correspond to two orthogonal axes on the QCustomPlot surface that you specify in the QCPColorMap
  22279. constructor. The \a data dimension however is encoded as the color of the point at (\a key, \a
  22280. value).
  22281. Set the number of points (or \a cells) in the key/value dimension via \ref
  22282. QCPColorMapData::setSize. The plot coordinate range over which these points will be displayed is
  22283. specified via \ref QCPColorMapData::setRange. The first cell will be centered on the lower range
  22284. boundary and the last cell will be centered on the upper range boundary. The data can be set by
  22285. either accessing the cells directly with QCPColorMapData::setCell or by addressing the cells via
  22286. their plot coordinates with \ref QCPColorMapData::setData. If possible, you should prefer
  22287. setCell, since it doesn't need to do any coordinate transformation and thus performs a bit
  22288. better.
  22289. The cell with index (0, 0) is at the bottom left, if the color map uses normal (i.e. not reversed)
  22290. key and value axes.
  22291. To show the user which colors correspond to which \a data values, a \ref QCPColorScale is
  22292. typically placed to the right of the axis rect. See the documentation there for details on how to
  22293. add and use a color scale.
  22294. \section qcpcolormap-appearance Changing the appearance
  22295. Most important to the appearance is the color gradient, which can be specified via \ref
  22296. setGradient. See the documentation of \ref QCPColorGradient for details on configuring a color
  22297. gradient.
  22298. The \a data range that is mapped to the colors of the gradient can be specified with \ref
  22299. setDataRange. To make the data range encompass the whole data set minimum to maximum, call \ref
  22300. rescaleDataRange. If your data may contain NaN values, use \ref QCPColorGradient::setNanHandling
  22301. to define how they are displayed.
  22302. \section qcpcolormap-transparency Transparency
  22303. Transparency in color maps can be achieved by two mechanisms. On one hand, you can specify alpha
  22304. values for color stops of the \ref QCPColorGradient, via the regular QColor interface. This will
  22305. cause the color map data which gets mapped to colors around those color stops to appear with the
  22306. accordingly interpolated transparency.
  22307. On the other hand you can also directly apply an alpha value to each cell independent of its
  22308. data, by using the alpha map feature of \ref QCPColorMapData. The relevant methods are \ref
  22309. QCPColorMapData::setAlpha, QCPColorMapData::fillAlpha and \ref QCPColorMapData::clearAlpha().
  22310. The two transparencies will be joined together in the plot and otherwise not interfere with each
  22311. other. They are mixed in a multiplicative matter, so an alpha of e.g. 50% (128/255) in both modes
  22312. simultaneously, will result in a total transparency of 25% (64/255).
  22313. \section qcpcolormap-usage Usage
  22314. Like all data representing objects in QCustomPlot, the QCPColorMap is a plottable
  22315. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  22316. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  22317. Usually, you first create an instance:
  22318. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-1
  22319. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot instance takes
  22320. ownership of the plottable, so do not delete it manually but use QCustomPlot::removePlottable() instead.
  22321. The newly created plottable can be modified, e.g.:
  22322. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpcolormap-creation-2
  22323. \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or
  22324. value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes,
  22325. you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to
  22326. determine the cell index. Rather directly access the cell index with \ref
  22327. QCPColorMapData::setCell.
  22328. */
  22329. /* start documentation of inline functions */
  22330. /*! \fn QCPColorMapData *QCPColorMap::data() const
  22331. Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to
  22332. modify data points (cells) and the color map key/value range.
  22333. \see setData
  22334. */
  22335. /* end documentation of inline functions */
  22336. /* start documentation of signals */
  22337. /*! \fn void QCPColorMap::dataRangeChanged(const QCPRange &newRange);
  22338. This signal is emitted when the data range changes.
  22339. \see setDataRange
  22340. */
  22341. /*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType);
  22342. This signal is emitted when the data scale type changes.
  22343. \see setDataScaleType
  22344. */
  22345. /*! \fn void QCPColorMap::gradientChanged(const QCPColorGradient &newGradient);
  22346. This signal is emitted when the gradient changes.
  22347. \see setGradient
  22348. */
  22349. /* end documentation of signals */
  22350. /*!
  22351. Constructs a color map with the specified \a keyAxis and \a valueAxis.
  22352. The created QCPColorMap is automatically registered with the QCustomPlot instance inferred from
  22353. \a keyAxis. This QCustomPlot instance takes ownership of the QCPColorMap, so do not delete it
  22354. manually but use QCustomPlot::removePlottable() instead.
  22355. */
  22356. QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  22357. QCPAbstractPlottable(keyAxis, valueAxis),
  22358. mDataScaleType(QCPAxis::ScaleType::stLinear),
  22359. mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))),
  22360. mGradient(QCPColorGradient:: GradientPreset::gpCold),
  22361. mInterpolate(true),
  22362. mTightBoundary(false),
  22363. mMapImageInvalidated(true)
  22364. {
  22365. }
  22366. QCPColorMap::~QCPColorMap()
  22367. {
  22368. delete mMapData;
  22369. }
  22370. /*!
  22371. Replaces the current \ref data with the provided \a data.
  22372. If \a copy is set to true, the \a data object will only be copied. if false, the color map
  22373. takes ownership of the passed data and replaces the internal data pointer with it. This is
  22374. significantly faster than copying for large datasets.
  22375. */
  22376. void QCPColorMap::setData(QCPColorMapData *data, bool copy)
  22377. {
  22378. if (mMapData == data)
  22379. {
  22380. qDebug() << Q_FUNC_INFO << "The data pointer is already in (and owned by) this plottable" << reinterpret_cast<quintptr>(data);
  22381. return;
  22382. }
  22383. if (copy)
  22384. {
  22385. *mMapData = *data;
  22386. } else
  22387. {
  22388. delete mMapData;
  22389. mMapData = data;
  22390. }
  22391. mMapImageInvalidated = true;
  22392. }
  22393. /*!
  22394. Sets the data range of this color map to \a dataRange. The data range defines which data values
  22395. are mapped to the color gradient.
  22396. To make the data range span the full range of the data set, use \ref rescaleDataRange.
  22397. \see QCPColorScale::setDataRange
  22398. */
  22399. void QCPColorMap::setDataRange(const QCPRange &dataRange)
  22400. {
  22401. if (!QCPRange::validRange(dataRange)) return;
  22402. if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper)
  22403. {
  22404. if (mDataScaleType == QCPAxis::ScaleType::stLogarithmic)
  22405. mDataRange = dataRange.sanitizedForLogScale();
  22406. else
  22407. mDataRange = dataRange.sanitizedForLinScale();
  22408. mMapImageInvalidated = true;
  22409. emit dataRangeChanged(mDataRange);
  22410. }
  22411. }
  22412. /*!
  22413. Sets whether the data is correlated with the color gradient linearly or logarithmically.
  22414. \see QCPColorScale::setDataScaleType
  22415. */
  22416. void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType)
  22417. {
  22418. if (mDataScaleType != scaleType)
  22419. {
  22420. mDataScaleType = scaleType;
  22421. mMapImageInvalidated = true;
  22422. emit dataScaleTypeChanged(mDataScaleType);
  22423. if (mDataScaleType == QCPAxis::ScaleType::stLogarithmic)
  22424. setDataRange(mDataRange.sanitizedForLogScale());
  22425. }
  22426. }
  22427. /*!
  22428. Sets the color gradient that is used to represent the data. For more details on how to create an
  22429. own gradient or use one of the preset gradients, see \ref QCPColorGradient.
  22430. The colors defined by the gradient will be used to represent data values in the currently set
  22431. data range, see \ref setDataRange. Data points that are outside this data range will either be
  22432. colored uniformly with the respective gradient boundary color, or the gradient will repeat,
  22433. depending on \ref QCPColorGradient::setPeriodic.
  22434. \see QCPColorScale::setGradient
  22435. */
  22436. void QCPColorMap::setGradient(const QCPColorGradient &gradient)
  22437. {
  22438. if (mGradient != gradient)
  22439. {
  22440. mGradient = gradient;
  22441. mMapImageInvalidated = true;
  22442. emit gradientChanged(mGradient);
  22443. }
  22444. }
  22445. /*!
  22446. Sets whether the color map image shall use bicubic interpolation when displaying the color map
  22447. shrinked or expanded, and not at a 1:1 pixel-to-data scale.
  22448. \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled"
  22449. */
  22450. void QCPColorMap::setInterpolate(bool enabled)
  22451. {
  22452. mInterpolate = enabled;
  22453. mMapImageInvalidated = true; // because oversampling factors might need to change
  22454. }
  22455. /*!
  22456. Sets whether the outer most data rows and columns are clipped to the specified key and value
  22457. range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange).
  22458. if \a enabled is set to false, the data points at the border of the color map are drawn with the
  22459. same width and height as all other data points. Since the data points are represented by
  22460. rectangles of one color centered on the data coordinate, this means that the shown color map
  22461. extends by half a data point over the specified key/value range in each direction.
  22462. \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled"
  22463. */
  22464. void QCPColorMap::setTightBoundary(bool enabled)
  22465. {
  22466. mTightBoundary = enabled;
  22467. }
  22468. /*!
  22469. Associates the color scale \a colorScale with this color map.
  22470. This means that both the color scale and the color map synchronize their gradient, data range and
  22471. data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps
  22472. can be associated with one single color scale. This causes the color maps to also synchronize
  22473. those properties, via the mutual color scale.
  22474. This function causes the color map to adopt the current color gradient, data range and data scale
  22475. type of \a colorScale. After this call, you may change these properties at either the color map
  22476. or the color scale, and the setting will be applied to both.
  22477. Pass \c nullptr as \a colorScale to disconnect the color scale from this color map again.
  22478. */
  22479. void QCPColorMap::setColorScale(QCPColorScale *colorScale)
  22480. {
  22481. if (mColorScale) // unconnect signals from old color scale
  22482. {
  22483. disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
  22484. disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22485. disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
  22486. disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  22487. disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
  22488. disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22489. }
  22490. mColorScale = colorScale;
  22491. if (mColorScale) // connect signals to new color scale
  22492. {
  22493. setGradient(mColorScale.data()->gradient());
  22494. setDataRange(mColorScale.data()->dataRange());
  22495. setDataScaleType(mColorScale.data()->dataScaleType());
  22496. connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange)));
  22497. connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22498. connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient)));
  22499. connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange)));
  22500. connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient)));
  22501. connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType)));
  22502. }
  22503. }
  22504. /*!
  22505. Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the
  22506. current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods,
  22507. only for the third data dimension of the color map.
  22508. The minimum and maximum values of the data set are buffered in the internal QCPColorMapData
  22509. instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref
  22510. QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For
  22511. performance reasons, however, they are only updated in an expanding fashion. So the buffered
  22512. maximum can only increase and the buffered minimum can only decrease. In consequence, changes to
  22513. the data that actually lower the maximum of the data set (by overwriting the cell holding the
  22514. current maximum with a smaller value), aren't recognized and the buffered maximum overestimates
  22515. the true maximum of the data set. The same happens for the buffered minimum. To recalculate the
  22516. true minimum and maximum by explicitly looking at each cell, the method
  22517. QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a
  22518. recalculateDataBounds calls this method before setting the data range to the buffered minimum and
  22519. maximum.
  22520. \see setDataRange
  22521. */
  22522. void QCPColorMap::rescaleDataRange(bool recalculateDataBounds)
  22523. {
  22524. if (recalculateDataBounds)
  22525. mMapData->recalculateDataBounds();
  22526. setDataRange(mMapData->dataBounds());
  22527. }
  22528. /*!
  22529. Takes the current appearance of the color map and updates the legend icon, which is used to
  22530. represent this color map in the legend (see \ref QCPLegend).
  22531. The \a transformMode specifies whether the rescaling is done by a faster, low quality image
  22532. scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm
  22533. (Qt::SmoothTransformation).
  22534. The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to
  22535. the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured
  22536. legend icon size, the thumb will be rescaled during drawing of the legend item.
  22537. \see setDataRange
  22538. */
  22539. void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize)
  22540. {
  22541. if (mMapImage.isNull() && !data()->isEmpty())
  22542. updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet)
  22543. if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again
  22544. {
  22545. bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  22546. bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  22547. mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode);
  22548. }
  22549. }
  22550. /* inherits documentation from base class */
  22551. double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  22552. {
  22553. Q_UNUSED(details)
  22554. if ((onlySelectable && mSelectable == QCP::stNone) || mMapData->isEmpty())
  22555. return -1;
  22556. if (!mKeyAxis || !mValueAxis)
  22557. return -1;
  22558. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  22559. {
  22560. double posKey, posValue;
  22561. pixelsToCoords(pos, posKey, posValue);
  22562. if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue))
  22563. {
  22564. if (details)
  22565. details->setValue(QCPDataSelection(QCPDataRange(0, 1))); // temporary solution, to facilitate whole-plottable selection. Replace in future version with segmented 2D selection.
  22566. return mParentPlot->selectionTolerance()*0.99;
  22567. }
  22568. }
  22569. return -1;
  22570. }
  22571. /* inherits documentation from base class */
  22572. QCPRange QCPColorMap::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  22573. {
  22574. foundRange = true;
  22575. QCPRange result = mMapData->keyRange();
  22576. result.normalize();
  22577. if (inSignDomain == QCP::SignDomain::sdPositive)
  22578. {
  22579. if (result.lower <= 0 && result.upper > 0)
  22580. result.lower = result.upper*1e-3;
  22581. else if (result.lower <= 0 && result.upper <= 0)
  22582. foundRange = false;
  22583. } else if (inSignDomain == QCP::SignDomain::sdNegative)
  22584. {
  22585. if (result.upper >= 0 && result.lower < 0)
  22586. result.upper = result.lower*1e-3;
  22587. else if (result.upper >= 0 && result.lower >= 0)
  22588. foundRange = false;
  22589. }
  22590. return result;
  22591. }
  22592. /* inherits documentation from base class */
  22593. QCPRange QCPColorMap::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  22594. {
  22595. if (inKeyRange != QCPRange())
  22596. {
  22597. if (mMapData->keyRange().upper < inKeyRange.lower || mMapData->keyRange().lower > inKeyRange.upper)
  22598. {
  22599. foundRange = false;
  22600. return {};
  22601. }
  22602. }
  22603. foundRange = true;
  22604. QCPRange result = mMapData->valueRange();
  22605. result.normalize();
  22606. if (inSignDomain == QCP::SignDomain::sdPositive)
  22607. {
  22608. if (result.lower <= 0 && result.upper > 0)
  22609. result.lower = result.upper*1e-3;
  22610. else if (result.lower <= 0 && result.upper <= 0)
  22611. foundRange = false;
  22612. } else if (inSignDomain == QCP::SignDomain::sdNegative)
  22613. {
  22614. if (result.upper >= 0 && result.lower < 0)
  22615. result.upper = result.lower*1e-3;
  22616. else if (result.upper >= 0 && result.lower >= 0)
  22617. foundRange = false;
  22618. }
  22619. return result;
  22620. }
  22621. /*! \internal
  22622. Updates the internal map image buffer by going through the internal \ref QCPColorMapData and
  22623. turning the data values into color pixels with \ref QCPColorGradient::colorize.
  22624. This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image
  22625. has been invalidated for a different reason (e.g. a change of the data range with \ref
  22626. setDataRange).
  22627. If the map cell count is low, the image created will be oversampled in order to avoid a
  22628. QPainter::drawImage bug which makes inner pixel boundaries jitter when stretch-drawing images
  22629. without smooth transform enabled. Accordingly, oversampling isn't performed if \ref
  22630. setInterpolate is true.
  22631. */
  22632. void QCPColorMap::updateMapImage()
  22633. {
  22634. QCPAxis *keyAxis = mKeyAxis.data();
  22635. if (!keyAxis) return;
  22636. if (mMapData->isEmpty()) return;
  22637. const QImage::Format format = QImage::Format_ARGB32_Premultiplied;
  22638. const int keySize = mMapData->keySize();
  22639. const int valueSize = mMapData->valueSize();
  22640. 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
  22641. 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
  22642. // resize mMapImage to correct dimensions including possible oversampling factors, according to key/value axes orientation:
  22643. if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.width() != keySize*keyOversamplingFactor || mMapImage.height() != valueSize*valueOversamplingFactor))
  22644. mMapImage = QImage(QSize(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor), format);
  22645. else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.width() != valueSize*valueOversamplingFactor || mMapImage.height() != keySize*keyOversamplingFactor))
  22646. mMapImage = QImage(QSize(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor), format);
  22647. if (mMapImage.isNull())
  22648. {
  22649. qDebug() << Q_FUNC_INFO << "Couldn't create map image (possibly too large for memory)";
  22650. mMapImage = QImage(QSize(10, 10), format);
  22651. mMapImage.fill(Qt::black);
  22652. } else
  22653. {
  22654. QImage *localMapImage = &mMapImage; // this is the image on which the colorization operates. Either the final mMapImage, or if we need oversampling, mUndersampledMapImage
  22655. if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
  22656. {
  22657. // resize undersampled map image to actual key/value cell sizes:
  22658. if (keyAxis->orientation() == Qt::Horizontal && (mUndersampledMapImage.width() != keySize || mUndersampledMapImage.height() != valueSize))
  22659. mUndersampledMapImage = QImage(QSize(keySize, valueSize), format);
  22660. else if (keyAxis->orientation() == Qt::Vertical && (mUndersampledMapImage.width() != valueSize || mUndersampledMapImage.height() != keySize))
  22661. mUndersampledMapImage = QImage(QSize(valueSize, keySize), format);
  22662. localMapImage = &mUndersampledMapImage; // make the colorization run on the undersampled image
  22663. } else if (!mUndersampledMapImage.isNull())
  22664. mUndersampledMapImage = QImage(); // don't need oversampling mechanism anymore (map size has changed) but mUndersampledMapImage still has nonzero size, free it
  22665. const double *rawData = mMapData->mData;
  22666. const unsigned char *rawAlpha = mMapData->mAlpha;
  22667. if (keyAxis->orientation() == Qt::Horizontal)
  22668. {
  22669. const int lineCount = valueSize;
  22670. const int rowCount = keySize;
  22671. for (int line=0; line<lineCount; ++line)
  22672. {
  22673. QRgb* pixels = reinterpret_cast<QRgb*>(localMapImage->scanLine((double)lineCount-1.0- (double)line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system)
  22674. if (rawAlpha)
  22675. mGradient.colorize(rawData + (line* rowCount), rawAlpha+ (line* rowCount), mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::ScaleType::stLogarithmic);
  22676. else
  22677. mGradient.colorize(rawData+(line* rowCount), mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::ScaleType::stLogarithmic);
  22678. }
  22679. } else // keyAxis->orientation() == Qt::Vertical
  22680. {
  22681. const int lineCount = keySize;
  22682. const int rowCount = valueSize;
  22683. for (int line=0; line<lineCount; ++line)
  22684. {
  22685. 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)
  22686. if (rawAlpha)
  22687. mGradient.colorize(rawData+line, rawAlpha+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::ScaleType::stLogarithmic);
  22688. else
  22689. mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::ScaleType::stLogarithmic);
  22690. }
  22691. }
  22692. if (keyOversamplingFactor > 1 || valueOversamplingFactor > 1)
  22693. {
  22694. if (keyAxis->orientation() == Qt::Horizontal)
  22695. mMapImage = mUndersampledMapImage.scaled(keySize*keyOversamplingFactor, valueSize*valueOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
  22696. else
  22697. mMapImage = mUndersampledMapImage.scaled(valueSize*valueOversamplingFactor, keySize*keyOversamplingFactor, Qt::IgnoreAspectRatio, Qt::FastTransformation);
  22698. }
  22699. }
  22700. mMapData->mDataModified = false;
  22701. mMapImageInvalidated = false;
  22702. }
  22703. /* inherits documentation from base class */
  22704. void QCPColorMap::draw(QCPPainter *painter)
  22705. {
  22706. if (mMapData->isEmpty()) return;
  22707. if (!mKeyAxis || !mValueAxis) return;
  22708. applyDefaultAntialiasingHint(painter);
  22709. if (mMapData->mDataModified || mMapImageInvalidated)
  22710. updateMapImage();
  22711. // use buffer if painting vectorized (PDF):
  22712. const bool useBuffer = painter->modes().testFlag(QCPPainter::pmVectorized);
  22713. QCPPainter *localPainter = painter; // will be redirected to paint on mapBuffer if painting vectorized
  22714. QRectF mapBufferTarget; // the rect in absolute widget coordinates where the visible map portion/buffer will end up in
  22715. QPixmap mapBuffer;
  22716. if (useBuffer)
  22717. {
  22718. const double mapBufferPixelRatio = 3; // factor by which DPI is increased in embedded bitmaps
  22719. mapBufferTarget = painter->clipRegion().boundingRect();
  22720. mapBuffer = QPixmap((mapBufferTarget.size()*mapBufferPixelRatio).toSize());
  22721. mapBuffer.fill(Qt::transparent);
  22722. localPainter = new QCPPainter(&mapBuffer);
  22723. localPainter->scale(mapBufferPixelRatio, mapBufferPixelRatio);
  22724. localPainter->translate(-mapBufferTarget.topLeft());
  22725. }
  22726. QRectF imageRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
  22727. coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
  22728. // extend imageRect to contain outer halves/quarters of bordering/cornering pixels (cells are centered on map range boundary):
  22729. double halfCellWidth = 0; // in pixels
  22730. double halfCellHeight = 0; // in pixels
  22731. if (keyAxis()->orientation() == Qt::Horizontal)
  22732. {
  22733. if (mMapData->keySize() > 1)
  22734. halfCellWidth = 0.5*imageRect.width()/double((double)mMapData->keySize()-1.0);
  22735. if (mMapData->valueSize() > 1)
  22736. halfCellHeight = 0.5*imageRect.height()/double((double)mMapData->valueSize()-1.0);
  22737. } else // keyAxis orientation is Qt::Vertical
  22738. {
  22739. if (mMapData->keySize() > 1)
  22740. halfCellHeight = 0.5*imageRect.height()/double((double)mMapData->keySize()- 1.0);
  22741. if (mMapData->valueSize() > 1)
  22742. halfCellWidth = 0.5*imageRect.width()/double((double)mMapData->valueSize()- 1.0);
  22743. }
  22744. imageRect.adjust(-halfCellWidth, -halfCellHeight, halfCellWidth, halfCellHeight);
  22745. const bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed();
  22746. const bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed();
  22747. const bool smoothBackup = localPainter->renderHints().testFlag(QPainter::SmoothPixmapTransform);
  22748. localPainter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate);
  22749. QRegion clipBackup;
  22750. if (mTightBoundary)
  22751. {
  22752. clipBackup = localPainter->clipRegion();
  22753. QRectF tightClipRect = QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower),
  22754. coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized();
  22755. localPainter->setClipRect(tightClipRect, Qt::IntersectClip);
  22756. }
  22757. localPainter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY));
  22758. if (mTightBoundary)
  22759. localPainter->setClipRegion(clipBackup);
  22760. localPainter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup);
  22761. if (useBuffer) // localPainter painted to mapBuffer, so now draw buffer with original painter
  22762. {
  22763. delete localPainter;
  22764. painter->drawPixmap(mapBufferTarget.toRect(), mapBuffer);
  22765. }
  22766. }
  22767. /* inherits documentation from base class */
  22768. void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  22769. {
  22770. applyDefaultAntialiasingHint(painter);
  22771. // draw map thumbnail:
  22772. if (!mLegendIcon.isNull())
  22773. {
  22774. QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation);
  22775. QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height());
  22776. iconRect.moveCenter(rect.center());
  22777. painter->drawPixmap(iconRect.topLeft(), scaledIcon);
  22778. }
  22779. /*
  22780. // draw frame:
  22781. painter->setBrush(Qt::NoBrush);
  22782. painter->setPen(Qt::black);
  22783. painter->drawRect(rect.adjusted(1, 1, 0, 0));
  22784. */
  22785. }
  22786. /* end of 'src/plottables/plottable-colormap.cpp' */
  22787. /* including file 'src/plottables/plottable-financial.cpp' */
  22788. /* modified 2021-03-29T02:30:44, size 42914 */
  22789. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22790. //////////////////// QCPFinancialData
  22791. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22792. /*! \class QCPFinancialData
  22793. \brief Holds the data of one single data point for QCPFinancial.
  22794. The stored data is:
  22795. \li \a key: coordinate on the key axis of this data point (this is the \a mainKey and the \a sortKey)
  22796. \li \a open: The opening value at the data point (this is the \a mainValue)
  22797. \li \a high: The high/maximum value at the data point
  22798. \li \a low: The low/minimum value at the data point
  22799. \li \a close: The closing value at the data point
  22800. The container for storing multiple data points is \ref QCPFinancialDataContainer. It is a typedef
  22801. for \ref QCPDataContainer with \ref QCPFinancialData as the DataType template parameter. See the
  22802. documentation there for an explanation regarding the data type's generic methods.
  22803. \see QCPFinancialDataContainer
  22804. */
  22805. /* start documentation of inline functions */
  22806. /*! \fn double QCPFinancialData::sortKey() const
  22807. Returns the \a key member of this data point.
  22808. For a general explanation of what this method is good for in the context of the data container,
  22809. see the documentation of \ref QCPDataContainer.
  22810. */
  22811. /*! \fn static QCPFinancialData QCPFinancialData::fromSortKey(double sortKey)
  22812. Returns a data point with the specified \a sortKey. All other members are set to zero.
  22813. For a general explanation of what this method is good for in the context of the data container,
  22814. see the documentation of \ref QCPDataContainer.
  22815. */
  22816. /*! \fn static static bool QCPFinancialData::sortKeyIsMainKey()
  22817. Since the member \a key is both the data point key coordinate and the data ordering parameter,
  22818. this method returns true.
  22819. For a general explanation of what this method is good for in the context of the data container,
  22820. see the documentation of \ref QCPDataContainer.
  22821. */
  22822. /*! \fn double QCPFinancialData::mainKey() const
  22823. Returns the \a key member of this data point.
  22824. For a general explanation of what this method is good for in the context of the data container,
  22825. see the documentation of \ref QCPDataContainer.
  22826. */
  22827. /*! \fn double QCPFinancialData::mainValue() const
  22828. Returns the \a open member of this data point.
  22829. For a general explanation of what this method is good for in the context of the data container,
  22830. see the documentation of \ref QCPDataContainer.
  22831. */
  22832. /*! \fn QCPRange QCPFinancialData::valueRange() const
  22833. Returns a QCPRange spanning from the \a low to the \a high value of this data point.
  22834. For a general explanation of what this method is good for in the context of the data container,
  22835. see the documentation of \ref QCPDataContainer.
  22836. */
  22837. /* end documentation of inline functions */
  22838. /*!
  22839. Constructs a data point with key and all values set to zero.
  22840. */
  22841. QCPFinancialData::QCPFinancialData() :
  22842. key(0),
  22843. open(0),
  22844. high(0),
  22845. low(0),
  22846. close(0)
  22847. {
  22848. }
  22849. /*!
  22850. Constructs a data point with the specified \a key and OHLC values.
  22851. */
  22852. QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) :
  22853. key(key),
  22854. open(open),
  22855. high(high),
  22856. low(low),
  22857. close(close)
  22858. {
  22859. }
  22860. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22861. //////////////////// QCPFinancial
  22862. ////////////////////////////////////////////////////////////////////////////////////////////////////
  22863. /*! \class QCPFinancial
  22864. \brief A plottable representing a financial stock chart
  22865. \image html QCPFinancial.png
  22866. This plottable represents time series data binned to certain intervals, mainly used for stock
  22867. charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be
  22868. set via \ref setChartStyle.
  22869. The data is passed via \ref setData as a set of open/high/low/close values at certain keys
  22870. (typically times). This means the data must be already binned appropriately. If data is only
  22871. available as a series of values (e.g. \a price against \a time), you can use the static
  22872. convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed
  22873. to \ref setData.
  22874. The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and \ref
  22875. setWidthType. A typical choice is to set the width type to \ref wtPlotCoords (the default) and
  22876. the width to (or slightly less than) one time bin interval width.
  22877. \section qcpfinancial-appearance Changing the appearance
  22878. Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored,
  22879. lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush).
  22880. If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are
  22881. represented with a different pen and brush than negative changes (\a close < \a open). These can
  22882. be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref
  22883. setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection
  22884. however, the normal selected pen/brush (provided by the \ref selectionDecorator) is used,
  22885. irrespective of whether the chart is single- or two-colored.
  22886. \section qcpfinancial-usage Usage
  22887. Like all data representing objects in QCustomPlot, the QCPFinancial is a plottable
  22888. (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies
  22889. (QCustomPlot::plottable, QCustomPlot::removePlottable, etc.)
  22890. Usually, you first create an instance:
  22891. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-1
  22892. which registers it with the QCustomPlot instance of the passed axes. Note that this QCustomPlot
  22893. instance takes ownership of the plottable, so do not delete it manually but use
  22894. QCustomPlot::removePlottable() instead. The newly created plottable can be modified, e.g.:
  22895. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-creation-2
  22896. Here we have used the static helper method \ref timeSeriesToOhlc, to turn a time-price data
  22897. series into a 24-hour binned open-high-low-close data series as QCPFinancial uses.
  22898. */
  22899. /* start of documentation of inline functions */
  22900. /*! \fn QCPFinancialDataContainer *QCPFinancial::data() const
  22901. Returns a pointer to the internal data storage of type \ref QCPFinancialDataContainer. You may
  22902. use it to directly manipulate the data, which may be more convenient and faster than using the
  22903. regular \ref setData or \ref addData methods, in certain situations.
  22904. */
  22905. /* end of documentation of inline functions */
  22906. /*!
  22907. Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  22908. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  22909. the same orientation. If either of these restrictions is violated, a corresponding message is
  22910. printed to the debug output (qDebug), the construction is not aborted, though.
  22911. The created QCPFinancial is automatically registered with the QCustomPlot instance inferred from \a
  22912. keyAxis. This QCustomPlot instance takes ownership of the QCPFinancial, so do not delete it manually
  22913. but use QCustomPlot::removePlottable() instead.
  22914. */
  22915. QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  22916. QCPAbstractPlottable1D<QCPFinancialData>(keyAxis, valueAxis),
  22917. mChartStyle(csCandlestick),
  22918. mWidth(0.5),
  22919. mWidthType(wtPlotCoords),
  22920. mTwoColored(true),
  22921. mBrushPositive(QBrush(QColor(50, 160, 0))),
  22922. mBrushNegative(QBrush(QColor(180, 0, 15))),
  22923. mPenPositive(QPen(QColor(40, 150, 0))),
  22924. mPenNegative(QPen(QColor(170, 5, 5)))
  22925. {
  22926. mSelectionDecorator->setBrush(QBrush(QColor(160, 160, 255)));
  22927. }
  22928. QCPFinancial::~QCPFinancial()
  22929. {
  22930. }
  22931. /*! \overload
  22932. Replaces the current data container with the provided \a data container.
  22933. Since a QSharedPointer is used, multiple QCPFinancials may share the same data container safely.
  22934. Modifying the data in the container will then affect all financials that share the container.
  22935. Sharing can be achieved by simply exchanging the data containers wrapped in shared pointers:
  22936. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-1
  22937. If you do not wish to share containers, but create a copy from an existing container, rather use
  22938. the \ref QCPDataContainer<DataType>::set method on the financial's data container directly:
  22939. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpfinancial-datasharing-2
  22940. \see addData, timeSeriesToOhlc
  22941. */
  22942. void QCPFinancial::setData(QSharedPointer<QCPFinancialDataContainer> data)
  22943. {
  22944. mDataContainer = data;
  22945. }
  22946. /*! \overload
  22947. Replaces the current data with the provided points in \a keys, \a open, \a high, \a low and \a
  22948. close. The provided vectors should have equal length. Else, the number of added points will be
  22949. the size of the smallest vector.
  22950. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  22951. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  22952. \see addData, timeSeriesToOhlc
  22953. */
  22954. 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)
  22955. {
  22956. mDataContainer->clear();
  22957. addData(keys, open, high, low, close, alreadySorted);
  22958. }
  22959. /*!
  22960. Sets which representation style shall be used to display the OHLC data.
  22961. */
  22962. void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style)
  22963. {
  22964. mChartStyle = style;
  22965. }
  22966. /*!
  22967. Sets the width of the individual bars/candlesticks to \a width in plot key coordinates.
  22968. A typical choice is to set it to (or slightly less than) one bin interval width.
  22969. */
  22970. void QCPFinancial::setWidth(double width)
  22971. {
  22972. mWidth = width;
  22973. }
  22974. /*!
  22975. Sets how the width of the financial bars is defined. See the documentation of \ref WidthType for
  22976. an explanation of the possible values for \a widthType.
  22977. The default value is \ref wtPlotCoords.
  22978. \see setWidth
  22979. */
  22980. void QCPFinancial::setWidthType(QCPFinancial::WidthType widthType)
  22981. {
  22982. mWidthType = widthType;
  22983. }
  22984. /*!
  22985. Sets whether this chart shall contrast positive from negative trends per data point by using two
  22986. separate colors to draw the respective bars/candlesticks.
  22987. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  22988. setBrush).
  22989. \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative
  22990. */
  22991. void QCPFinancial::setTwoColored(bool twoColored)
  22992. {
  22993. mTwoColored = twoColored;
  22994. }
  22995. /*!
  22996. If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
  22997. of data points with a positive trend (i.e. bars/candlesticks with close >= open).
  22998. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  22999. setBrush).
  23000. \see setBrushNegative, setPenPositive, setPenNegative
  23001. */
  23002. void QCPFinancial::setBrushPositive(const QBrush &brush)
  23003. {
  23004. mBrushPositive = brush;
  23005. }
  23006. /*!
  23007. If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills
  23008. of data points with a negative trend (i.e. bars/candlesticks with close < open).
  23009. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23010. setBrush).
  23011. \see setBrushPositive, setPenNegative, setPenPositive
  23012. */
  23013. void QCPFinancial::setBrushNegative(const QBrush &brush)
  23014. {
  23015. mBrushNegative = brush;
  23016. }
  23017. /*!
  23018. If \ref setTwoColored is set to true, this function controls the pen that is used to draw
  23019. outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open).
  23020. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23021. setBrush).
  23022. \see setPenNegative, setBrushPositive, setBrushNegative
  23023. */
  23024. void QCPFinancial::setPenPositive(const QPen &pen)
  23025. {
  23026. mPenPositive = pen;
  23027. }
  23028. /*!
  23029. If \ref setTwoColored is set to true, this function controls the pen that is used to draw
  23030. outlines of data points with a negative trend (i.e. bars/candlesticks with close < open).
  23031. If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref
  23032. setBrush).
  23033. \see setPenPositive, setBrushNegative, setBrushPositive
  23034. */
  23035. void QCPFinancial::setPenNegative(const QPen &pen)
  23036. {
  23037. mPenNegative = pen;
  23038. }
  23039. /*! \overload
  23040. Adds the provided points in \a keys, \a open, \a high, \a low and \a close to the current data.
  23041. The provided vectors should have equal length. Else, the number of added points will be the size
  23042. of the smallest vector.
  23043. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  23044. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  23045. Alternatively, you can also access and modify the data directly via the \ref data method, which
  23046. returns a pointer to the internal data container.
  23047. \see timeSeriesToOhlc
  23048. */
  23049. 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)
  23050. {
  23051. if (keys.size() != open.size() || open.size() != high.size() || high.size() != low.size() || low.size() != close.size() || close.size() != keys.size())
  23052. qDebug() << Q_FUNC_INFO << "keys, open, high, low, close have different sizes:" << keys.size() << open.size() << high.size() << low.size() << close.size();
  23053. const int n = qMin(keys.size(), qMin(open.size(), qMin(high.size(), qMin(low.size(), close.size()))));
  23054. QVector<QCPFinancialData> tempData(n);
  23055. QVector<QCPFinancialData>::iterator it = tempData.begin();
  23056. const QVector<QCPFinancialData>::iterator itEnd = tempData.end();
  23057. int i = 0;
  23058. while (it != itEnd)
  23059. {
  23060. it->key = keys[i];
  23061. it->open = open[i];
  23062. it->high = high[i];
  23063. it->low = low[i];
  23064. it->close = close[i];
  23065. ++it;
  23066. ++i;
  23067. }
  23068. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  23069. }
  23070. /*! \overload
  23071. Adds the provided data point as \a key, \a open, \a high, \a low and \a close to the current
  23072. data.
  23073. Alternatively, you can also access and modify the data directly via the \ref data method, which
  23074. returns a pointer to the internal data container.
  23075. \see timeSeriesToOhlc
  23076. */
  23077. void QCPFinancial::addData(double key, double open, double high, double low, double close)
  23078. {
  23079. mDataContainer->add(QCPFinancialData(key, open, high, low, close));
  23080. }
  23081. /*!
  23082. \copydoc QCPPlottableInterface1D::selectTestRect
  23083. */
  23084. QCPDataSelection QCPFinancial::selectTestRect(const QRectF &rect, bool onlySelectable) const
  23085. {
  23086. QCPDataSelection result;
  23087. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23088. return result;
  23089. if (!mKeyAxis || !mValueAxis)
  23090. return result;
  23091. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  23092. getVisibleDataBounds(visibleBegin, visibleEnd);
  23093. for (QCPFinancialDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  23094. {
  23095. if (rect.intersects(selectionHitBox(it)))
  23096. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  23097. }
  23098. result.simplify();
  23099. return result;
  23100. }
  23101. /*!
  23102. Implements a selectTest specific to this plottable's point geometry.
  23103. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  23104. point to \a pos.
  23105. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  23106. */
  23107. double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  23108. {
  23109. Q_UNUSED(details)
  23110. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23111. return -1;
  23112. if (!mKeyAxis || !mValueAxis)
  23113. return -1;
  23114. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  23115. {
  23116. // get visible data range:
  23117. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  23118. QCPFinancialDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  23119. getVisibleDataBounds(visibleBegin, visibleEnd);
  23120. // perform select test according to configured style:
  23121. double result = -1;
  23122. switch (mChartStyle)
  23123. {
  23124. case QCPFinancial::csOhlc:
  23125. result = ohlcSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
  23126. case QCPFinancial::csCandlestick:
  23127. result = candlestickSelectTest(pos, visibleBegin, visibleEnd, closestDataPoint); break;
  23128. }
  23129. if (details)
  23130. {
  23131. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  23132. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  23133. }
  23134. return result;
  23135. }
  23136. return -1;
  23137. }
  23138. /* inherits documentation from base class */
  23139. QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  23140. {
  23141. QCPRange range = mDataContainer->keyRange(foundRange, inSignDomain);
  23142. // determine exact range by including width of bars/flags:
  23143. if (foundRange)
  23144. {
  23145. if (inSignDomain != QCP::SignDomain::sdPositive || range.lower-mWidth*0.5 > 0)
  23146. range.lower -= mWidth*0.5;
  23147. if (inSignDomain != QCP::SignDomain::sdNegative || range.upper+mWidth*0.5 < 0)
  23148. range.upper += mWidth*0.5;
  23149. }
  23150. return range;
  23151. }
  23152. /* inherits documentation from base class */
  23153. QCPRange QCPFinancial::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  23154. {
  23155. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  23156. }
  23157. /*!
  23158. A convenience function that converts time series data (\a value against \a time) to OHLC binned
  23159. data points. The return value can then be passed on to \ref QCPFinancialDataContainer::set(const
  23160. QCPFinancialDataContainer&).
  23161. The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given.
  23162. For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour
  23163. each, set \a timeBinSize to 3600.
  23164. \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The
  23165. value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys.
  23166. It merely defines the mathematical offset/phase of the bins that will be used to process the
  23167. data.
  23168. */
  23169. QCPFinancialDataContainer QCPFinancial::timeSeriesToOhlc(const QVector<double> &time, const QVector<double> &value, double timeBinSize, double timeBinOffset)
  23170. {
  23171. QCPFinancialDataContainer data;
  23172. int count = qMin(time.size(), value.size());
  23173. if (count == 0)
  23174. return QCPFinancialDataContainer();
  23175. QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first());
  23176. int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5);
  23177. for (int i=0; i<count; ++i)
  23178. {
  23179. int index = qFloor((time.at(i)-timeBinOffset)/timeBinSize+0.5);
  23180. if (currentBinIndex == index) // data point still in current bin, extend high/low:
  23181. {
  23182. if (value.at(i) < currentBinData.low) currentBinData.low = value.at(i);
  23183. if (value.at(i) > currentBinData.high) currentBinData.high = value.at(i);
  23184. if (i == count-1) // last data point is in current bin, finalize bin:
  23185. {
  23186. currentBinData.close = value.at(i);
  23187. currentBinData.key = timeBinOffset+(index)*timeBinSize;
  23188. data.add(currentBinData);
  23189. }
  23190. } else // data point not anymore in current bin, set close of old and open of new bin, and add old to map:
  23191. {
  23192. // finalize current bin:
  23193. currentBinData.close = value.at(i-1);
  23194. currentBinData.key = timeBinOffset+(index-1)*timeBinSize;
  23195. data.add(currentBinData);
  23196. // start next bin:
  23197. currentBinIndex = index;
  23198. currentBinData.open = value.at(i);
  23199. currentBinData.high = value.at(i);
  23200. currentBinData.low = value.at(i);
  23201. }
  23202. }
  23203. return data;
  23204. }
  23205. /* inherits documentation from base class */
  23206. void QCPFinancial::draw(QCPPainter *painter)
  23207. {
  23208. // get visible data range:
  23209. QCPFinancialDataContainer::const_iterator visibleBegin, visibleEnd;
  23210. getVisibleDataBounds(visibleBegin, visibleEnd);
  23211. // loop over and draw segments of unselected/selected data:
  23212. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  23213. getDataSegments(selectedSegments, unselectedSegments);
  23214. allSegments << unselectedSegments << selectedSegments;
  23215. for (int i=0; i<allSegments.size(); ++i)
  23216. {
  23217. bool isSelectedSegment = i >= unselectedSegments.size();
  23218. QCPFinancialDataContainer::const_iterator begin = visibleBegin;
  23219. QCPFinancialDataContainer::const_iterator end = visibleEnd;
  23220. mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
  23221. if (begin == end)
  23222. continue;
  23223. // draw data segment according to configured style:
  23224. switch (mChartStyle)
  23225. {
  23226. case QCPFinancial::csOhlc:
  23227. drawOhlcPlot(painter, begin, end, isSelectedSegment); break;
  23228. case QCPFinancial::csCandlestick:
  23229. drawCandlestickPlot(painter, begin, end, isSelectedSegment); break;
  23230. }
  23231. }
  23232. // draw other selection decoration that isn't just line/scatter pens and brushes:
  23233. if (mSelectionDecorator)
  23234. mSelectionDecorator->drawDecoration(painter, selection());
  23235. }
  23236. /* inherits documentation from base class */
  23237. void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  23238. {
  23239. painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing
  23240. if (mChartStyle == csOhlc)
  23241. {
  23242. if (mTwoColored)
  23243. {
  23244. // draw upper left half icon with positive color:
  23245. painter->setBrush(mBrushPositive);
  23246. painter->setPen(mPenPositive);
  23247. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
  23248. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23249. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  23250. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  23251. // draw bottom right half icon with negative color:
  23252. painter->setBrush(mBrushNegative);
  23253. painter->setPen(mPenNegative);
  23254. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
  23255. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23256. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  23257. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  23258. } else
  23259. {
  23260. painter->setBrush(mBrush);
  23261. painter->setPen(mPen);
  23262. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23263. painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft()));
  23264. painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft()));
  23265. }
  23266. } else if (mChartStyle == csCandlestick)
  23267. {
  23268. if (mTwoColored)
  23269. {
  23270. // draw upper left half icon with positive color:
  23271. painter->setBrush(mBrushPositive);
  23272. painter->setPen(mPenPositive);
  23273. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint()));
  23274. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  23275. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23276. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  23277. // draw bottom right half icon with negative color:
  23278. painter->setBrush(mBrushNegative);
  23279. painter->setPen(mPenNegative);
  23280. painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint()));
  23281. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  23282. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23283. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  23284. } else
  23285. {
  23286. painter->setBrush(mBrush);
  23287. painter->setPen(mPen);
  23288. painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft()));
  23289. painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft()));
  23290. painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft()));
  23291. }
  23292. }
  23293. }
  23294. /*! \internal
  23295. Draws the data from \a begin to \a end-1 as OHLC bars with the provided \a painter.
  23296. This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc.
  23297. */
  23298. void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
  23299. {
  23300. QCPAxis *keyAxis = mKeyAxis.data();
  23301. QCPAxis *valueAxis = mValueAxis.data();
  23302. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  23303. if (keyAxis->orientation() == Qt::Horizontal)
  23304. {
  23305. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23306. {
  23307. if (isSelected && mSelectionDecorator)
  23308. mSelectionDecorator->applyPen(painter);
  23309. else if (mTwoColored)
  23310. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23311. else
  23312. painter->setPen(mPen);
  23313. double keyPixel = keyAxis->coordToPixel(it->key);
  23314. double openPixel = valueAxis->coordToPixel(it->open);
  23315. double closePixel = valueAxis->coordToPixel(it->close);
  23316. // draw backbone:
  23317. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(it->low)));
  23318. // draw open:
  23319. double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
  23320. painter->drawLine(QPointF(keyPixel-pixelWidth, openPixel), QPointF(keyPixel, openPixel));
  23321. // draw close:
  23322. painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+pixelWidth, closePixel));
  23323. }
  23324. } else
  23325. {
  23326. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23327. {
  23328. if (isSelected && mSelectionDecorator)
  23329. mSelectionDecorator->applyPen(painter);
  23330. else if (mTwoColored)
  23331. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23332. else
  23333. painter->setPen(mPen);
  23334. double keyPixel = keyAxis->coordToPixel(it->key);
  23335. double openPixel = valueAxis->coordToPixel(it->open);
  23336. double closePixel = valueAxis->coordToPixel(it->close);
  23337. // draw backbone:
  23338. painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(it->low), keyPixel));
  23339. // draw open:
  23340. double pixelWidth = getPixelWidth(it->key, keyPixel); // sign of this makes sure open/close are on correct sides
  23341. painter->drawLine(QPointF(openPixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel));
  23342. // draw close:
  23343. painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+pixelWidth));
  23344. }
  23345. }
  23346. }
  23347. /*! \internal
  23348. Draws the data from \a begin to \a end-1 as Candlesticks with the provided \a painter.
  23349. This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick.
  23350. */
  23351. void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, bool isSelected)
  23352. {
  23353. QCPAxis *keyAxis = mKeyAxis.data();
  23354. QCPAxis *valueAxis = mValueAxis.data();
  23355. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  23356. if (keyAxis->orientation() == Qt::Horizontal)
  23357. {
  23358. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23359. {
  23360. if (isSelected && mSelectionDecorator)
  23361. {
  23362. mSelectionDecorator->applyPen(painter);
  23363. mSelectionDecorator->applyBrush(painter);
  23364. } else if (mTwoColored)
  23365. {
  23366. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23367. painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
  23368. } else
  23369. {
  23370. painter->setPen(mPen);
  23371. painter->setBrush(mBrush);
  23372. }
  23373. double keyPixel = keyAxis->coordToPixel(it->key);
  23374. double openPixel = valueAxis->coordToPixel(it->open);
  23375. double closePixel = valueAxis->coordToPixel(it->close);
  23376. // draw high:
  23377. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
  23378. // draw low:
  23379. painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it->low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
  23380. // draw open-close box:
  23381. double pixelWidth = getPixelWidth(it->key, keyPixel);
  23382. painter->drawRect(QRectF(QPointF(keyPixel-pixelWidth, closePixel), QPointF(keyPixel+pixelWidth, openPixel)));
  23383. }
  23384. } else // keyAxis->orientation() == Qt::Vertical
  23385. {
  23386. for (QCPFinancialDataContainer::const_iterator it = begin; it != end; ++it)
  23387. {
  23388. if (isSelected && mSelectionDecorator)
  23389. {
  23390. mSelectionDecorator->applyPen(painter);
  23391. mSelectionDecorator->applyBrush(painter);
  23392. } else if (mTwoColored)
  23393. {
  23394. painter->setPen(it->close >= it->open ? mPenPositive : mPenNegative);
  23395. painter->setBrush(it->close >= it->open ? mBrushPositive : mBrushNegative);
  23396. } else
  23397. {
  23398. painter->setPen(mPen);
  23399. painter->setBrush(mBrush);
  23400. }
  23401. double keyPixel = keyAxis->coordToPixel(it->key);
  23402. double openPixel = valueAxis->coordToPixel(it->open);
  23403. double closePixel = valueAxis->coordToPixel(it->close);
  23404. // draw high:
  23405. painter->drawLine(QPointF(valueAxis->coordToPixel(it->high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
  23406. // draw low:
  23407. painter->drawLine(QPointF(valueAxis->coordToPixel(it->low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
  23408. // draw open-close box:
  23409. double pixelWidth = getPixelWidth(it->key, keyPixel);
  23410. painter->drawRect(QRectF(QPointF(closePixel, keyPixel-pixelWidth), QPointF(openPixel, keyPixel+pixelWidth)));
  23411. }
  23412. }
  23413. }
  23414. /*! \internal
  23415. This function is used to determine the width of the bar at coordinate \a key, according to the
  23416. specified width (\ref setWidth) and width type (\ref setWidthType). Provide the pixel position of
  23417. \a key in \a keyPixel (because usually this was already calculated via \ref QCPAxis::coordToPixel
  23418. when this function is called).
  23419. It returns the number of pixels the bar extends to higher keys, relative to the \a key
  23420. coordinate. So with a non-reversed horizontal axis, the return value is positive. With a reversed
  23421. horizontal axis, the return value is negative. This is important so the open/close flags on the
  23422. \ref csOhlc bar are drawn to the correct side.
  23423. */
  23424. double QCPFinancial::getPixelWidth(double key, double keyPixel) const
  23425. {
  23426. double result = 0;
  23427. switch (mWidthType)
  23428. {
  23429. case wtAbsolute:
  23430. {
  23431. if (mKeyAxis)
  23432. result = mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  23433. break;
  23434. }
  23435. case wtAxisRectRatio:
  23436. {
  23437. if (mKeyAxis && mKeyAxis.data()->axisRect())
  23438. {
  23439. if (mKeyAxis.data()->orientation() == Qt::Horizontal)
  23440. result = mKeyAxis.data()->axisRect()->width()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  23441. else
  23442. result = mKeyAxis.data()->axisRect()->height()*mWidth*0.5*mKeyAxis.data()->pixelOrientation();
  23443. } else
  23444. qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined";
  23445. break;
  23446. }
  23447. case wtPlotCoords:
  23448. {
  23449. if (mKeyAxis)
  23450. result = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel;
  23451. else
  23452. qDebug() << Q_FUNC_INFO << "No key axis defined";
  23453. break;
  23454. }
  23455. }
  23456. return result;
  23457. }
  23458. /*! \internal
  23459. This method is a helper function for \ref selectTest. It is used to test for selection when the
  23460. chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end.
  23461. Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
  23462. representation of the plottable, and \a closestDataPoint will point to the respective data point.
  23463. */
  23464. double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
  23465. {
  23466. closestDataPoint = mDataContainer->constEnd();
  23467. QCPAxis *keyAxis = mKeyAxis.data();
  23468. QCPAxis *valueAxis = mValueAxis.data();
  23469. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  23470. double minDistSqr = (std::numeric_limits<double>::max)();
  23471. if (keyAxis->orientation() == Qt::Horizontal)
  23472. {
  23473. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23474. {
  23475. double keyPixel = keyAxis->coordToPixel(it->key);
  23476. // calculate distance to backbone:
  23477. double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)));
  23478. if (currentDistSqr < minDistSqr)
  23479. {
  23480. minDistSqr = currentDistSqr;
  23481. closestDataPoint = it;
  23482. }
  23483. }
  23484. } else // keyAxis->orientation() == Qt::Vertical
  23485. {
  23486. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23487. {
  23488. double keyPixel = keyAxis->coordToPixel(it->key);
  23489. // calculate distance to backbone:
  23490. double currentDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel));
  23491. if (currentDistSqr < minDistSqr)
  23492. {
  23493. minDistSqr = currentDistSqr;
  23494. closestDataPoint = it;
  23495. }
  23496. }
  23497. }
  23498. return qSqrt(minDistSqr);
  23499. }
  23500. /*! \internal
  23501. This method is a helper function for \ref selectTest. It is used to test for selection when the
  23502. chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a
  23503. end.
  23504. Like \ref selectTest, this method returns the shortest distance of \a pos to the graphical
  23505. representation of the plottable, and \a closestDataPoint will point to the respective data point.
  23506. */
  23507. double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataContainer::const_iterator &begin, const QCPFinancialDataContainer::const_iterator &end, QCPFinancialDataContainer::const_iterator &closestDataPoint) const
  23508. {
  23509. closestDataPoint = mDataContainer->constEnd();
  23510. QCPAxis *keyAxis = mKeyAxis.data();
  23511. QCPAxis *valueAxis = mValueAxis.data();
  23512. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; }
  23513. double minDistSqr = (std::numeric_limits<double>::max)();
  23514. if (keyAxis->orientation() == Qt::Horizontal)
  23515. {
  23516. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23517. {
  23518. double currentDistSqr;
  23519. // determine whether pos is in open-close-box:
  23520. QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
  23521. QCPRange boxValueRange(it->close, it->open);
  23522. double posKey, posValue;
  23523. pixelsToCoords(pos, posKey, posValue);
  23524. if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
  23525. {
  23526. currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  23527. } else
  23528. {
  23529. // calculate distance to high/low lines:
  23530. double keyPixel = keyAxis->coordToPixel(it->key);
  23531. double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->high)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMax(it->open, it->close))));
  23532. double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(keyPixel, valueAxis->coordToPixel(it->low)), QCPVector2D(keyPixel, valueAxis->coordToPixel(qMin(it->open, it->close))));
  23533. currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
  23534. }
  23535. if (currentDistSqr < minDistSqr)
  23536. {
  23537. minDistSqr = currentDistSqr;
  23538. closestDataPoint = it;
  23539. }
  23540. }
  23541. } else // keyAxis->orientation() == Qt::Vertical
  23542. {
  23543. for (QCPFinancialDataContainer::const_iterator it=begin; it!=end; ++it)
  23544. {
  23545. double currentDistSqr;
  23546. // determine whether pos is in open-close-box:
  23547. QCPRange boxKeyRange(it->key-mWidth*0.5, it->key+mWidth*0.5);
  23548. QCPRange boxValueRange(it->close, it->open);
  23549. double posKey, posValue;
  23550. pixelsToCoords(pos, posKey, posValue);
  23551. if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box
  23552. {
  23553. currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99;
  23554. } else
  23555. {
  23556. // calculate distance to high/low lines:
  23557. double keyPixel = keyAxis->coordToPixel(it->key);
  23558. double highLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->high), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMax(it->open, it->close)), keyPixel));
  23559. double lowLineDistSqr = QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(valueAxis->coordToPixel(it->low), keyPixel), QCPVector2D(valueAxis->coordToPixel(qMin(it->open, it->close)), keyPixel));
  23560. currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr);
  23561. }
  23562. if (currentDistSqr < minDistSqr)
  23563. {
  23564. minDistSqr = currentDistSqr;
  23565. closestDataPoint = it;
  23566. }
  23567. }
  23568. }
  23569. return qSqrt(minDistSqr);
  23570. }
  23571. /*! \internal
  23572. called by the drawing methods to determine which data (key) range is visible at the current key
  23573. axis range setting, so only that needs to be processed.
  23574. \a begin returns an iterator to the lowest data point that needs to be taken into account when
  23575. plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a
  23576. begin may still be just outside the visible range.
  23577. \a end returns the iterator just above the highest data point that needs to be taken into
  23578. account. Same as before, \a end may also lie just outside of the visible range
  23579. if the plottable contains no data, both \a begin and \a end point to \c constEnd.
  23580. */
  23581. void QCPFinancial::getVisibleDataBounds(QCPFinancialDataContainer::const_iterator &begin, QCPFinancialDataContainer::const_iterator &end) const
  23582. {
  23583. if (!mKeyAxis)
  23584. {
  23585. qDebug() << Q_FUNC_INFO << "invalid key axis";
  23586. begin = mDataContainer->constEnd();
  23587. end = mDataContainer->constEnd();
  23588. return;
  23589. }
  23590. begin = mDataContainer->findBegin(mKeyAxis.data()->range().lower-mWidth*0.5); // subtract half width of ohlc/candlestick to include partially visible data points
  23591. end = mDataContainer->findEnd(mKeyAxis.data()->range().upper+mWidth*0.5); // add half width of ohlc/candlestick to include partially visible data points
  23592. }
  23593. /*! \internal
  23594. Returns the hit box in pixel coordinates that will be used for data selection with the selection
  23595. rect (\ref selectTestRect), of the data point given by \a it.
  23596. */
  23597. QRectF QCPFinancial::selectionHitBox(QCPFinancialDataContainer::const_iterator it) const
  23598. {
  23599. QCPAxis *keyAxis = mKeyAxis.data();
  23600. QCPAxis *valueAxis = mValueAxis.data();
  23601. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return {}; }
  23602. double keyPixel = keyAxis->coordToPixel(it->key);
  23603. double highPixel = valueAxis->coordToPixel(it->high);
  23604. double lowPixel = valueAxis->coordToPixel(it->low);
  23605. double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it->key-mWidth*0.5);
  23606. if (keyAxis->orientation() == Qt::Horizontal)
  23607. return QRectF(keyPixel-keyWidthPixels, highPixel, keyWidthPixels*2, lowPixel-highPixel).normalized();
  23608. else
  23609. return QRectF(highPixel, keyPixel-keyWidthPixels, lowPixel-highPixel, keyWidthPixels*2).normalized();
  23610. }
  23611. /* end of 'src/plottables/plottable-financial.cpp' */
  23612. /* including file 'src/plottables/plottable-errorbar.cpp' */
  23613. /* modified 2021-03-29T02:30:44, size 37679 */
  23614. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23615. //////////////////// QCPErrorBarsData
  23616. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23617. /*! \class QCPErrorBarsData
  23618. \brief Holds the data of one single error bar for QCPErrorBars.
  23619. The stored data is:
  23620. \li \a errorMinus: how much the error bar extends towards negative coordinates from the data
  23621. point position
  23622. \li \a errorPlus: how much the error bar extends towards positive coordinates from the data point
  23623. position
  23624. The container for storing the error bar information is \ref QCPErrorBarsDataContainer. It is a
  23625. typedef for <tt>QVector<\ref QCPErrorBarsData></tt>.
  23626. \see QCPErrorBarsDataContainer
  23627. */
  23628. /*!
  23629. Constructs an error bar with errors set to zero.
  23630. */
  23631. QCPErrorBarsData::QCPErrorBarsData() :
  23632. errorMinus(0),
  23633. errorPlus(0)
  23634. {
  23635. }
  23636. /*!
  23637. Constructs an error bar with equal \a error in both negative and positive direction.
  23638. */
  23639. QCPErrorBarsData::QCPErrorBarsData(double error) :
  23640. errorMinus(error),
  23641. errorPlus(error)
  23642. {
  23643. }
  23644. /*!
  23645. Constructs an error bar with negative and positive errors set to \a errorMinus and \a errorPlus,
  23646. respectively.
  23647. */
  23648. QCPErrorBarsData::QCPErrorBarsData(double errorMinus, double errorPlus) :
  23649. errorMinus(errorMinus),
  23650. errorPlus(errorPlus)
  23651. {
  23652. }
  23653. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23654. //////////////////// QCPErrorBars
  23655. ////////////////////////////////////////////////////////////////////////////////////////////////////
  23656. /*! \class QCPErrorBars
  23657. \brief A plottable that adds a set of error bars to other plottables.
  23658. \image html QCPErrorBars.png
  23659. The \ref QCPErrorBars plottable can be attached to other one-dimensional plottables (e.g. \ref
  23660. QCPGraph, \ref QCPCurve, \ref QCPBars, etc.) and equips them with error bars.
  23661. Use \ref setDataPlottable to define for which plottable the \ref QCPErrorBars shall display the
  23662. error bars. The orientation of the error bars can be controlled with \ref setErrorType.
  23663. By using \ref setData, you can supply the actual error data, either as symmetric error or
  23664. plus/minus asymmetric errors. \ref QCPErrorBars only stores the error data. The absolute
  23665. key/value position of each error bar will be adopted from the configured data plottable. The
  23666. error data of the \ref QCPErrorBars are associated one-to-one via their index to the data points
  23667. of the data plottable. You can directly access and manipulate the error bar data via \ref data.
  23668. Set either of the plus/minus errors to NaN (<tt>qQNaN()</tt> or
  23669. <tt>std::numeric_limits<double>::quiet_NaN()</tt>) to not show the respective error bar on the data point at
  23670. that index.
  23671. \section qcperrorbars-appearance Changing the appearance
  23672. The appearance of the error bars is defined by the pen (\ref setPen), and the width of the
  23673. whiskers (\ref setWhiskerWidth). Further, the error bar backbones may leave a gap around the data
  23674. point center to prevent that error bars are drawn too close to or even through scatter points.
  23675. This gap size can be controlled via \ref setSymbolGap.
  23676. */
  23677. /* start of documentation of inline functions */
  23678. /*! \fn QSharedPointer<QCPErrorBarsDataContainer> QCPErrorBars::data() const
  23679. Returns a shared pointer to the internal data storage of type \ref QCPErrorBarsDataContainer. You
  23680. may use it to directly manipulate the error values, which may be more convenient and faster than
  23681. using the regular \ref setData methods.
  23682. */
  23683. /* end of documentation of inline functions */
  23684. /*!
  23685. Constructs an error bars plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value
  23686. axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have
  23687. the same orientation. If either of these restrictions is violated, a corresponding message is
  23688. printed to the debug output (qDebug), the construction is not aborted, though.
  23689. It is also important that the \a keyAxis and \a valueAxis are the same for the error bars
  23690. plottable and the data plottable that the error bars shall be drawn on (\ref setDataPlottable).
  23691. The created \ref QCPErrorBars is automatically registered with the QCustomPlot instance inferred
  23692. from \a keyAxis. This QCustomPlot instance takes ownership of the \ref QCPErrorBars, so do not
  23693. delete it manually but use \ref QCustomPlot::removePlottable() instead.
  23694. */
  23695. QCPErrorBars::QCPErrorBars(QCPAxis *keyAxis, QCPAxis *valueAxis) :
  23696. QCPAbstractPlottable(keyAxis, valueAxis),
  23697. mDataContainer(new QVector<QCPErrorBarsData>),
  23698. mErrorType(etValueError),
  23699. mWhiskerWidth(9),
  23700. mSymbolGap(10)
  23701. {
  23702. setPen(QPen(Qt::black, 0));
  23703. setBrush(Qt::NoBrush);
  23704. }
  23705. QCPErrorBars::~QCPErrorBars()
  23706. {
  23707. }
  23708. /*! \overload
  23709. Replaces the current data container with the provided \a data container.
  23710. Since a QSharedPointer is used, multiple \ref QCPErrorBars instances may share the same data
  23711. container safely. Modifying the data in the container will then affect all \ref QCPErrorBars
  23712. instances that share the container. Sharing can be achieved by simply exchanging the data
  23713. containers wrapped in shared pointers:
  23714. \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-1
  23715. If you do not wish to share containers, but create a copy from an existing container, assign the
  23716. data containers directly:
  23717. \snippet documentation/doc-code-snippets/mainwindow.cpp qcperrorbars-datasharing-2
  23718. (This uses different notation compared with other plottables, because the \ref QCPErrorBars
  23719. uses a \c QVector<QCPErrorBarsData> as its data container, instead of a \ref QCPDataContainer.)
  23720. \see addData
  23721. */
  23722. void QCPErrorBars::setData(QSharedPointer<QCPErrorBarsDataContainer> data)
  23723. {
  23724. mDataContainer = data;
  23725. }
  23726. /*! \overload
  23727. Sets symmetrical error values as specified in \a error. The errors will be associated one-to-one
  23728. by the data point index to the associated data plottable (\ref setDataPlottable).
  23729. You can directly access and manipulate the error bar data via \ref data.
  23730. \see addData
  23731. */
  23732. void QCPErrorBars::setData(const QVector<double> &error)
  23733. {
  23734. mDataContainer->clear();
  23735. addData(error);
  23736. }
  23737. /*! \overload
  23738. Sets asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
  23739. associated one-to-one by the data point index to the associated data plottable (\ref
  23740. setDataPlottable).
  23741. You can directly access and manipulate the error bar data via \ref data.
  23742. \see addData
  23743. */
  23744. void QCPErrorBars::setData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
  23745. {
  23746. mDataContainer->clear();
  23747. addData(errorMinus, errorPlus);
  23748. }
  23749. /*!
  23750. Sets the data plottable to which the error bars will be applied. The error values specified e.g.
  23751. via \ref setData will be associated one-to-one by the data point index to the data points of \a
  23752. plottable. This means that the error bars will adopt the key/value coordinates of the data point
  23753. with the same index.
  23754. The passed \a plottable must be a one-dimensional plottable, i.e. it must implement the \ref
  23755. QCPPlottableInterface1D. Further, it must not be a \ref QCPErrorBars instance itself. If either
  23756. of these restrictions is violated, a corresponding qDebug output is generated, and the data
  23757. plottable of this \ref QCPErrorBars instance is set to zero.
  23758. For proper display, care must also be taken that the key and value axes of the \a plottable match
  23759. those configured for this \ref QCPErrorBars instance.
  23760. */
  23761. void QCPErrorBars::setDataPlottable(QCPAbstractPlottable *plottable)
  23762. {
  23763. if (plottable && qobject_cast<QCPErrorBars*>(plottable))
  23764. {
  23765. mDataPlottable = nullptr;
  23766. qDebug() << Q_FUNC_INFO << "can't set another QCPErrorBars instance as data plottable";
  23767. return;
  23768. }
  23769. if (plottable && !plottable->interface1D())
  23770. {
  23771. mDataPlottable = nullptr;
  23772. qDebug() << Q_FUNC_INFO << "passed plottable doesn't implement 1d interface, can't associate with QCPErrorBars";
  23773. return;
  23774. }
  23775. mDataPlottable = plottable;
  23776. }
  23777. /*!
  23778. Sets in which orientation the error bars shall appear on the data points. If your data needs both
  23779. error dimensions, create two \ref QCPErrorBars with different \a type.
  23780. */
  23781. void QCPErrorBars::setErrorType(ErrorType type)
  23782. {
  23783. mErrorType = type;
  23784. }
  23785. /*!
  23786. Sets the width of the whiskers (the short bars at the end of the actual error bar backbones) to
  23787. \a pixels.
  23788. */
  23789. void QCPErrorBars::setWhiskerWidth(double pixels)
  23790. {
  23791. mWhiskerWidth = pixels;
  23792. }
  23793. /*!
  23794. Sets the gap diameter around the data points that will be left out when drawing the error bar
  23795. backbones. This gap prevents that error bars are drawn too close to or even through scatter
  23796. points.
  23797. */
  23798. void QCPErrorBars::setSymbolGap(double pixels)
  23799. {
  23800. mSymbolGap = pixels;
  23801. }
  23802. /*! \overload
  23803. Adds symmetrical error values as specified in \a error. The errors will be associated one-to-one
  23804. by the data point index to the associated data plottable (\ref setDataPlottable).
  23805. You can directly access and manipulate the error bar data via \ref data.
  23806. \see setData
  23807. */
  23808. void QCPErrorBars::addData(const QVector<double> &error)
  23809. {
  23810. addData(error, error);
  23811. }
  23812. /*! \overload
  23813. Adds asymmetrical errors as specified in \a errorMinus and \a errorPlus. The errors will be
  23814. associated one-to-one by the data point index to the associated data plottable (\ref
  23815. setDataPlottable).
  23816. You can directly access and manipulate the error bar data via \ref data.
  23817. \see setData
  23818. */
  23819. void QCPErrorBars::addData(const QVector<double> &errorMinus, const QVector<double> &errorPlus)
  23820. {
  23821. if (errorMinus.size() != errorPlus.size())
  23822. qDebug() << Q_FUNC_INFO << "minus and plus error vectors have different sizes:" << errorMinus.size() << errorPlus.size();
  23823. const int n = qMin(errorMinus.size(), errorPlus.size());
  23824. mDataContainer->reserve(n);
  23825. for (int i=0; i<n; ++i)
  23826. mDataContainer->append(QCPErrorBarsData(errorMinus.at(i), errorPlus.at(i)));
  23827. }
  23828. /*! \overload
  23829. Adds a single symmetrical error bar as specified in \a error. The errors will be associated
  23830. one-to-one by the data point index to the associated data plottable (\ref setDataPlottable).
  23831. You can directly access and manipulate the error bar data via \ref data.
  23832. \see setData
  23833. */
  23834. void QCPErrorBars::addData(double error)
  23835. {
  23836. mDataContainer->append(QCPErrorBarsData(error));
  23837. }
  23838. /*! \overload
  23839. Adds a single asymmetrical error bar as specified in \a errorMinus and \a errorPlus. The errors
  23840. will be associated one-to-one by the data point index to the associated data plottable (\ref
  23841. setDataPlottable).
  23842. You can directly access and manipulate the error bar data via \ref data.
  23843. \see setData
  23844. */
  23845. void QCPErrorBars::addData(double errorMinus, double errorPlus)
  23846. {
  23847. mDataContainer->append(QCPErrorBarsData(errorMinus, errorPlus));
  23848. }
  23849. /* inherits documentation from base class */
  23850. int QCPErrorBars::dataCount() const
  23851. {
  23852. return mDataContainer->size();
  23853. }
  23854. /* inherits documentation from base class */
  23855. double QCPErrorBars::dataMainKey(int index) const
  23856. {
  23857. if (mDataPlottable)
  23858. return mDataPlottable->interface1D()->dataMainKey(index);
  23859. else
  23860. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23861. return 0;
  23862. }
  23863. /* inherits documentation from base class */
  23864. double QCPErrorBars::dataSortKey(int index) const
  23865. {
  23866. if (mDataPlottable)
  23867. return mDataPlottable->interface1D()->dataSortKey(index);
  23868. else
  23869. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23870. return 0;
  23871. }
  23872. /* inherits documentation from base class */
  23873. double QCPErrorBars::dataMainValue(int index) const
  23874. {
  23875. if (mDataPlottable)
  23876. return mDataPlottable->interface1D()->dataMainValue(index);
  23877. else
  23878. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23879. return 0;
  23880. }
  23881. /* inherits documentation from base class */
  23882. QCPRange QCPErrorBars::dataValueRange(int index) const
  23883. {
  23884. if (mDataPlottable)
  23885. {
  23886. const double value = mDataPlottable->interface1D()->dataMainValue(index);
  23887. if (index >= 0 && index < mDataContainer->size() && mErrorType == etValueError)
  23888. return {value-mDataContainer->at(index).errorMinus, value+mDataContainer->at(index).errorPlus};
  23889. else
  23890. return {value, value};
  23891. } else
  23892. {
  23893. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23894. return {};
  23895. }
  23896. }
  23897. /* inherits documentation from base class */
  23898. QPointF QCPErrorBars::dataPixelPosition(int index) const
  23899. {
  23900. if (mDataPlottable)
  23901. return mDataPlottable->interface1D()->dataPixelPosition(index);
  23902. else
  23903. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23904. return {};
  23905. }
  23906. /* inherits documentation from base class */
  23907. bool QCPErrorBars::sortKeyIsMainKey() const
  23908. {
  23909. if (mDataPlottable)
  23910. {
  23911. return mDataPlottable->interface1D()->sortKeyIsMainKey();
  23912. } else
  23913. {
  23914. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23915. return true;
  23916. }
  23917. }
  23918. /*!
  23919. \copydoc QCPPlottableInterface1D::selectTestRect
  23920. */
  23921. QCPDataSelection QCPErrorBars::selectTestRect(const QRectF &rect, bool onlySelectable) const
  23922. {
  23923. QCPDataSelection result;
  23924. if (!mDataPlottable)
  23925. return result;
  23926. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23927. return result;
  23928. if (!mKeyAxis || !mValueAxis)
  23929. return result;
  23930. QCPErrorBarsDataContainer::const_iterator visibleBegin, visibleEnd;
  23931. getVisibleDataBounds(visibleBegin, visibleEnd, QCPDataRange(0, dataCount()));
  23932. QVector<QLineF> backbones, whiskers;
  23933. for (QCPErrorBarsDataContainer::const_iterator it=visibleBegin; it!=visibleEnd; ++it)
  23934. {
  23935. backbones.clear();
  23936. whiskers.clear();
  23937. getErrorBarLines(it, backbones, whiskers);
  23938. foreach (const QLineF &backbone, backbones)
  23939. {
  23940. if (rectIntersectsLine(rect, backbone))
  23941. {
  23942. result.addDataRange(QCPDataRange(int(it-mDataContainer->constBegin()), int(it-mDataContainer->constBegin()+1)), false);
  23943. break;
  23944. }
  23945. }
  23946. }
  23947. result.simplify();
  23948. return result;
  23949. }
  23950. /* inherits documentation from base class */
  23951. int QCPErrorBars::findBegin(double sortKey, bool expandedRange) const
  23952. {
  23953. if (mDataPlottable)
  23954. {
  23955. if (mDataContainer->isEmpty())
  23956. return 0;
  23957. int beginIndex = mDataPlottable->interface1D()->findBegin(sortKey, expandedRange);
  23958. if (beginIndex >= mDataContainer->size())
  23959. beginIndex = mDataContainer->size()-1;
  23960. return beginIndex;
  23961. } else
  23962. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23963. return 0;
  23964. }
  23965. /* inherits documentation from base class */
  23966. int QCPErrorBars::findEnd(double sortKey, bool expandedRange) const
  23967. {
  23968. if (mDataPlottable)
  23969. {
  23970. if (mDataContainer->isEmpty())
  23971. return 0;
  23972. int endIndex = mDataPlottable->interface1D()->findEnd(sortKey, expandedRange);
  23973. if (endIndex > mDataContainer->size())
  23974. endIndex = mDataContainer->size();
  23975. return endIndex;
  23976. } else
  23977. qDebug() << Q_FUNC_INFO << "no data plottable set";
  23978. return 0;
  23979. }
  23980. /*!
  23981. Implements a selectTest specific to this plottable's point geometry.
  23982. If \a details is not 0, it will be set to a \ref QCPDataSelection, describing the closest data
  23983. point to \a pos.
  23984. \seebaseclassmethod \ref QCPAbstractPlottable::selectTest
  23985. */
  23986. double QCPErrorBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  23987. {
  23988. if (!mDataPlottable) return -1;
  23989. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  23990. return -1;
  23991. if (!mKeyAxis || !mValueAxis)
  23992. return -1;
  23993. if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint()) || mParentPlot->interactions().testFlag(QCP::iSelectPlottablesBeyondAxisRect))
  23994. {
  23995. QCPErrorBarsDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  23996. double result = pointDistance(pos, closestDataPoint);
  23997. if (details)
  23998. {
  23999. int pointIndex = int(closestDataPoint-mDataContainer->constBegin());
  24000. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  24001. }
  24002. return result;
  24003. } else
  24004. return -1;
  24005. }
  24006. /* inherits documentation from base class */
  24007. void QCPErrorBars::draw(QCPPainter *painter)
  24008. {
  24009. if (!mDataPlottable) return;
  24010. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  24011. if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
  24012. // if the sort key isn't the main key, we must check the visibility for each data point/error bar individually
  24013. // (getVisibleDataBounds applies range restriction, but otherwise can only return full data range):
  24014. bool checkPointVisibility = !mDataPlottable->interface1D()->sortKeyIsMainKey();
  24015. // check data validity if flag set:
  24016. #ifdef QCUSTOMPLOT_CHECK_DATA
  24017. QCPErrorBarsDataContainer::const_iterator it;
  24018. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  24019. {
  24020. if (QCP::isInvalidData(it->errorMinus, it->errorPlus))
  24021. qDebug() << Q_FUNC_INFO << "Data point at index" << it-mDataContainer->constBegin() << "invalid." << "Plottable name:" << name();
  24022. }
  24023. #endif
  24024. applyDefaultAntialiasingHint(painter);
  24025. painter->setBrush(Qt::NoBrush);
  24026. // loop over and draw segments of unselected/selected data:
  24027. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  24028. getDataSegments(selectedSegments, unselectedSegments);
  24029. allSegments << unselectedSegments << selectedSegments;
  24030. QVector<QLineF> backbones, whiskers;
  24031. for (int i=0; i<allSegments.size(); ++i)
  24032. {
  24033. QCPErrorBarsDataContainer::const_iterator begin, end;
  24034. getVisibleDataBounds(begin, end, allSegments.at(i));
  24035. if (begin == end)
  24036. continue;
  24037. bool isSelectedSegment = i >= unselectedSegments.size();
  24038. if (isSelectedSegment && mSelectionDecorator)
  24039. mSelectionDecorator->applyPen(painter);
  24040. else
  24041. painter->setPen(mPen);
  24042. if (painter->pen().capStyle() == Qt::SquareCap)
  24043. {
  24044. QPen capFixPen(painter->pen());
  24045. capFixPen.setCapStyle(Qt::FlatCap);
  24046. painter->setPen(capFixPen);
  24047. }
  24048. backbones.clear();
  24049. whiskers.clear();
  24050. for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  24051. {
  24052. if (!checkPointVisibility || errorBarVisible(int(it-mDataContainer->constBegin())))
  24053. getErrorBarLines(it, backbones, whiskers);
  24054. }
  24055. painter->drawLines(backbones);
  24056. painter->drawLines(whiskers);
  24057. }
  24058. // draw other selection decoration that isn't just line/scatter pens and brushes:
  24059. if (mSelectionDecorator)
  24060. mSelectionDecorator->drawDecoration(painter, selection());
  24061. }
  24062. /* inherits documentation from base class */
  24063. void QCPErrorBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  24064. {
  24065. applyDefaultAntialiasingHint(painter);
  24066. painter->setPen(mPen);
  24067. if (mErrorType == etValueError && mValueAxis && mValueAxis->orientation() == Qt::Vertical)
  24068. {
  24069. painter->drawLine(QLineF(rect.center().x(), rect.top()+2, rect.center().x(), rect.bottom()-1));
  24070. painter->drawLine(QLineF(rect.center().x()-4, rect.top()+2, rect.center().x()+4, rect.top()+2));
  24071. painter->drawLine(QLineF(rect.center().x()-4, rect.bottom()-1, rect.center().x()+4, rect.bottom()-1));
  24072. } else
  24073. {
  24074. painter->drawLine(QLineF(rect.left()+2, rect.center().y(), rect.right()-2, rect.center().y()));
  24075. painter->drawLine(QLineF(rect.left()+2, rect.center().y()-4, rect.left()+2, rect.center().y()+4));
  24076. painter->drawLine(QLineF(rect.right()-2, rect.center().y()-4, rect.right()-2, rect.center().y()+4));
  24077. }
  24078. }
  24079. /* inherits documentation from base class */
  24080. QCPRange QCPErrorBars::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  24081. {
  24082. if (!mDataPlottable)
  24083. {
  24084. foundRange = false;
  24085. return {};
  24086. }
  24087. QCPRange range;
  24088. bool haveLower = false;
  24089. bool haveUpper = false;
  24090. QCPErrorBarsDataContainer::const_iterator it;
  24091. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  24092. {
  24093. if (mErrorType == etValueError)
  24094. {
  24095. // error bar doesn't extend in key dimension (except whisker but we ignore that here), so only use data point center
  24096. const double current = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
  24097. if (qIsNaN(current)) continue;
  24098. if (inSignDomain == QCP::SignDomain::sdBoth || (inSignDomain == QCP::SignDomain::sdNegative && current < 0) || (inSignDomain == QCP::SignDomain::sdPositive && current > 0))
  24099. {
  24100. if (current < range.lower || !haveLower)
  24101. {
  24102. range.lower = current;
  24103. haveLower = true;
  24104. }
  24105. if (current > range.upper || !haveUpper)
  24106. {
  24107. range.upper = current;
  24108. haveUpper = true;
  24109. }
  24110. }
  24111. } else // mErrorType == etKeyError
  24112. {
  24113. const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
  24114. if (qIsNaN(dataKey)) continue;
  24115. // plus error:
  24116. double current = dataKey + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
  24117. if (inSignDomain == QCP::SignDomain::sdBoth || (inSignDomain == QCP::SignDomain::sdNegative && current < 0) || (inSignDomain == QCP::SignDomain::sdPositive && current > 0))
  24118. {
  24119. if (current > range.upper || !haveUpper)
  24120. {
  24121. range.upper = current;
  24122. haveUpper = true;
  24123. }
  24124. }
  24125. // minus error:
  24126. current = dataKey - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
  24127. if (inSignDomain == QCP::SignDomain::sdBoth || (inSignDomain == QCP::SignDomain::sdNegative && current < 0) || (inSignDomain == QCP::SignDomain::sdPositive && current > 0))
  24128. {
  24129. if (current < range.lower || !haveLower)
  24130. {
  24131. range.lower = current;
  24132. haveLower = true;
  24133. }
  24134. }
  24135. }
  24136. }
  24137. if (haveUpper && !haveLower)
  24138. {
  24139. range.lower = range.upper;
  24140. haveLower = true;
  24141. } else if (haveLower && !haveUpper)
  24142. {
  24143. range.upper = range.lower;
  24144. haveUpper = true;
  24145. }
  24146. foundRange = haveLower && haveUpper;
  24147. return range;
  24148. }
  24149. /* inherits documentation from base class */
  24150. QCPRange QCPErrorBars::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  24151. {
  24152. if (!mDataPlottable)
  24153. {
  24154. foundRange = false;
  24155. return {};
  24156. }
  24157. QCPRange range;
  24158. const bool restrictKeyRange = inKeyRange != QCPRange();
  24159. bool haveLower = false;
  24160. bool haveUpper = false;
  24161. QCPErrorBarsDataContainer::const_iterator itBegin = mDataContainer->constBegin();
  24162. QCPErrorBarsDataContainer::const_iterator itEnd = mDataContainer->constEnd();
  24163. if (mDataPlottable->interface1D()->sortKeyIsMainKey() && restrictKeyRange)
  24164. {
  24165. itBegin = mDataContainer->constBegin()+findBegin(inKeyRange.lower, false);
  24166. itEnd = mDataContainer->constBegin()+findEnd(inKeyRange.upper, false);
  24167. }
  24168. for (QCPErrorBarsDataContainer::const_iterator it = itBegin; it != itEnd; ++it)
  24169. {
  24170. if (restrictKeyRange)
  24171. {
  24172. const double dataKey = mDataPlottable->interface1D()->dataMainKey(int(it-mDataContainer->constBegin()));
  24173. if (dataKey < inKeyRange.lower || dataKey > inKeyRange.upper)
  24174. continue;
  24175. }
  24176. if (mErrorType == etValueError)
  24177. {
  24178. const double dataValue = mDataPlottable->interface1D()->dataMainValue(int(it-mDataContainer->constBegin()));
  24179. if (qIsNaN(dataValue)) continue;
  24180. // plus error:
  24181. double current = dataValue + (qIsNaN(it->errorPlus) ? 0 : it->errorPlus);
  24182. if (inSignDomain == QCP::SignDomain::sdBoth || (inSignDomain == QCP::SignDomain::sdNegative && current < 0) || (inSignDomain == QCP::SignDomain::sdPositive && current > 0))
  24183. {
  24184. if (current > range.upper || !haveUpper)
  24185. {
  24186. range.upper = current;
  24187. haveUpper = true;
  24188. }
  24189. }
  24190. // minus error:
  24191. current = dataValue - (qIsNaN(it->errorMinus) ? 0 : it->errorMinus);
  24192. if (inSignDomain == QCP::SignDomain::sdBoth || (inSignDomain == QCP::SignDomain::sdNegative && current < 0) || (inSignDomain == QCP::SignDomain::sdPositive && current > 0))
  24193. {
  24194. if (current < range.lower || !haveLower)
  24195. {
  24196. range.lower = current;
  24197. haveLower = true;
  24198. }
  24199. }
  24200. } else // mErrorType == etKeyError
  24201. {
  24202. // error bar doesn't extend in value dimension (except whisker but we ignore that here), so only use data point center
  24203. const double current = mDataPlottable->interface1D()->dataMainValue(int(it-mDataContainer->constBegin()));
  24204. if (qIsNaN(current)) continue;
  24205. if (inSignDomain == QCP::SignDomain::sdBoth || (inSignDomain == QCP::SignDomain::sdNegative && current < 0) || (inSignDomain == QCP::SignDomain::sdPositive && current > 0))
  24206. {
  24207. if (current < range.lower || !haveLower)
  24208. {
  24209. range.lower = current;
  24210. haveLower = true;
  24211. }
  24212. if (current > range.upper || !haveUpper)
  24213. {
  24214. range.upper = current;
  24215. haveUpper = true;
  24216. }
  24217. }
  24218. }
  24219. }
  24220. if (haveUpper && !haveLower)
  24221. {
  24222. range.lower = range.upper;
  24223. haveLower = true;
  24224. } else if (haveLower && !haveUpper)
  24225. {
  24226. range.upper = range.lower;
  24227. haveUpper = true;
  24228. }
  24229. foundRange = haveLower && haveUpper;
  24230. return range;
  24231. }
  24232. /*! \internal
  24233. Calculates the lines that make up the error bar belonging to the data point \a it.
  24234. The resulting lines are added to \a backbones and \a whiskers. The vectors are not cleared, so
  24235. calling this method with different \a it but the same \a backbones and \a whiskers allows to
  24236. accumulate lines for multiple data points.
  24237. This method assumes that \a it is a valid iterator within the bounds of this \ref QCPErrorBars
  24238. instance and within the bounds of the associated data plottable.
  24239. */
  24240. void QCPErrorBars::getErrorBarLines(QCPErrorBarsDataContainer::const_iterator it, QVector<QLineF> &backbones, QVector<QLineF> &whiskers) const
  24241. {
  24242. if (!mDataPlottable) return;
  24243. int index = int(it-mDataContainer->constBegin());
  24244. QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
  24245. if (qIsNaN(centerPixel.x()) || qIsNaN(centerPixel.y()))
  24246. return;
  24247. QCPAxis *errorAxis = mErrorType == etValueError ? mValueAxis.data() : mKeyAxis.data();
  24248. QCPAxis *orthoAxis = mErrorType == etValueError ? mKeyAxis.data() : mValueAxis.data();
  24249. const double centerErrorAxisPixel = errorAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  24250. const double centerOrthoAxisPixel = orthoAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  24251. const double centerErrorAxisCoord = errorAxis->pixelToCoord(centerErrorAxisPixel); // depending on plottable, this might be different from just mDataPlottable->interface1D()->dataMainKey/Value
  24252. const double symbolGap = mSymbolGap*0.5*errorAxis->pixelOrientation();
  24253. // plus error:
  24254. double errorStart, errorEnd;
  24255. if (!qIsNaN(it->errorPlus))
  24256. {
  24257. errorStart = centerErrorAxisPixel+symbolGap;
  24258. errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord+it->errorPlus);
  24259. if (errorAxis->orientation() == Qt::Vertical)
  24260. {
  24261. if ((errorStart > errorEnd) != errorAxis->rangeReversed())
  24262. backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
  24263. whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
  24264. } else
  24265. {
  24266. if ((errorStart < errorEnd) != errorAxis->rangeReversed())
  24267. backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
  24268. whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
  24269. }
  24270. }
  24271. // minus error:
  24272. if (!qIsNaN(it->errorMinus))
  24273. {
  24274. errorStart = centerErrorAxisPixel-symbolGap;
  24275. errorEnd = errorAxis->coordToPixel(centerErrorAxisCoord-it->errorMinus);
  24276. if (errorAxis->orientation() == Qt::Vertical)
  24277. {
  24278. if ((errorStart < errorEnd) != errorAxis->rangeReversed())
  24279. backbones.append(QLineF(centerOrthoAxisPixel, errorStart, centerOrthoAxisPixel, errorEnd));
  24280. whiskers.append(QLineF(centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5, errorEnd));
  24281. } else
  24282. {
  24283. if ((errorStart > errorEnd) != errorAxis->rangeReversed())
  24284. backbones.append(QLineF(errorStart, centerOrthoAxisPixel, errorEnd, centerOrthoAxisPixel));
  24285. whiskers.append(QLineF(errorEnd, centerOrthoAxisPixel-mWhiskerWidth*0.5, errorEnd, centerOrthoAxisPixel+mWhiskerWidth*0.5));
  24286. }
  24287. }
  24288. }
  24289. /*! \internal
  24290. This method outputs the currently visible data range via \a begin and \a end. The returned range
  24291. will also never exceed \a rangeRestriction.
  24292. Since error bars with type \ref etKeyError may extend to arbitrarily positive and negative key
  24293. coordinates relative to their data point key, this method checks all outer error bars whether
  24294. they truly don't reach into the visible portion of the axis rect, by calling \ref
  24295. errorBarVisible. On the other hand error bars with type \ref etValueError that are associated
  24296. with data plottables whose sort key is equal to the main key (see \ref qcpdatacontainer-datatype
  24297. "QCPDataContainer DataType") can be handled very efficiently by finding the visible range of
  24298. error bars through binary search (\ref QCPPlottableInterface1D::findBegin and \ref
  24299. QCPPlottableInterface1D::findEnd).
  24300. If the plottable's sort key is not equal to the main key, this method returns the full data
  24301. range, only restricted by \a rangeRestriction. Drawing optimization then has to be done on a
  24302. point-by-point basis in the \ref draw method.
  24303. */
  24304. void QCPErrorBars::getVisibleDataBounds(QCPErrorBarsDataContainer::const_iterator &begin, QCPErrorBarsDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
  24305. {
  24306. QCPAxis *keyAxis = mKeyAxis.data();
  24307. QCPAxis *valueAxis = mValueAxis.data();
  24308. if (!keyAxis || !valueAxis)
  24309. {
  24310. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  24311. end = mDataContainer->constEnd();
  24312. begin = end;
  24313. return;
  24314. }
  24315. if (!mDataPlottable || rangeRestriction.isEmpty())
  24316. {
  24317. end = mDataContainer->constEnd();
  24318. begin = end;
  24319. return;
  24320. }
  24321. if (!mDataPlottable->interface1D()->sortKeyIsMainKey())
  24322. {
  24323. // if the sort key isn't the main key, it's not possible to find a contiguous range of visible
  24324. // data points, so this method then only applies the range restriction and otherwise returns
  24325. // the full data range. Visibility checks must be done on a per-datapoin-basis during drawing
  24326. QCPDataRange dataRange(0, mDataContainer->size());
  24327. dataRange = dataRange.bounded(rangeRestriction);
  24328. begin = mDataContainer->constBegin()+dataRange.begin();
  24329. end = mDataContainer->constBegin()+dataRange.end();
  24330. return;
  24331. }
  24332. // get visible data range via interface from data plottable, and then restrict to available error data points:
  24333. const int n = qMin(mDataContainer->size(), mDataPlottable->interface1D()->dataCount());
  24334. int beginIndex = mDataPlottable->interface1D()->findBegin(keyAxis->range().lower);
  24335. int endIndex = mDataPlottable->interface1D()->findEnd(keyAxis->range().upper);
  24336. int i = beginIndex;
  24337. while (i > 0 && i < n && i > rangeRestriction.begin())
  24338. {
  24339. if (errorBarVisible(i))
  24340. beginIndex = i;
  24341. --i;
  24342. }
  24343. i = endIndex;
  24344. while (i >= 0 && i < n && i < rangeRestriction.end())
  24345. {
  24346. if (errorBarVisible(i))
  24347. endIndex = i+1;
  24348. ++i;
  24349. }
  24350. QCPDataRange dataRange(beginIndex, endIndex);
  24351. dataRange = dataRange.bounded(rangeRestriction.bounded(QCPDataRange(0, mDataContainer->size())));
  24352. begin = mDataContainer->constBegin()+dataRange.begin();
  24353. end = mDataContainer->constBegin()+dataRange.end();
  24354. }
  24355. /*! \internal
  24356. Calculates the minimum distance in pixels the error bars' representation has from the given \a
  24357. pixelPoint. This is used to determine whether the error bar was clicked or not, e.g. in \ref
  24358. selectTest. The closest data point to \a pixelPoint is returned in \a closestData.
  24359. */
  24360. double QCPErrorBars::pointDistance(const QPointF &pixelPoint, QCPErrorBarsDataContainer::const_iterator &closestData) const
  24361. {
  24362. closestData = mDataContainer->constEnd();
  24363. if (!mDataPlottable || mDataContainer->isEmpty())
  24364. return -1.0;
  24365. if (!mKeyAxis || !mValueAxis)
  24366. {
  24367. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  24368. return -1.0;
  24369. }
  24370. QCPErrorBarsDataContainer::const_iterator begin, end;
  24371. getVisibleDataBounds(begin, end, QCPDataRange(0, dataCount()));
  24372. // calculate minimum distances to error backbones (whiskers are ignored for speed) and find closestData iterator:
  24373. double minDistSqr = (std::numeric_limits<double>::max)();
  24374. QVector<QLineF> backbones, whiskers;
  24375. for (QCPErrorBarsDataContainer::const_iterator it=begin; it!=end; ++it)
  24376. {
  24377. getErrorBarLines(it, backbones, whiskers);
  24378. foreach (const QLineF &backbone, backbones)
  24379. {
  24380. const double currentDistSqr = QCPVector2D(pixelPoint).distanceSquaredToLine(backbone);
  24381. if (currentDistSqr < minDistSqr)
  24382. {
  24383. minDistSqr = currentDistSqr;
  24384. closestData = it;
  24385. }
  24386. }
  24387. }
  24388. return qSqrt(minDistSqr);
  24389. }
  24390. /*! \internal
  24391. \note This method is identical to \ref QCPAbstractPlottable1D::getDataSegments but needs to be
  24392. reproduced here since the \ref QCPErrorBars plottable, as a special case that doesn't have its
  24393. own key/value data coordinates, doesn't derive from \ref QCPAbstractPlottable1D. See the
  24394. documentation there for details.
  24395. */
  24396. void QCPErrorBars::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
  24397. {
  24398. selectedSegments.clear();
  24399. unselectedSegments.clear();
  24400. if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
  24401. {
  24402. if (selected())
  24403. selectedSegments << QCPDataRange(0, dataCount());
  24404. else
  24405. unselectedSegments << QCPDataRange(0, dataCount());
  24406. } else
  24407. {
  24408. QCPDataSelection sel(selection());
  24409. sel.simplify();
  24410. selectedSegments = sel.dataRanges();
  24411. unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
  24412. }
  24413. }
  24414. /*! \internal
  24415. Returns whether the error bar at the specified \a index is visible within the current key axis
  24416. range.
  24417. This method assumes for performance reasons without checking that the key axis, the value axis,
  24418. and the data plottable (\ref setDataPlottable) are not \c nullptr and that \a index is within
  24419. valid bounds of this \ref QCPErrorBars instance and the bounds of the data plottable.
  24420. */
  24421. bool QCPErrorBars::errorBarVisible(int index) const
  24422. {
  24423. QPointF centerPixel = mDataPlottable->interface1D()->dataPixelPosition(index);
  24424. const double centerKeyPixel = mKeyAxis->orientation() == Qt::Horizontal ? centerPixel.x() : centerPixel.y();
  24425. if (qIsNaN(centerKeyPixel))
  24426. return false;
  24427. double keyMin, keyMax;
  24428. if (mErrorType == etKeyError)
  24429. {
  24430. const double centerKey = mKeyAxis->pixelToCoord(centerKeyPixel);
  24431. const double errorPlus = mDataContainer->at(index).errorPlus;
  24432. const double errorMinus = mDataContainer->at(index).errorMinus;
  24433. keyMax = centerKey+(qIsNaN(errorPlus) ? 0 : errorPlus);
  24434. keyMin = centerKey-(qIsNaN(errorMinus) ? 0 : errorMinus);
  24435. } else // mErrorType == etValueError
  24436. {
  24437. keyMax = mKeyAxis->pixelToCoord(centerKeyPixel+mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
  24438. keyMin = mKeyAxis->pixelToCoord(centerKeyPixel-mWhiskerWidth*0.5*mKeyAxis->pixelOrientation());
  24439. }
  24440. return ((keyMax > mKeyAxis->range().lower) && (keyMin < mKeyAxis->range().upper));
  24441. }
  24442. /*! \internal
  24443. Returns whether \a line intersects (or is contained in) \a pixelRect.
  24444. \a line is assumed to be either perfectly horizontal or perfectly vertical, as is the case for
  24445. error bar lines.
  24446. */
  24447. bool QCPErrorBars::rectIntersectsLine(const QRectF &pixelRect, const QLineF &line) const
  24448. {
  24449. if (pixelRect.left() > line.x1() && pixelRect.left() > line.x2())
  24450. return false;
  24451. else if (pixelRect.right() < line.x1() && pixelRect.right() < line.x2())
  24452. return false;
  24453. else if (pixelRect.top() > line.y1() && pixelRect.top() > line.y2())
  24454. return false;
  24455. else if (pixelRect.bottom() < line.y1() && pixelRect.bottom() < line.y2())
  24456. return false;
  24457. else
  24458. return true;
  24459. }
  24460. /* end of 'src/plottables/plottable-errorbar.cpp' */
  24461. /* including file 'src/items/item-straightline.cpp' */
  24462. /* modified 2021-03-29T02:30:44, size 7596 */
  24463. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24464. //////////////////// QCPItemStraightLine
  24465. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24466. /*! \class QCPItemStraightLine
  24467. \brief A straight line that spans infinitely in both directions
  24468. \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions."
  24469. It has two positions, \a point1 and \a point2, which define the straight line.
  24470. */
  24471. /*!
  24472. Creates a straight line item and sets default values.
  24473. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24474. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24475. */
  24476. QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) :
  24477. QCPAbstractItem(parentPlot),
  24478. point1(createPosition(QLatin1String("point1"))),
  24479. point2(createPosition(QLatin1String("point2")))
  24480. {
  24481. point1->setCoords(0, 0);
  24482. point2->setCoords(1, 1);
  24483. setPen(QPen(Qt::black));
  24484. setSelectedPen(QPen(Qt::blue,2));
  24485. }
  24486. QCPItemStraightLine::~QCPItemStraightLine()
  24487. {
  24488. }
  24489. /*!
  24490. Sets the pen that will be used to draw the line
  24491. \see setSelectedPen
  24492. */
  24493. void QCPItemStraightLine::setPen(const QPen &pen)
  24494. {
  24495. mPen = pen;
  24496. }
  24497. /*!
  24498. Sets the pen that will be used to draw the line when selected
  24499. \see setPen, setSelected
  24500. */
  24501. void QCPItemStraightLine::setSelectedPen(const QPen &pen)
  24502. {
  24503. mSelectedPen = pen;
  24504. }
  24505. /* inherits documentation from base class */
  24506. double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24507. {
  24508. Q_UNUSED(details)
  24509. if (onlySelectable && !mSelectable)
  24510. return -1;
  24511. return QCPVector2D(pos).distanceToStraightLine(point1->pixelPosition(), point2->pixelPosition()-point1->pixelPosition());
  24512. }
  24513. /* inherits documentation from base class */
  24514. void QCPItemStraightLine::draw(QCPPainter *painter)
  24515. {
  24516. QCPVector2D start(point1->pixelPosition());
  24517. QCPVector2D end(point2->pixelPosition());
  24518. // get visible segment of straight line inside clipRect:
  24519. int clipPad = qCeil(mainPen().widthF());
  24520. QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  24521. // paint visible segment, if existent:
  24522. if (!line.isNull())
  24523. {
  24524. painter->setPen(mainPen());
  24525. painter->drawLine(line);
  24526. }
  24527. }
  24528. /*! \internal
  24529. Returns the section of the straight line defined by \a base and direction vector \a
  24530. vec, that is visible in the specified \a rect.
  24531. This is a helper function for \ref draw.
  24532. */
  24533. QLineF QCPItemStraightLine::getRectClippedStraightLine(const QCPVector2D &base, const QCPVector2D &vec, const QRect &rect) const
  24534. {
  24535. double bx, by;
  24536. double gamma;
  24537. QLineF result;
  24538. if (vec.x() == 0 && vec.y() == 0)
  24539. return result;
  24540. if (qFuzzyIsNull(vec.x())) // line is vertical
  24541. {
  24542. // check top of rect:
  24543. bx = rect.left();
  24544. by = rect.top();
  24545. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  24546. if (gamma >= 0 && gamma <= rect.width())
  24547. result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical
  24548. } else if (qFuzzyIsNull(vec.y())) // line is horizontal
  24549. {
  24550. // check left of rect:
  24551. bx = rect.left();
  24552. by = rect.top();
  24553. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  24554. if (gamma >= 0 && gamma <= rect.height())
  24555. result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal
  24556. } else // line is skewed
  24557. {
  24558. QList<QCPVector2D> pointVectors;
  24559. // check top of rect:
  24560. bx = rect.left();
  24561. by = rect.top();
  24562. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  24563. if (gamma >= 0 && gamma <= rect.width())
  24564. pointVectors.append(QCPVector2D(bx+gamma, by));
  24565. // check bottom of rect:
  24566. bx = rect.left();
  24567. by = rect.bottom();
  24568. gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y();
  24569. if (gamma >= 0 && gamma <= rect.width())
  24570. pointVectors.append(QCPVector2D(bx+gamma, by));
  24571. // check left of rect:
  24572. bx = rect.left();
  24573. by = rect.top();
  24574. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  24575. if (gamma >= 0 && gamma <= rect.height())
  24576. pointVectors.append(QCPVector2D(bx, by+gamma));
  24577. // check right of rect:
  24578. bx = rect.right();
  24579. by = rect.top();
  24580. gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x();
  24581. if (gamma >= 0 && gamma <= rect.height())
  24582. pointVectors.append(QCPVector2D(bx, by+gamma));
  24583. // evaluate points:
  24584. if (pointVectors.size() == 2)
  24585. {
  24586. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  24587. } else if (pointVectors.size() > 2)
  24588. {
  24589. // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
  24590. double distSqrMax = 0;
  24591. QCPVector2D pv1, pv2;
  24592. for (int i=0; i<pointVectors.size()-1; ++i)
  24593. {
  24594. for (int k=i+1; k<pointVectors.size(); ++k)
  24595. {
  24596. double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
  24597. if (distSqr > distSqrMax)
  24598. {
  24599. pv1 = pointVectors.at(i);
  24600. pv2 = pointVectors.at(k);
  24601. distSqrMax = distSqr;
  24602. }
  24603. }
  24604. }
  24605. result.setPoints(pv1.toPointF(), pv2.toPointF());
  24606. }
  24607. }
  24608. return result;
  24609. }
  24610. /*! \internal
  24611. Returns the pen that should be used for drawing lines. Returns mPen when the
  24612. item is not selected and mSelectedPen when it is.
  24613. */
  24614. QPen QCPItemStraightLine::mainPen() const
  24615. {
  24616. return mSelected ? mSelectedPen : mPen;
  24617. }
  24618. /* end of 'src/items/item-straightline.cpp' */
  24619. /* including file 'src/items/item-line.cpp' */
  24620. /* modified 2021-03-29T02:30:44, size 8525 */
  24621. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24622. //////////////////// QCPItemLine
  24623. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24624. /*! \class QCPItemLine
  24625. \brief A line from one point to another
  24626. \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions."
  24627. It has two positions, \a start and \a end, which define the end points of the line.
  24628. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow.
  24629. */
  24630. /*!
  24631. Creates a line item and sets default values.
  24632. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24633. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24634. */
  24635. QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) :
  24636. QCPAbstractItem(parentPlot),
  24637. start(createPosition(QLatin1String("start"))),
  24638. end(createPosition(QLatin1String("end")))
  24639. {
  24640. start->setCoords(0, 0);
  24641. end->setCoords(1, 1);
  24642. setPen(QPen(Qt::black));
  24643. setSelectedPen(QPen(Qt::blue,2));
  24644. }
  24645. QCPItemLine::~QCPItemLine()
  24646. {
  24647. }
  24648. /*!
  24649. Sets the pen that will be used to draw the line
  24650. \see setSelectedPen
  24651. */
  24652. void QCPItemLine::setPen(const QPen &pen)
  24653. {
  24654. mPen = pen;
  24655. }
  24656. /*!
  24657. Sets the pen that will be used to draw the line when selected
  24658. \see setPen, setSelected
  24659. */
  24660. void QCPItemLine::setSelectedPen(const QPen &pen)
  24661. {
  24662. mSelectedPen = pen;
  24663. }
  24664. /*!
  24665. Sets the line ending style of the head. The head corresponds to the \a end position.
  24666. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24667. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  24668. \see setTail
  24669. */
  24670. void QCPItemLine::setHead(const QCPLineEnding &head)
  24671. {
  24672. mHead = head;
  24673. }
  24674. /*!
  24675. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  24676. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24677. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  24678. \see setHead
  24679. */
  24680. void QCPItemLine::setTail(const QCPLineEnding &tail)
  24681. {
  24682. mTail = tail;
  24683. }
  24684. /* inherits documentation from base class */
  24685. double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24686. {
  24687. Q_UNUSED(details)
  24688. if (onlySelectable && !mSelectable)
  24689. return -1;
  24690. return qSqrt(QCPVector2D(pos).distanceSquaredToLine(start->pixelPosition(), end->pixelPosition()));
  24691. }
  24692. /* inherits documentation from base class */
  24693. void QCPItemLine::draw(QCPPainter *painter)
  24694. {
  24695. QCPVector2D startVec(start->pixelPosition());
  24696. QCPVector2D endVec(end->pixelPosition());
  24697. if (qFuzzyIsNull((startVec-endVec).lengthSquared()))
  24698. return;
  24699. // get visible segment of straight line inside clipRect:
  24700. int clipPad = int(qMax(mHead.boundingDistance(), mTail.boundingDistance()));
  24701. clipPad = qMax(clipPad, qCeil(mainPen().widthF()));
  24702. QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad));
  24703. // paint visible segment, if existent:
  24704. if (!line.isNull())
  24705. {
  24706. painter->setPen(mainPen());
  24707. painter->drawLine(line);
  24708. painter->setBrush(Qt::SolidPattern);
  24709. if (mTail.style() != QCPLineEnding::EndingStyle::esNone)
  24710. mTail.draw(painter, startVec, startVec-endVec);
  24711. if (mHead.style() != QCPLineEnding::EndingStyle::esNone)
  24712. mHead.draw(painter, endVec, endVec-startVec);
  24713. }
  24714. }
  24715. /*! \internal
  24716. Returns the section of the line defined by \a start and \a end, that is visible in the specified
  24717. \a rect.
  24718. This is a helper function for \ref draw.
  24719. */
  24720. QLineF QCPItemLine::getRectClippedLine(const QCPVector2D &start, const QCPVector2D &end, const QRect &rect) const
  24721. {
  24722. bool containsStart = rect.contains(qRound(start.x()), qRound(start.y()));
  24723. bool containsEnd = rect.contains(qRound(end.x()), qRound(end.y()));
  24724. if (containsStart && containsEnd)
  24725. return {start.toPointF(), end.toPointF()};
  24726. QCPVector2D base = start;
  24727. QCPVector2D vec = end-start;
  24728. double bx, by;
  24729. double gamma, mu;
  24730. QLineF result;
  24731. QList<QCPVector2D> pointVectors;
  24732. if (!qFuzzyIsNull(vec.y())) // line is not horizontal
  24733. {
  24734. // check top of rect:
  24735. bx = rect.left();
  24736. by = rect.top();
  24737. mu = (by-base.y())/vec.y();
  24738. if (mu >= 0 && mu <= 1)
  24739. {
  24740. gamma = base.x()-bx + mu*vec.x();
  24741. if (gamma >= 0 && gamma <= rect.width())
  24742. pointVectors.append(QCPVector2D(bx+gamma, by));
  24743. }
  24744. // check bottom of rect:
  24745. bx = rect.left();
  24746. by = rect.bottom();
  24747. mu = (by-base.y())/vec.y();
  24748. if (mu >= 0 && mu <= 1)
  24749. {
  24750. gamma = base.x()-bx + mu*vec.x();
  24751. if (gamma >= 0 && gamma <= rect.width())
  24752. pointVectors.append(QCPVector2D(bx+gamma, by));
  24753. }
  24754. }
  24755. if (!qFuzzyIsNull(vec.x())) // line is not vertical
  24756. {
  24757. // check left of rect:
  24758. bx = rect.left();
  24759. by = rect.top();
  24760. mu = (bx-base.x())/vec.x();
  24761. if (mu >= 0 && mu <= 1)
  24762. {
  24763. gamma = base.y()-by + mu*vec.y();
  24764. if (gamma >= 0 && gamma <= rect.height())
  24765. pointVectors.append(QCPVector2D(bx, by+gamma));
  24766. }
  24767. // check right of rect:
  24768. bx = rect.right();
  24769. by = rect.top();
  24770. mu = (bx-base.x())/vec.x();
  24771. if (mu >= 0 && mu <= 1)
  24772. {
  24773. gamma = base.y()-by + mu*vec.y();
  24774. if (gamma >= 0 && gamma <= rect.height())
  24775. pointVectors.append(QCPVector2D(bx, by+gamma));
  24776. }
  24777. }
  24778. if (containsStart)
  24779. pointVectors.append(start);
  24780. if (containsEnd)
  24781. pointVectors.append(end);
  24782. // evaluate points:
  24783. if (pointVectors.size() == 2)
  24784. {
  24785. result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF());
  24786. } else if (pointVectors.size() > 2)
  24787. {
  24788. // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance:
  24789. double distSqrMax = 0;
  24790. QCPVector2D pv1, pv2;
  24791. for (int i=0; i<pointVectors.size()-1; ++i)
  24792. {
  24793. for (int k=i+1; k<pointVectors.size(); ++k)
  24794. {
  24795. double distSqr = (pointVectors.at(i)-pointVectors.at(k)).lengthSquared();
  24796. if (distSqr > distSqrMax)
  24797. {
  24798. pv1 = pointVectors.at(i);
  24799. pv2 = pointVectors.at(k);
  24800. distSqrMax = distSqr;
  24801. }
  24802. }
  24803. }
  24804. result.setPoints(pv1.toPointF(), pv2.toPointF());
  24805. }
  24806. return result;
  24807. }
  24808. /*! \internal
  24809. Returns the pen that should be used for drawing lines. Returns mPen when the
  24810. item is not selected and mSelectedPen when it is.
  24811. */
  24812. QPen QCPItemLine::mainPen() const
  24813. {
  24814. return mSelected ? mSelectedPen : mPen;
  24815. }
  24816. /* end of 'src/items/item-line.cpp' */
  24817. /* including file 'src/items/item-curve.cpp' */
  24818. /* modified 2021-03-29T02:30:44, size 7273 */
  24819. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24820. //////////////////// QCPItemCurve
  24821. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24822. /*! \class QCPItemCurve
  24823. \brief A curved line from one point to another
  24824. \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions."
  24825. It has four positions, \a start and \a end, which define the end points of the line, and two
  24826. control points which define the direction the line exits from the start and the direction from
  24827. which it approaches the end: \a startDir and \a endDir.
  24828. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an
  24829. arrow.
  24830. Often it is desirable for the control points to stay at fixed relative positions to the start/end
  24831. point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start,
  24832. and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir.
  24833. */
  24834. /*!
  24835. Creates a curve item and sets default values.
  24836. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24837. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24838. */
  24839. QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) :
  24840. QCPAbstractItem(parentPlot),
  24841. start(createPosition(QLatin1String("start"))),
  24842. startDir(createPosition(QLatin1String("startDir"))),
  24843. endDir(createPosition(QLatin1String("endDir"))),
  24844. end(createPosition(QLatin1String("end")))
  24845. {
  24846. start->setCoords(0, 0);
  24847. startDir->setCoords(0.5, 0);
  24848. endDir->setCoords(0, 0.5);
  24849. end->setCoords(1, 1);
  24850. setPen(QPen(Qt::black));
  24851. setSelectedPen(QPen(Qt::blue,2));
  24852. }
  24853. QCPItemCurve::~QCPItemCurve()
  24854. {
  24855. }
  24856. /*!
  24857. Sets the pen that will be used to draw the line
  24858. \see setSelectedPen
  24859. */
  24860. void QCPItemCurve::setPen(const QPen &pen)
  24861. {
  24862. mPen = pen;
  24863. }
  24864. /*!
  24865. Sets the pen that will be used to draw the line when selected
  24866. \see setPen, setSelected
  24867. */
  24868. void QCPItemCurve::setSelectedPen(const QPen &pen)
  24869. {
  24870. mSelectedPen = pen;
  24871. }
  24872. /*!
  24873. Sets the line ending style of the head. The head corresponds to the \a end position.
  24874. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24875. a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode
  24876. \see setTail
  24877. */
  24878. void QCPItemCurve::setHead(const QCPLineEnding &head)
  24879. {
  24880. mHead = head;
  24881. }
  24882. /*!
  24883. Sets the line ending style of the tail. The tail corresponds to the \a start position.
  24884. Note that due to the overloaded QCPLineEnding constructor, you may directly specify
  24885. a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode
  24886. \see setHead
  24887. */
  24888. void QCPItemCurve::setTail(const QCPLineEnding &tail)
  24889. {
  24890. mTail = tail;
  24891. }
  24892. /* inherits documentation from base class */
  24893. double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  24894. {
  24895. Q_UNUSED(details)
  24896. if (onlySelectable && !mSelectable)
  24897. return -1;
  24898. QPointF startVec(start->pixelPosition());
  24899. QPointF startDirVec(startDir->pixelPosition());
  24900. QPointF endDirVec(endDir->pixelPosition());
  24901. QPointF endVec(end->pixelPosition());
  24902. QPainterPath cubicPath(startVec);
  24903. cubicPath.cubicTo(startDirVec, endDirVec, endVec);
  24904. QList<QPolygonF> polygons = cubicPath.toSubpathPolygons();
  24905. if (polygons.isEmpty())
  24906. return -1;
  24907. const QPolygonF polygon = polygons.first();
  24908. QCPVector2D p(pos);
  24909. double minDistSqr = (std::numeric_limits<double>::max)();
  24910. for (int i=1; i<polygon.size(); ++i)
  24911. {
  24912. double distSqr = p.distanceSquaredToLine(polygon.at(i-1), polygon.at(i));
  24913. if (distSqr < minDistSqr)
  24914. minDistSqr = distSqr;
  24915. }
  24916. return qSqrt(minDistSqr);
  24917. }
  24918. /* inherits documentation from base class */
  24919. void QCPItemCurve::draw(QCPPainter *painter)
  24920. {
  24921. QCPVector2D startVec(start->pixelPosition());
  24922. QCPVector2D startDirVec(startDir->pixelPosition());
  24923. QCPVector2D endDirVec(endDir->pixelPosition());
  24924. QCPVector2D endVec(end->pixelPosition());
  24925. if ((endVec-startVec).length() > 1e10) // too large curves cause crash
  24926. return;
  24927. QPainterPath cubicPath(startVec.toPointF());
  24928. cubicPath.cubicTo(startDirVec.toPointF(), endDirVec.toPointF(), endVec.toPointF());
  24929. // paint visible segment, if existent:
  24930. const int clipEnlarge = qCeil(mainPen().widthF());
  24931. QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
  24932. QRect cubicRect = cubicPath.controlPointRect().toRect();
  24933. if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position
  24934. cubicRect.adjust(0, 0, 1, 1);
  24935. if (clip.intersects(cubicRect))
  24936. {
  24937. painter->setPen(mainPen());
  24938. painter->drawPath(cubicPath);
  24939. painter->setBrush(Qt::SolidPattern);
  24940. if (mTail.style() != QCPLineEnding::EndingStyle::esNone)
  24941. mTail.draw(painter, startVec, M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI);
  24942. if (mHead.style() != QCPLineEnding::EndingStyle::esNone)
  24943. mHead.draw(painter, endVec, -cubicPath.angleAtPercent(1)/180.0*M_PI);
  24944. }
  24945. }
  24946. /*! \internal
  24947. Returns the pen that should be used for drawing lines. Returns mPen when the
  24948. item is not selected and mSelectedPen when it is.
  24949. */
  24950. QPen QCPItemCurve::mainPen() const
  24951. {
  24952. return mSelected ? mSelectedPen : mPen;
  24953. }
  24954. /* end of 'src/items/item-curve.cpp' */
  24955. /* including file 'src/items/item-rect.cpp' */
  24956. /* modified 2021-03-29T02:30:44, size 6472 */
  24957. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24958. //////////////////// QCPItemRect
  24959. ////////////////////////////////////////////////////////////////////////////////////////////////////
  24960. /*! \class QCPItemRect
  24961. \brief A rectangle
  24962. \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions."
  24963. It has two positions, \a topLeft and \a bottomRight, which define the rectangle.
  24964. */
  24965. /*!
  24966. Creates a rectangle item and sets default values.
  24967. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  24968. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  24969. */
  24970. QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) :
  24971. QCPAbstractItem(parentPlot),
  24972. topLeft(createPosition(QLatin1String("topLeft"))),
  24973. bottomRight(createPosition(QLatin1String("bottomRight"))),
  24974. top(createAnchor(QLatin1String("top"), aiTop)),
  24975. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  24976. right(createAnchor(QLatin1String("right"), aiRight)),
  24977. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  24978. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  24979. left(createAnchor(QLatin1String("left"), aiLeft))
  24980. {
  24981. topLeft->setCoords(0, 1);
  24982. bottomRight->setCoords(1, 0);
  24983. setPen(QPen(Qt::black));
  24984. setSelectedPen(QPen(Qt::blue,2));
  24985. setBrush(Qt::NoBrush);
  24986. setSelectedBrush(Qt::NoBrush);
  24987. }
  24988. QCPItemRect::~QCPItemRect()
  24989. {
  24990. }
  24991. /*!
  24992. Sets the pen that will be used to draw the line of the rectangle
  24993. \see setSelectedPen, setBrush
  24994. */
  24995. void QCPItemRect::setPen(const QPen &pen)
  24996. {
  24997. mPen = pen;
  24998. }
  24999. /*!
  25000. Sets the pen that will be used to draw the line of the rectangle when selected
  25001. \see setPen, setSelected
  25002. */
  25003. void QCPItemRect::setSelectedPen(const QPen &pen)
  25004. {
  25005. mSelectedPen = pen;
  25006. }
  25007. /*!
  25008. Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to
  25009. Qt::NoBrush.
  25010. \see setSelectedBrush, setPen
  25011. */
  25012. void QCPItemRect::setBrush(const QBrush &brush)
  25013. {
  25014. mBrush = brush;
  25015. }
  25016. /*!
  25017. Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a
  25018. brush to Qt::NoBrush.
  25019. \see setBrush
  25020. */
  25021. void QCPItemRect::setSelectedBrush(const QBrush &brush)
  25022. {
  25023. mSelectedBrush = brush;
  25024. }
  25025. /* inherits documentation from base class */
  25026. double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25027. {
  25028. Q_UNUSED(details)
  25029. if (onlySelectable && !mSelectable)
  25030. return -1;
  25031. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition()).normalized();
  25032. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  25033. return rectDistance(rect, pos, filledRect);
  25034. }
  25035. /* inherits documentation from base class */
  25036. void QCPItemRect::draw(QCPPainter *painter)
  25037. {
  25038. QPointF p1 = topLeft->pixelPosition();
  25039. QPointF p2 = bottomRight->pixelPosition();
  25040. if (p1.toPoint() == p2.toPoint())
  25041. return;
  25042. QRectF rect = QRectF(p1, p2).normalized();
  25043. double clipPad = mainPen().widthF();
  25044. QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  25045. if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect
  25046. {
  25047. painter->setPen(mainPen());
  25048. painter->setBrush(mainBrush());
  25049. painter->drawRect(rect);
  25050. }
  25051. }
  25052. /* inherits documentation from base class */
  25053. QPointF QCPItemRect::anchorPixelPosition(int anchorId) const
  25054. {
  25055. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
  25056. switch (anchorId)
  25057. {
  25058. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  25059. case aiTopRight: return rect.topRight();
  25060. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  25061. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  25062. case aiBottomLeft: return rect.bottomLeft();
  25063. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  25064. }
  25065. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25066. return {};
  25067. }
  25068. /*! \internal
  25069. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25070. and mSelectedPen when it is.
  25071. */
  25072. QPen QCPItemRect::mainPen() const
  25073. {
  25074. return mSelected ? mSelectedPen : mPen;
  25075. }
  25076. /*! \internal
  25077. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  25078. is not selected and mSelectedBrush when it is.
  25079. */
  25080. QBrush QCPItemRect::mainBrush() const
  25081. {
  25082. return mSelected ? mSelectedBrush : mBrush;
  25083. }
  25084. /* end of 'src/items/item-rect.cpp' */
  25085. /* including file 'src/items/item-text.cpp' */
  25086. /* modified 2021-03-29T02:30:44, size 13335 */
  25087. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25088. //////////////////// QCPItemText
  25089. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25090. /*! \class QCPItemText
  25091. \brief A text label
  25092. \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions."
  25093. Its position is defined by the member \a position and the setting of \ref setPositionAlignment.
  25094. The latter controls which part of the text rect shall be aligned with \a position.
  25095. The text alignment itself (i.e. left, center, right) can be controlled with \ref
  25096. setTextAlignment.
  25097. The text may be rotated around the \a position point with \ref setRotation.
  25098. */
  25099. /*!
  25100. Creates a text item and sets default values.
  25101. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25102. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25103. */
  25104. QCPItemText::QCPItemText(QCustomPlot *parentPlot) :
  25105. QCPAbstractItem(parentPlot),
  25106. position(createPosition(QLatin1String("position"))),
  25107. topLeft(createAnchor(QLatin1String("topLeft"), aiTopLeft)),
  25108. top(createAnchor(QLatin1String("top"), aiTop)),
  25109. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  25110. right(createAnchor(QLatin1String("right"), aiRight)),
  25111. bottomRight(createAnchor(QLatin1String("bottomRight"), aiBottomRight)),
  25112. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  25113. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  25114. left(createAnchor(QLatin1String("left"), aiLeft)),
  25115. mText(QLatin1String("text")),
  25116. mPositionAlignment(Qt::AlignCenter),
  25117. mTextAlignment(Qt::AlignTop|Qt::AlignHCenter),
  25118. mRotation(0)
  25119. {
  25120. position->setCoords(0, 0);
  25121. setPen(Qt::NoPen);
  25122. setSelectedPen(Qt::NoPen);
  25123. setBrush(Qt::NoBrush);
  25124. setSelectedBrush(Qt::NoBrush);
  25125. setColor(Qt::black);
  25126. setSelectedColor(Qt::blue);
  25127. }
  25128. QCPItemText::~QCPItemText()
  25129. {
  25130. }
  25131. /*!
  25132. Sets the color of the text.
  25133. */
  25134. void QCPItemText::setColor(const QColor &color)
  25135. {
  25136. mColor = color;
  25137. }
  25138. /*!
  25139. Sets the color of the text that will be used when the item is selected.
  25140. */
  25141. void QCPItemText::setSelectedColor(const QColor &color)
  25142. {
  25143. mSelectedColor = color;
  25144. }
  25145. /*!
  25146. Sets the pen that will be used do draw a rectangular border around the text. To disable the
  25147. border, set \a pen to Qt::NoPen.
  25148. \see setSelectedPen, setBrush, setPadding
  25149. */
  25150. void QCPItemText::setPen(const QPen &pen)
  25151. {
  25152. mPen = pen;
  25153. }
  25154. /*!
  25155. Sets the pen that will be used do draw a rectangular border around the text, when the item is
  25156. selected. To disable the border, set \a pen to Qt::NoPen.
  25157. \see setPen
  25158. */
  25159. void QCPItemText::setSelectedPen(const QPen &pen)
  25160. {
  25161. mSelectedPen = pen;
  25162. }
  25163. /*!
  25164. Sets the brush that will be used do fill the background of the text. To disable the
  25165. background, set \a brush to Qt::NoBrush.
  25166. \see setSelectedBrush, setPen, setPadding
  25167. */
  25168. void QCPItemText::setBrush(const QBrush &brush)
  25169. {
  25170. mBrush = brush;
  25171. }
  25172. /*!
  25173. Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the
  25174. background, set \a brush to Qt::NoBrush.
  25175. \see setBrush
  25176. */
  25177. void QCPItemText::setSelectedBrush(const QBrush &brush)
  25178. {
  25179. mSelectedBrush = brush;
  25180. }
  25181. /*!
  25182. Sets the font of the text.
  25183. \see setSelectedFont, setColor
  25184. */
  25185. void QCPItemText::setFont(const QFont &font)
  25186. {
  25187. mFont = font;
  25188. }
  25189. /*!
  25190. Sets the font of the text that will be used when the item is selected.
  25191. \see setFont
  25192. */
  25193. void QCPItemText::setSelectedFont(const QFont &font)
  25194. {
  25195. mSelectedFont = font;
  25196. }
  25197. /*!
  25198. Sets the text that will be displayed. Multi-line texts are supported by inserting a line break
  25199. character, e.g. '\n'.
  25200. \see setFont, setColor, setTextAlignment
  25201. */
  25202. void QCPItemText::setText(const QString &text)
  25203. {
  25204. mText = text;
  25205. }
  25206. /*!
  25207. Sets which point of the text rect shall be aligned with \a position.
  25208. Examples:
  25209. \li If \a alignment is <tt>Qt::AlignHCenter | Qt::AlignTop</tt>, the text will be positioned such
  25210. that the top of the text rect will be horizontally centered on \a position.
  25211. \li If \a alignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt>, \a position will indicate the
  25212. bottom left corner of the text rect.
  25213. If you want to control the alignment of (multi-lined) text within the text rect, use \ref
  25214. setTextAlignment.
  25215. */
  25216. void QCPItemText::setPositionAlignment(Qt::Alignment alignment)
  25217. {
  25218. mPositionAlignment = alignment;
  25219. }
  25220. /*!
  25221. Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight).
  25222. */
  25223. void QCPItemText::setTextAlignment(Qt::Alignment alignment)
  25224. {
  25225. mTextAlignment = alignment;
  25226. }
  25227. /*!
  25228. Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated
  25229. around \a position.
  25230. */
  25231. void QCPItemText::setRotation(double degrees)
  25232. {
  25233. mRotation = degrees;
  25234. }
  25235. /*!
  25236. Sets the distance between the border of the text rectangle and the text. The appearance (and
  25237. visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush.
  25238. */
  25239. void QCPItemText::setPadding(const QMargins &padding)
  25240. {
  25241. mPadding = padding;
  25242. }
  25243. /* inherits documentation from base class */
  25244. double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25245. {
  25246. Q_UNUSED(details)
  25247. if (onlySelectable && !mSelectable)
  25248. return -1;
  25249. // The rect may be rotated, so we transform the actual clicked pos to the rotated
  25250. // coordinate system, so we can use the normal rectDistance function for non-rotated rects:
  25251. QPointF positionPixels(position->pixelPosition());
  25252. QTransform inputTransform;
  25253. inputTransform.translate(positionPixels.x(), positionPixels.y());
  25254. inputTransform.rotate(-mRotation);
  25255. inputTransform.translate(-positionPixels.x(), -positionPixels.y());
  25256. QPointF rotatedPos = inputTransform.map(pos);
  25257. QFontMetrics fontMetrics(mFont);
  25258. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  25259. QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  25260. QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment);
  25261. textBoxRect.moveTopLeft(textPos.toPoint());
  25262. return rectDistance(textBoxRect, rotatedPos, true);
  25263. }
  25264. /* inherits documentation from base class */
  25265. void QCPItemText::draw(QCPPainter *painter)
  25266. {
  25267. QPointF pos(position->pixelPosition());
  25268. QTransform transform = painter->transform();
  25269. transform.translate(pos.x(), pos.y());
  25270. if (!qFuzzyIsNull(mRotation))
  25271. transform.rotate(mRotation);
  25272. painter->setFont(mainFont());
  25273. QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  25274. QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  25275. QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
  25276. textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top()));
  25277. textBoxRect.moveTopLeft(textPos.toPoint());
  25278. int clipPad = qCeil(mainPen().widthF());
  25279. QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  25280. if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect())))
  25281. {
  25282. painter->setTransform(transform);
  25283. if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) ||
  25284. (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0))
  25285. {
  25286. painter->setPen(mainPen());
  25287. painter->setBrush(mainBrush());
  25288. painter->drawRect(textBoxRect);
  25289. }
  25290. painter->setBrush(Qt::NoBrush);
  25291. painter->setPen(QPen(mainColor()));
  25292. painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText);
  25293. }
  25294. }
  25295. /* inherits documentation from base class */
  25296. QPointF QCPItemText::anchorPixelPosition(int anchorId) const
  25297. {
  25298. // get actual rect points (pretty much copied from draw function):
  25299. QPointF pos(position->pixelPosition());
  25300. QTransform transform;
  25301. transform.translate(pos.x(), pos.y());
  25302. if (!qFuzzyIsNull(mRotation))
  25303. transform.rotate(mRotation);
  25304. QFontMetrics fontMetrics(mainFont());
  25305. QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText);
  25306. QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom());
  25307. QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation
  25308. textBoxRect.moveTopLeft(textPos.toPoint());
  25309. QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect));
  25310. switch (anchorId)
  25311. {
  25312. case aiTopLeft: return rectPoly.at(0);
  25313. case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5;
  25314. case aiTopRight: return rectPoly.at(1);
  25315. case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5;
  25316. case aiBottomRight: return rectPoly.at(2);
  25317. case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5;
  25318. case aiBottomLeft: return rectPoly.at(3);
  25319. case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5;
  25320. }
  25321. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25322. return {};
  25323. }
  25324. /*! \internal
  25325. Returns the point that must be given to the QPainter::drawText function (which expects the top
  25326. left point of the text rect), according to the position \a pos, the text bounding box \a rect and
  25327. the requested \a positionAlignment.
  25328. For example, if \a positionAlignment is <tt>Qt::AlignLeft | Qt::AlignBottom</tt> the returned point
  25329. will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally
  25330. drawn at that point, the lower left corner of the resulting text rect is at \a pos.
  25331. */
  25332. QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const
  25333. {
  25334. if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop))
  25335. return pos;
  25336. QPointF result = pos; // start at top left
  25337. if (positionAlignment.testFlag(Qt::AlignHCenter))
  25338. result.rx() -= rect.width()/2.0;
  25339. else if (positionAlignment.testFlag(Qt::AlignRight))
  25340. result.rx() -= rect.width();
  25341. if (positionAlignment.testFlag(Qt::AlignVCenter))
  25342. result.ry() -= rect.height()/2.0;
  25343. else if (positionAlignment.testFlag(Qt::AlignBottom))
  25344. result.ry() -= rect.height();
  25345. return result;
  25346. }
  25347. /*! \internal
  25348. Returns the font that should be used for drawing text. Returns mFont when the item is not selected
  25349. and mSelectedFont when it is.
  25350. */
  25351. QFont QCPItemText::mainFont() const
  25352. {
  25353. return mSelected ? mSelectedFont : mFont;
  25354. }
  25355. /*! \internal
  25356. Returns the color that should be used for drawing text. Returns mColor when the item is not
  25357. selected and mSelectedColor when it is.
  25358. */
  25359. QColor QCPItemText::mainColor() const
  25360. {
  25361. return mSelected ? mSelectedColor : mColor;
  25362. }
  25363. /*! \internal
  25364. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25365. and mSelectedPen when it is.
  25366. */
  25367. QPen QCPItemText::mainPen() const
  25368. {
  25369. return mSelected ? mSelectedPen : mPen;
  25370. }
  25371. /*! \internal
  25372. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  25373. is not selected and mSelectedBrush when it is.
  25374. */
  25375. QBrush QCPItemText::mainBrush() const
  25376. {
  25377. return mSelected ? mSelectedBrush : mBrush;
  25378. }
  25379. /* end of 'src/items/item-text.cpp' */
  25380. /* including file 'src/items/item-ellipse.cpp' */
  25381. /* modified 2021-03-29T02:30:44, size 7881 */
  25382. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25383. //////////////////// QCPItemEllipse
  25384. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25385. /*! \class QCPItemEllipse
  25386. \brief An ellipse
  25387. \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions."
  25388. It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in.
  25389. */
  25390. /*!
  25391. Creates an ellipse item and sets default values.
  25392. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25393. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25394. */
  25395. QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) :
  25396. QCPAbstractItem(parentPlot),
  25397. topLeft(createPosition(QLatin1String("topLeft"))),
  25398. bottomRight(createPosition(QLatin1String("bottomRight"))),
  25399. topLeftRim(createAnchor(QLatin1String("topLeftRim"), aiTopLeftRim)),
  25400. top(createAnchor(QLatin1String("top"), aiTop)),
  25401. topRightRim(createAnchor(QLatin1String("topRightRim"), aiTopRightRim)),
  25402. right(createAnchor(QLatin1String("right"), aiRight)),
  25403. bottomRightRim(createAnchor(QLatin1String("bottomRightRim"), aiBottomRightRim)),
  25404. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  25405. bottomLeftRim(createAnchor(QLatin1String("bottomLeftRim"), aiBottomLeftRim)),
  25406. left(createAnchor(QLatin1String("left"), aiLeft)),
  25407. center(createAnchor(QLatin1String("center"), aiCenter))
  25408. {
  25409. topLeft->setCoords(0, 1);
  25410. bottomRight->setCoords(1, 0);
  25411. setPen(QPen(Qt::black));
  25412. setSelectedPen(QPen(Qt::blue, 2));
  25413. setBrush(Qt::NoBrush);
  25414. setSelectedBrush(Qt::NoBrush);
  25415. }
  25416. QCPItemEllipse::~QCPItemEllipse()
  25417. {
  25418. }
  25419. /*!
  25420. Sets the pen that will be used to draw the line of the ellipse
  25421. \see setSelectedPen, setBrush
  25422. */
  25423. void QCPItemEllipse::setPen(const QPen &pen)
  25424. {
  25425. mPen = pen;
  25426. }
  25427. /*!
  25428. Sets the pen that will be used to draw the line of the ellipse when selected
  25429. \see setPen, setSelected
  25430. */
  25431. void QCPItemEllipse::setSelectedPen(const QPen &pen)
  25432. {
  25433. mSelectedPen = pen;
  25434. }
  25435. /*!
  25436. Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to
  25437. Qt::NoBrush.
  25438. \see setSelectedBrush, setPen
  25439. */
  25440. void QCPItemEllipse::setBrush(const QBrush &brush)
  25441. {
  25442. mBrush = brush;
  25443. }
  25444. /*!
  25445. Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a
  25446. brush to Qt::NoBrush.
  25447. \see setBrush
  25448. */
  25449. void QCPItemEllipse::setSelectedBrush(const QBrush &brush)
  25450. {
  25451. mSelectedBrush = brush;
  25452. }
  25453. /* inherits documentation from base class */
  25454. double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25455. {
  25456. Q_UNUSED(details)
  25457. if (onlySelectable && !mSelectable)
  25458. return -1;
  25459. QPointF p1 = topLeft->pixelPosition();
  25460. QPointF p2 = bottomRight->pixelPosition();
  25461. QPointF center((p1+p2)/2.0);
  25462. double a = qAbs(p1.x()-p2.x())/2.0;
  25463. double b = qAbs(p1.y()-p2.y())/2.0;
  25464. double x = pos.x()-center.x();
  25465. double y = pos.y()-center.y();
  25466. // distance to border:
  25467. double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b));
  25468. double result = qAbs(c-1)*qSqrt(x*x+y*y);
  25469. // filled ellipse, allow click inside to count as hit:
  25470. if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
  25471. {
  25472. if (x*x/(a*a) + y*y/(b*b) <= 1)
  25473. result = mParentPlot->selectionTolerance()*0.99;
  25474. }
  25475. return result;
  25476. }
  25477. /* inherits documentation from base class */
  25478. void QCPItemEllipse::draw(QCPPainter *painter)
  25479. {
  25480. QPointF p1 = topLeft->pixelPosition();
  25481. QPointF p2 = bottomRight->pixelPosition();
  25482. if (p1.toPoint() == p2.toPoint())
  25483. return;
  25484. QRectF ellipseRect = QRectF(p1, p2).normalized();
  25485. const int clipEnlarge = qCeil(mainPen().widthF());
  25486. QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
  25487. if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect
  25488. {
  25489. painter->setPen(mainPen());
  25490. painter->setBrush(mainBrush());
  25491. #ifdef __EXCEPTIONS
  25492. try // drawEllipse sometimes throws exceptions if ellipse is too big
  25493. {
  25494. #endif
  25495. painter->drawEllipse(ellipseRect);
  25496. #ifdef __EXCEPTIONS
  25497. } catch (...)
  25498. {
  25499. qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible";
  25500. setVisible(false);
  25501. }
  25502. #endif
  25503. }
  25504. }
  25505. /* inherits documentation from base class */
  25506. QPointF QCPItemEllipse::anchorPixelPosition(int anchorId) const
  25507. {
  25508. QRectF rect = QRectF(topLeft->pixelPosition(), bottomRight->pixelPosition());
  25509. switch (anchorId)
  25510. {
  25511. case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2);
  25512. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  25513. case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2);
  25514. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  25515. case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2);
  25516. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  25517. case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2);
  25518. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  25519. case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5;
  25520. }
  25521. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25522. return {};
  25523. }
  25524. /*! \internal
  25525. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25526. and mSelectedPen when it is.
  25527. */
  25528. QPen QCPItemEllipse::mainPen() const
  25529. {
  25530. return mSelected ? mSelectedPen : mPen;
  25531. }
  25532. /*! \internal
  25533. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  25534. is not selected and mSelectedBrush when it is.
  25535. */
  25536. QBrush QCPItemEllipse::mainBrush() const
  25537. {
  25538. return mSelected ? mSelectedBrush : mBrush;
  25539. }
  25540. /* end of 'src/items/item-ellipse.cpp' */
  25541. /* including file 'src/items/item-pixmap.cpp' */
  25542. /* modified 2021-03-29T02:30:44, size 10622 */
  25543. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25544. //////////////////// QCPItemPixmap
  25545. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25546. /*! \class QCPItemPixmap
  25547. \brief An arbitrary pixmap
  25548. \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions."
  25549. It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will
  25550. be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to
  25551. fit the rectangle or be drawn aligned to the topLeft position.
  25552. If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown
  25553. on the right side of the example image), the pixmap will be flipped in the respective
  25554. orientations.
  25555. */
  25556. /*!
  25557. Creates a rectangle item and sets default values.
  25558. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25559. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25560. */
  25561. QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) :
  25562. QCPAbstractItem(parentPlot),
  25563. topLeft(createPosition(QLatin1String("topLeft"))),
  25564. bottomRight(createPosition(QLatin1String("bottomRight"))),
  25565. top(createAnchor(QLatin1String("top"), aiTop)),
  25566. topRight(createAnchor(QLatin1String("topRight"), aiTopRight)),
  25567. right(createAnchor(QLatin1String("right"), aiRight)),
  25568. bottom(createAnchor(QLatin1String("bottom"), aiBottom)),
  25569. bottomLeft(createAnchor(QLatin1String("bottomLeft"), aiBottomLeft)),
  25570. left(createAnchor(QLatin1String("left"), aiLeft)),
  25571. mScaled(false),
  25572. mScaledPixmapInvalidated(true),
  25573. mAspectRatioMode(Qt::KeepAspectRatio),
  25574. mTransformationMode(Qt::SmoothTransformation)
  25575. {
  25576. topLeft->setCoords(0, 1);
  25577. bottomRight->setCoords(1, 0);
  25578. setPen(Qt::NoPen);
  25579. setSelectedPen(QPen(Qt::blue));
  25580. }
  25581. QCPItemPixmap::~QCPItemPixmap()
  25582. {
  25583. }
  25584. /*!
  25585. Sets the pixmap that will be displayed.
  25586. */
  25587. void QCPItemPixmap::setPixmap(const QPixmap &pixmap)
  25588. {
  25589. mPixmap = pixmap;
  25590. mScaledPixmapInvalidated = true;
  25591. if (mPixmap.isNull())
  25592. qDebug() << Q_FUNC_INFO << "pixmap is null";
  25593. }
  25594. /*!
  25595. Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a
  25596. bottomRight positions.
  25597. */
  25598. void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode)
  25599. {
  25600. mScaled = scaled;
  25601. mAspectRatioMode = aspectRatioMode;
  25602. mTransformationMode = transformationMode;
  25603. mScaledPixmapInvalidated = true;
  25604. }
  25605. /*!
  25606. Sets the pen that will be used to draw a border around the pixmap.
  25607. \see setSelectedPen, setBrush
  25608. */
  25609. void QCPItemPixmap::setPen(const QPen &pen)
  25610. {
  25611. mPen = pen;
  25612. }
  25613. /*!
  25614. Sets the pen that will be used to draw a border around the pixmap when selected
  25615. \see setPen, setSelected
  25616. */
  25617. void QCPItemPixmap::setSelectedPen(const QPen &pen)
  25618. {
  25619. mSelectedPen = pen;
  25620. }
  25621. /* inherits documentation from base class */
  25622. double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25623. {
  25624. Q_UNUSED(details)
  25625. if (onlySelectable && !mSelectable)
  25626. return -1;
  25627. return rectDistance(getFinalRect(), pos, true);
  25628. }
  25629. /* inherits documentation from base class */
  25630. void QCPItemPixmap::draw(QCPPainter *painter)
  25631. {
  25632. bool flipHorz = false;
  25633. bool flipVert = false;
  25634. QRect rect = getFinalRect(&flipHorz, &flipVert);
  25635. int clipPad = mainPen().style() == Qt::NoPen ? 0 : qCeil(mainPen().widthF());
  25636. QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad);
  25637. if (boundingRect.intersects(clipRect()))
  25638. {
  25639. updateScaledPixmap(rect, flipHorz, flipVert);
  25640. painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap);
  25641. QPen pen = mainPen();
  25642. if (pen.style() != Qt::NoPen)
  25643. {
  25644. painter->setPen(pen);
  25645. painter->setBrush(Qt::NoBrush);
  25646. painter->drawRect(rect);
  25647. }
  25648. }
  25649. }
  25650. /* inherits documentation from base class */
  25651. QPointF QCPItemPixmap::anchorPixelPosition(int anchorId) const
  25652. {
  25653. bool flipHorz = false;
  25654. bool flipVert = false;
  25655. QRect rect = getFinalRect(&flipHorz, &flipVert);
  25656. // we actually want denormal rects (negative width/height) here, so restore
  25657. // the flipped state:
  25658. if (flipHorz)
  25659. rect.adjust(rect.width(), 0, -rect.width(), 0);
  25660. if (flipVert)
  25661. rect.adjust(0, rect.height(), 0, -rect.height());
  25662. switch (anchorId)
  25663. {
  25664. case aiTop: return (rect.topLeft()+rect.topRight())*0.5;
  25665. case aiTopRight: return rect.topRight();
  25666. case aiRight: return (rect.topRight()+rect.bottomRight())*0.5;
  25667. case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5;
  25668. case aiBottomLeft: return rect.bottomLeft();
  25669. case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;
  25670. }
  25671. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  25672. return {};
  25673. }
  25674. /*! \internal
  25675. Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The
  25676. parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped
  25677. horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a
  25678. bottomRight.)
  25679. This function only creates the scaled pixmap when the buffered pixmap has a different size than
  25680. the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does
  25681. not cause expensive rescaling every time.
  25682. If scaling is disabled, sets mScaledPixmap to a null QPixmap.
  25683. */
  25684. void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert)
  25685. {
  25686. if (mPixmap.isNull())
  25687. return;
  25688. if (mScaled)
  25689. {
  25690. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25691. double devicePixelRatio = mPixmap.devicePixelRatio();
  25692. #else
  25693. double devicePixelRatio = 1.0;
  25694. #endif
  25695. if (finalRect.isNull())
  25696. finalRect = getFinalRect(&flipHorz, &flipVert);
  25697. if (mScaledPixmapInvalidated || finalRect.size() != mScaledPixmap.size()/devicePixelRatio)
  25698. {
  25699. mScaledPixmap = mPixmap.scaled(finalRect.size()*devicePixelRatio, mAspectRatioMode, mTransformationMode);
  25700. if (flipHorz || flipVert)
  25701. mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert));
  25702. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25703. mScaledPixmap.setDevicePixelRatio(devicePixelRatio);
  25704. #endif
  25705. }
  25706. } else if (!mScaledPixmap.isNull())
  25707. mScaledPixmap = QPixmap();
  25708. mScaledPixmapInvalidated = false;
  25709. }
  25710. /*! \internal
  25711. Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions
  25712. and scaling settings.
  25713. The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn
  25714. flipped horizontally or vertically in the returned rect. (The returned rect itself is always
  25715. normalized, i.e. the top left corner of the rect is actually further to the top/left than the
  25716. bottom right corner). This is the case when the item position \a topLeft is further to the
  25717. bottom/right than \a bottomRight.
  25718. If scaling is disabled, returns a rect with size of the original pixmap and the top left corner
  25719. aligned with the item position \a topLeft. The position \a bottomRight is ignored.
  25720. */
  25721. QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const
  25722. {
  25723. QRect result;
  25724. bool flipHorz = false;
  25725. bool flipVert = false;
  25726. QPoint p1 = topLeft->pixelPosition().toPoint();
  25727. QPoint p2 = bottomRight->pixelPosition().toPoint();
  25728. if (p1 == p2)
  25729. return {p1, QSize(0, 0)};
  25730. if (mScaled)
  25731. {
  25732. QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y());
  25733. QPoint topLeft = p1;
  25734. if (newSize.width() < 0)
  25735. {
  25736. flipHorz = true;
  25737. newSize.rwidth() *= -1;
  25738. topLeft.setX(p2.x());
  25739. }
  25740. if (newSize.height() < 0)
  25741. {
  25742. flipVert = true;
  25743. newSize.rheight() *= -1;
  25744. topLeft.setY(p2.y());
  25745. }
  25746. QSize scaledSize = mPixmap.size();
  25747. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25748. scaledSize /= mPixmap.devicePixelRatio();
  25749. scaledSize.scale(newSize*mPixmap.devicePixelRatio(), mAspectRatioMode);
  25750. #else
  25751. scaledSize.scale(newSize, mAspectRatioMode);
  25752. #endif
  25753. result = QRect(topLeft, scaledSize);
  25754. } else
  25755. {
  25756. #ifdef QCP_DEVICEPIXELRATIO_SUPPORTED
  25757. result = QRect(p1, mPixmap.size()/mPixmap.devicePixelRatio());
  25758. #else
  25759. result = QRect(p1, mPixmap.size());
  25760. #endif
  25761. }
  25762. if (flippedHorz)
  25763. *flippedHorz = flipHorz;
  25764. if (flippedVert)
  25765. *flippedVert = flipVert;
  25766. return result;
  25767. }
  25768. /*! \internal
  25769. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  25770. and mSelectedPen when it is.
  25771. */
  25772. QPen QCPItemPixmap::mainPen() const
  25773. {
  25774. return mSelected ? mSelectedPen : mPen;
  25775. }
  25776. /* end of 'src/items/item-pixmap.cpp' */
  25777. /* including file 'src/items/item-tracer.cpp' */
  25778. /* modified 2021-03-29T02:30:44, size 14645 */
  25779. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25780. //////////////////// QCPItemTracer
  25781. ////////////////////////////////////////////////////////////////////////////////////////////////////
  25782. /*! \class QCPItemTracer
  25783. \brief Item that sticks to QCPGraph data points
  25784. \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions."
  25785. The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt
  25786. the coordinate axes of the graph and update its \a position to be on the graph's data. This means
  25787. the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a
  25788. QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a
  25789. position will have no effect because they will be overriden in the next redraw (this is when the
  25790. coordinate update happens).
  25791. If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will
  25792. stay at the corresponding end of the graph.
  25793. With \ref setInterpolating you may specify whether the tracer may only stay exactly on data
  25794. points or whether it interpolates data points linearly, if given a key that lies between two data
  25795. points of the graph.
  25796. The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer
  25797. have no own visual appearance (set the style to \ref tsNone), and just connect other item
  25798. positions to the tracer \a position (used as an anchor) via \ref
  25799. QCPItemPosition::setParentAnchor.
  25800. \note The tracer position is only automatically updated upon redraws. So when the data of the
  25801. graph changes and immediately afterwards (without a redraw) the position coordinates of the
  25802. tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref
  25803. updatePosition must be called manually, prior to reading the tracer coordinates.
  25804. */
  25805. /*!
  25806. Creates a tracer item and sets default values.
  25807. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  25808. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  25809. */
  25810. QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) :
  25811. QCPAbstractItem(parentPlot),
  25812. position(createPosition(QLatin1String("position"))),
  25813. mSize(6),
  25814. mStyle(tsCrosshair),
  25815. mGraph(nullptr),
  25816. mGraphKey(0),
  25817. mInterpolating(false)
  25818. {
  25819. position->setCoords(0, 0);
  25820. setBrush(Qt::NoBrush);
  25821. setSelectedBrush(Qt::NoBrush);
  25822. setPen(QPen(Qt::black));
  25823. setSelectedPen(QPen(Qt::blue, 2));
  25824. }
  25825. QCPItemTracer::~QCPItemTracer()
  25826. {
  25827. }
  25828. /*!
  25829. Sets the pen that will be used to draw the line of the tracer
  25830. \see setSelectedPen, setBrush
  25831. */
  25832. void QCPItemTracer::setPen(const QPen &pen)
  25833. {
  25834. mPen = pen;
  25835. }
  25836. /*!
  25837. Sets the pen that will be used to draw the line of the tracer when selected
  25838. \see setPen, setSelected
  25839. */
  25840. void QCPItemTracer::setSelectedPen(const QPen &pen)
  25841. {
  25842. mSelectedPen = pen;
  25843. }
  25844. /*!
  25845. Sets the brush that will be used to draw any fills of the tracer
  25846. \see setSelectedBrush, setPen
  25847. */
  25848. void QCPItemTracer::setBrush(const QBrush &brush)
  25849. {
  25850. mBrush = brush;
  25851. }
  25852. /*!
  25853. Sets the brush that will be used to draw any fills of the tracer, when selected.
  25854. \see setBrush, setSelected
  25855. */
  25856. void QCPItemTracer::setSelectedBrush(const QBrush &brush)
  25857. {
  25858. mSelectedBrush = brush;
  25859. }
  25860. /*!
  25861. Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare
  25862. does, \ref tsCrosshair does not).
  25863. */
  25864. void QCPItemTracer::setSize(double size)
  25865. {
  25866. mSize = size;
  25867. }
  25868. /*!
  25869. Sets the style/visual appearance of the tracer.
  25870. If you only want to use the tracer \a position as an anchor for other items, set \a style to
  25871. \ref tsNone.
  25872. */
  25873. void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style)
  25874. {
  25875. mStyle = style;
  25876. }
  25877. /*!
  25878. Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type
  25879. QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph.
  25880. To free the tracer from any graph, set \a graph to \c nullptr. The tracer \a position can then be
  25881. placed freely like any other item position. This is the state the tracer will assume when its
  25882. graph gets deleted while still attached to it.
  25883. \see setGraphKey
  25884. */
  25885. void QCPItemTracer::setGraph(QCPGraph *graph)
  25886. {
  25887. if (graph)
  25888. {
  25889. if (graph->parentPlot() == mParentPlot)
  25890. {
  25891. position->setType(QCPItemPosition::PositionType:: ptPlotCoords);
  25892. position->setAxes(graph->keyAxis(), graph->valueAxis());
  25893. mGraph = graph;
  25894. updatePosition();
  25895. } else
  25896. qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item";
  25897. } else
  25898. {
  25899. mGraph = nullptr;
  25900. }
  25901. }
  25902. /*!
  25903. Sets the key of the graph's data point the tracer will be positioned at. This is the only free
  25904. coordinate of a tracer when attached to a graph.
  25905. Depending on \ref setInterpolating, the tracer will be either positioned on the data point
  25906. closest to \a key, or will stay exactly at \a key and interpolate the value linearly.
  25907. \see setGraph, setInterpolating
  25908. */
  25909. void QCPItemTracer::setGraphKey(double key)
  25910. {
  25911. mGraphKey = key;
  25912. }
  25913. /*!
  25914. Sets whether the value of the graph's data points shall be interpolated, when positioning the
  25915. tracer.
  25916. If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on
  25917. the data point of the graph which is closest to the key, but which is not necessarily exactly
  25918. there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and
  25919. the appropriate value will be interpolated from the graph's data points linearly.
  25920. \see setGraph, setGraphKey
  25921. */
  25922. void QCPItemTracer::setInterpolating(bool enabled)
  25923. {
  25924. mInterpolating = enabled;
  25925. }
  25926. /* inherits documentation from base class */
  25927. double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  25928. {
  25929. Q_UNUSED(details)
  25930. if (onlySelectable && !mSelectable)
  25931. return -1;
  25932. QPointF center(position->pixelPosition());
  25933. double w = mSize/2.0;
  25934. QRect clip = clipRect();
  25935. switch (mStyle)
  25936. {
  25937. case tsNone: return -1;
  25938. case tsPlus:
  25939. {
  25940. if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25941. return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(center+QPointF(-w, 0), center+QPointF(w, 0)),
  25942. QCPVector2D(pos).distanceSquaredToLine(center+QPointF(0, -w), center+QPointF(0, w))));
  25943. break;
  25944. }
  25945. case tsCrosshair:
  25946. {
  25947. return qSqrt(qMin(QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(clip.left(), center.y()), QCPVector2D(clip.right(), center.y())),
  25948. QCPVector2D(pos).distanceSquaredToLine(QCPVector2D(center.x(), clip.top()), QCPVector2D(center.x(), clip.bottom()))));
  25949. }
  25950. case tsCircle:
  25951. {
  25952. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25953. {
  25954. // distance to border:
  25955. double centerDist = QCPVector2D(center-pos).length();
  25956. double circleLine = w;
  25957. double result = qAbs(centerDist-circleLine);
  25958. // filled ellipse, allow click inside to count as hit:
  25959. if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0)
  25960. {
  25961. if (centerDist <= circleLine)
  25962. result = mParentPlot->selectionTolerance()*0.99;
  25963. }
  25964. return result;
  25965. }
  25966. break;
  25967. }
  25968. case tsSquare:
  25969. {
  25970. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25971. {
  25972. QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w));
  25973. bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0;
  25974. return rectDistance(rect, pos, filledRect);
  25975. }
  25976. break;
  25977. }
  25978. }
  25979. return -1;
  25980. }
  25981. /* inherits documentation from base class */
  25982. void QCPItemTracer::draw(QCPPainter *painter)
  25983. {
  25984. updatePosition();
  25985. if (mStyle == tsNone)
  25986. return;
  25987. painter->setPen(mainPen());
  25988. painter->setBrush(mainBrush());
  25989. QPointF center(position->pixelPosition());
  25990. double w = mSize/2.0;
  25991. QRect clip = clipRect();
  25992. switch (mStyle)
  25993. {
  25994. case tsNone: return;
  25995. case tsPlus:
  25996. {
  25997. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  25998. {
  25999. painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0)));
  26000. painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w)));
  26001. }
  26002. break;
  26003. }
  26004. case tsCrosshair:
  26005. {
  26006. if (center.y() > clip.top() && center.y() < clip.bottom())
  26007. painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y()));
  26008. if (center.x() > clip.left() && center.x() < clip.right())
  26009. painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom()));
  26010. break;
  26011. }
  26012. case tsCircle:
  26013. {
  26014. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  26015. painter->drawEllipse(center, w, w);
  26016. break;
  26017. }
  26018. case tsSquare:
  26019. {
  26020. if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect()))
  26021. painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w)));
  26022. break;
  26023. }
  26024. }
  26025. }
  26026. /*!
  26027. If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a
  26028. position to reside on the graph data, depending on the configured key (\ref setGraphKey).
  26029. It is called automatically on every redraw and normally doesn't need to be called manually. One
  26030. exception is when you want to read the tracer coordinates via \a position and are not sure that
  26031. the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw.
  26032. In that situation, call this function before accessing \a position, to make sure you don't get
  26033. out-of-date coordinates.
  26034. If there is no graph set on this tracer, this function does nothing.
  26035. */
  26036. void QCPItemTracer::updatePosition()
  26037. {
  26038. if (mGraph)
  26039. {
  26040. if (mParentPlot->hasPlottable(mGraph))
  26041. {
  26042. if (mGraph->data()->size() > 1)
  26043. {
  26044. QCPGraphDataContainer::const_iterator first = mGraph->data()->constBegin();
  26045. QCPGraphDataContainer::const_iterator last = mGraph->data()->constEnd()-1;
  26046. if (mGraphKey <= first->key)
  26047. position->setCoords(first->key, first->value);
  26048. else if (mGraphKey >= last->key)
  26049. position->setCoords(last->key, last->value);
  26050. else
  26051. {
  26052. QCPGraphDataContainer::const_iterator it = mGraph->data()->findBegin(mGraphKey);
  26053. if (it != mGraph->data()->constEnd()) // mGraphKey is not exactly on last iterator, but somewhere between iterators
  26054. {
  26055. QCPGraphDataContainer::const_iterator prevIt = it;
  26056. ++it; // won't advance to constEnd because we handled that case (mGraphKey >= last->key) before
  26057. if (mInterpolating)
  26058. {
  26059. // interpolate between iterators around mGraphKey:
  26060. double slope = 0;
  26061. if (!qFuzzyCompare(double(it->key), double(prevIt->key)))
  26062. slope = (it->value-prevIt->value)/(it->key-prevIt->key);
  26063. position->setCoords(mGraphKey, (mGraphKey-prevIt->key)*slope+prevIt->value);
  26064. } else
  26065. {
  26066. // find iterator with key closest to mGraphKey:
  26067. if (mGraphKey < (prevIt->key+it->key)*0.5)
  26068. position->setCoords(prevIt->key, prevIt->value);
  26069. else
  26070. position->setCoords(it->key, it->value);
  26071. }
  26072. } else // mGraphKey is exactly on last iterator (should actually be caught when comparing first/last keys, but this is a failsafe for fp uncertainty)
  26073. position->setCoords(it->key, it->value);
  26074. }
  26075. } else if (mGraph->data()->size() == 1)
  26076. {
  26077. QCPGraphDataContainer::const_iterator it = mGraph->data()->constBegin();
  26078. position->setCoords(it->key, it->value);
  26079. } else
  26080. qDebug() << Q_FUNC_INFO << "graph has no data";
  26081. } else
  26082. qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)";
  26083. }
  26084. }
  26085. /*! \internal
  26086. Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected
  26087. and mSelectedPen when it is.
  26088. */
  26089. QPen QCPItemTracer::mainPen() const
  26090. {
  26091. return mSelected ? mSelectedPen : mPen;
  26092. }
  26093. /*! \internal
  26094. Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item
  26095. is not selected and mSelectedBrush when it is.
  26096. */
  26097. QBrush QCPItemTracer::mainBrush() const
  26098. {
  26099. return mSelected ? mSelectedBrush : mBrush;
  26100. }
  26101. /* end of 'src/items/item-tracer.cpp' */
  26102. /* including file 'src/items/item-bracket.cpp' */
  26103. /* modified 2021-03-29T02:30:44, size 10705 */
  26104. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26105. //////////////////// QCPItemBracket
  26106. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26107. /*! \class QCPItemBracket
  26108. \brief A bracket for referencing/highlighting certain parts in the plot.
  26109. \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions."
  26110. It has two positions, \a left and \a right, which define the span of the bracket. If \a left is
  26111. actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the
  26112. example image.
  26113. The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket
  26114. stretches away from the embraced span, can be controlled with \ref setLength.
  26115. \image html QCPItemBracket-length.png
  26116. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  26117. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  26118. It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine
  26119. or QCPItemCurve) or a text label (QCPItemText), to the bracket.
  26120. */
  26121. /*!
  26122. Creates a bracket item and sets default values.
  26123. The created item is automatically registered with \a parentPlot. This QCustomPlot instance takes
  26124. ownership of the item, so do not delete it manually but use QCustomPlot::removeItem() instead.
  26125. */
  26126. QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) :
  26127. QCPAbstractItem(parentPlot),
  26128. left(createPosition(QLatin1String("left"))),
  26129. right(createPosition(QLatin1String("right"))),
  26130. center(createAnchor(QLatin1String("center"), aiCenter)),
  26131. mLength(8),
  26132. mStyle(bsCalligraphic)
  26133. {
  26134. left->setCoords(0, 0);
  26135. right->setCoords(1, 1);
  26136. setPen(QPen(Qt::black));
  26137. setSelectedPen(QPen(Qt::blue, 2));
  26138. }
  26139. QCPItemBracket::~QCPItemBracket()
  26140. {
  26141. }
  26142. /*!
  26143. Sets the pen that will be used to draw the bracket.
  26144. Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the
  26145. stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use
  26146. \ref setLength, which has a similar effect.
  26147. \see setSelectedPen
  26148. */
  26149. void QCPItemBracket::setPen(const QPen &pen)
  26150. {
  26151. mPen = pen;
  26152. }
  26153. /*!
  26154. Sets the pen that will be used to draw the bracket when selected
  26155. \see setPen, setSelected
  26156. */
  26157. void QCPItemBracket::setSelectedPen(const QPen &pen)
  26158. {
  26159. mSelectedPen = pen;
  26160. }
  26161. /*!
  26162. Sets the \a length in pixels how far the bracket extends in the direction towards the embraced
  26163. span of the bracket (i.e. perpendicular to the <i>left</i>-<i>right</i>-direction)
  26164. \image html QCPItemBracket-length.png
  26165. <center>Demonstrating the effect of different values for \ref setLength, for styles \ref
  26166. bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.</center>
  26167. */
  26168. void QCPItemBracket::setLength(double length)
  26169. {
  26170. mLength = length;
  26171. }
  26172. /*!
  26173. Sets the style of the bracket, i.e. the shape/visual appearance.
  26174. \see setPen
  26175. */
  26176. void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style)
  26177. {
  26178. mStyle = style;
  26179. }
  26180. /* inherits documentation from base class */
  26181. double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  26182. {
  26183. Q_UNUSED(details)
  26184. if (onlySelectable && !mSelectable)
  26185. return -1;
  26186. QCPVector2D p(pos);
  26187. QCPVector2D leftVec(left->pixelPosition());
  26188. QCPVector2D rightVec(right->pixelPosition());
  26189. if (leftVec.toPoint() == rightVec.toPoint())
  26190. return -1;
  26191. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  26192. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  26193. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  26194. switch (mStyle)
  26195. {
  26196. case QCPItemBracket::bsSquare:
  26197. case QCPItemBracket::bsRound:
  26198. {
  26199. double a = p.distanceSquaredToLine(centerVec-widthVec, centerVec+widthVec);
  26200. double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec, centerVec-widthVec);
  26201. double c = p.distanceSquaredToLine(centerVec+widthVec+lengthVec, centerVec+widthVec);
  26202. return qSqrt(qMin(qMin(a, b), c));
  26203. }
  26204. case QCPItemBracket::bsCurly:
  26205. case QCPItemBracket::bsCalligraphic:
  26206. {
  26207. double a = p.distanceSquaredToLine(centerVec-widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
  26208. double b = p.distanceSquaredToLine(centerVec-widthVec+lengthVec*0.7, centerVec-widthVec*0.75+lengthVec*0.15);
  26209. double c = p.distanceSquaredToLine(centerVec+widthVec*0.75+lengthVec*0.15, centerVec+lengthVec*0.3);
  26210. double d = p.distanceSquaredToLine(centerVec+widthVec+lengthVec*0.7, centerVec+widthVec*0.75+lengthVec*0.15);
  26211. return qSqrt(qMin(qMin(a, b), qMin(c, d)));
  26212. }
  26213. }
  26214. return -1;
  26215. }
  26216. /* inherits documentation from base class */
  26217. void QCPItemBracket::draw(QCPPainter *painter)
  26218. {
  26219. QCPVector2D leftVec(left->pixelPosition());
  26220. QCPVector2D rightVec(right->pixelPosition());
  26221. if (leftVec.toPoint() == rightVec.toPoint())
  26222. return;
  26223. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  26224. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  26225. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  26226. QPolygon boundingPoly;
  26227. boundingPoly << leftVec.toPoint() << rightVec.toPoint()
  26228. << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint();
  26229. const int clipEnlarge = qCeil(mainPen().widthF());
  26230. QRect clip = clipRect().adjusted(-clipEnlarge, -clipEnlarge, clipEnlarge, clipEnlarge);
  26231. if (clip.intersects(boundingPoly.boundingRect()))
  26232. {
  26233. painter->setPen(mainPen());
  26234. switch (mStyle)
  26235. {
  26236. case bsSquare:
  26237. {
  26238. painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF());
  26239. painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
  26240. painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26241. break;
  26242. }
  26243. case bsRound:
  26244. {
  26245. painter->setBrush(Qt::NoBrush);
  26246. QPainterPath path;
  26247. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  26248. path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF());
  26249. path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26250. painter->drawPath(path);
  26251. break;
  26252. }
  26253. case bsCurly:
  26254. {
  26255. painter->setBrush(Qt::NoBrush);
  26256. QPainterPath path;
  26257. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  26258. path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+lengthVec).toPointF(), centerVec.toPointF());
  26259. path.cubicTo((centerVec-0.4*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26260. painter->drawPath(path);
  26261. break;
  26262. }
  26263. case bsCalligraphic:
  26264. {
  26265. painter->setPen(Qt::NoPen);
  26266. painter->setBrush(QBrush(mainPen().color()));
  26267. QPainterPath path;
  26268. path.moveTo((centerVec+widthVec+lengthVec).toPointF());
  26269. path.cubicTo((centerVec+widthVec-lengthVec*0.8).toPointF(), (centerVec+0.4*widthVec+0.8*lengthVec).toPointF(), centerVec.toPointF());
  26270. path.cubicTo((centerVec-0.4*widthVec+0.8*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8).toPointF(), (centerVec-widthVec+lengthVec).toPointF());
  26271. path.cubicTo((centerVec-widthVec-lengthVec*0.5).toPointF(), (centerVec-0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+lengthVec*0.2).toPointF());
  26272. path.cubicTo((centerVec+0.2*widthVec+1.2*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5).toPointF(), (centerVec+widthVec+lengthVec).toPointF());
  26273. painter->drawPath(path);
  26274. break;
  26275. }
  26276. }
  26277. }
  26278. }
  26279. /* inherits documentation from base class */
  26280. QPointF QCPItemBracket::anchorPixelPosition(int anchorId) const
  26281. {
  26282. QCPVector2D leftVec(left->pixelPosition());
  26283. QCPVector2D rightVec(right->pixelPosition());
  26284. if (leftVec.toPoint() == rightVec.toPoint())
  26285. return leftVec.toPointF();
  26286. QCPVector2D widthVec = (rightVec-leftVec)*0.5;
  26287. QCPVector2D lengthVec = widthVec.perpendicular().normalized()*mLength;
  26288. QCPVector2D centerVec = (rightVec+leftVec)*0.5-lengthVec;
  26289. switch (anchorId)
  26290. {
  26291. case aiCenter:
  26292. return centerVec.toPointF();
  26293. }
  26294. qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId;
  26295. return {};
  26296. }
  26297. /*! \internal
  26298. Returns the pen that should be used for drawing lines. Returns mPen when the
  26299. item is not selected and mSelectedPen when it is.
  26300. */
  26301. QPen QCPItemBracket::mainPen() const
  26302. {
  26303. return mSelected ? mSelectedPen : mPen;
  26304. }
  26305. /* end of 'src/items/item-bracket.cpp' */
  26306. /* including file 'src/polar/radialaxis.cpp' */
  26307. /* modified 2021-03-29T02:30:44, size 49415 */
  26308. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26309. //////////////////// QCPPolarAxisRadial
  26310. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26311. /*! \class QCPPolarAxisRadial
  26312. \brief The radial axis inside a radial plot
  26313. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  26314. functionality to be incomplete, as well as changing public interfaces in the future.
  26315. Each axis holds an instance of QCPAxisTicker which is used to generate the tick coordinates and
  26316. tick labels. You can access the currently installed \ref ticker or set a new one (possibly one of
  26317. the specialized subclasses, or your own subclass) via \ref setTicker. For details, see the
  26318. documentation of QCPAxisTicker.
  26319. */
  26320. /* start of documentation of inline functions */
  26321. /*! \fn QSharedPointer<QCPAxisTicker> QCPPolarAxisRadial::ticker() const
  26322. Returns a modifiable shared pointer to the currently installed axis ticker. The axis ticker is
  26323. responsible for generating the tick positions and tick labels of this axis. You can access the
  26324. \ref QCPAxisTicker with this method and modify basic properties such as the approximate tick count
  26325. (\ref QCPAxisTicker::setTickCount).
  26326. You can gain more control over the axis ticks by setting a different \ref QCPAxisTicker subclass, see
  26327. the documentation there. A new axis ticker can be set with \ref setTicker.
  26328. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  26329. ticker simply by passing the same shared pointer to multiple axes.
  26330. \see setTicker
  26331. */
  26332. /* end of documentation of inline functions */
  26333. /* start of documentation of signals */
  26334. /*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange)
  26335. This signal is emitted when the range of this axis has changed. You can connect it to the \ref
  26336. setRange slot of another axis to communicate the new range to the other axis, in order for it to
  26337. be synchronized.
  26338. You may also manipulate/correct the range with \ref setRange in a slot connected to this signal.
  26339. This is useful if for example a maximum range span shall not be exceeded, or if the lower/upper
  26340. range shouldn't go beyond certain values (see \ref QCPRange::bounded). For example, the following
  26341. slot would limit the x axis to ranges between 0 and 10:
  26342. \code
  26343. customPlot->xAxis->setRange(newRange.bounded(0, 10))
  26344. \endcode
  26345. */
  26346. /*! \fn void QCPPolarAxisRadial::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange)
  26347. \overload
  26348. Additionally to the new range, this signal also provides the previous range held by the axis as
  26349. \a oldRange.
  26350. */
  26351. /*! \fn void QCPPolarAxisRadial::scaleTypeChanged(QCPPolarAxisRadial::ScaleType scaleType);
  26352. This signal is emitted when the scale type changes, by calls to \ref setScaleType
  26353. */
  26354. /*! \fn void QCPPolarAxisRadial::selectionChanged(QCPPolarAxisRadial::SelectableParts selection)
  26355. This signal is emitted when the selection state of this axis has changed, either by user interaction
  26356. or by a direct call to \ref setSelectedParts.
  26357. */
  26358. /*! \fn void QCPPolarAxisRadial::selectableChanged(const QCPPolarAxisRadial::SelectableParts &parts);
  26359. This signal is emitted when the selectability changes, by calls to \ref setSelectableParts
  26360. */
  26361. /* end of documentation of signals */
  26362. /*!
  26363. Constructs an Axis instance of Type \a type for the axis rect \a parent.
  26364. Usually it isn't necessary to instantiate axes directly, because you can let QCustomPlot create
  26365. them for you with \ref QCPAxisRect::addAxis. If you want to use own QCPAxis-subclasses however,
  26366. create them manually and then inject them also via \ref QCPAxisRect::addAxis.
  26367. */
  26368. QCPPolarAxisRadial::QCPPolarAxisRadial(QCPPolarAxisAngular *parent) :
  26369. QCPLayerable(parent->parentPlot(), QString(), parent),
  26370. mRangeDrag(true),
  26371. mRangeZoom(true),
  26372. mRangeZoomFactor(0.85),
  26373. // axis base:
  26374. mAngularAxis(parent),
  26375. mAngle(45),
  26376. mAngleReference(arAngularAxis),
  26377. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  26378. mSelectedParts(spNone),
  26379. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  26380. mSelectedBasePen(QPen(Qt::blue, 2)),
  26381. // axis label:
  26382. mLabelPadding(0),
  26383. mLabel(),
  26384. mLabelFont(mParentPlot->font()),
  26385. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  26386. mLabelColor(Qt::black),
  26387. mSelectedLabelColor(Qt::blue),
  26388. // tick labels:
  26389. // mTickLabelPadding(0), in label painter
  26390. mTickLabels(true),
  26391. // mTickLabelRotation(0), in label painter
  26392. mTickLabelFont(mParentPlot->font()),
  26393. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  26394. mTickLabelColor(Qt::black),
  26395. mSelectedTickLabelColor(Qt::blue),
  26396. mNumberPrecision(6),
  26397. mNumberFormatChar('g'),
  26398. mNumberBeautifulPowers(true),
  26399. mNumberMultiplyCross(false),
  26400. // ticks and subticks:
  26401. mTicks(true),
  26402. mSubTicks(true),
  26403. mTickLengthIn(5),
  26404. mTickLengthOut(0),
  26405. mSubTickLengthIn(2),
  26406. mSubTickLengthOut(0),
  26407. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  26408. mSelectedTickPen(QPen(Qt::blue, 2)),
  26409. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  26410. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  26411. // scale and range:
  26412. mRange(0, 5),
  26413. mRangeReversed(false),
  26414. mScaleType(QCPPolarAxisRadial::ScaleType:: stLinear),
  26415. // internal members:
  26416. mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect
  26417. mTicker(new QCPAxisTicker),
  26418. mLabelPainter(mParentPlot)
  26419. {
  26420. setParent(parent);
  26421. setAntialiased(true);
  26422. setTickLabelPadding(5);
  26423. setTickLabelRotation(0);
  26424. setTickLabelMode(lmUpright);
  26425. mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::AnchorReferenceType::artTangent);
  26426. mLabelPainter.setAbbreviateDecimalPowers(false);
  26427. }
  26428. QCPPolarAxisRadial::~QCPPolarAxisRadial()
  26429. {
  26430. }
  26431. QCPPolarAxisRadial::LabelMode QCPPolarAxisRadial::tickLabelMode() const
  26432. {
  26433. switch (mLabelPainter.anchorMode())
  26434. {
  26435. case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright;
  26436. case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated;
  26437. default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break;
  26438. }
  26439. return lmUpright;
  26440. }
  26441. /* No documentation as it is a property getter */
  26442. QString QCPPolarAxisRadial::numberFormat() const
  26443. {
  26444. QString result;
  26445. result.append(mNumberFormatChar);
  26446. if (mNumberBeautifulPowers)
  26447. {
  26448. result.append(QLatin1Char('b'));
  26449. if (mNumberMultiplyCross)
  26450. result.append(QLatin1Char('c'));
  26451. }
  26452. return result;
  26453. }
  26454. /* No documentation as it is a property getter */
  26455. int QCPPolarAxisRadial::tickLengthIn() const
  26456. {
  26457. return mTickLengthIn;
  26458. }
  26459. /* No documentation as it is a property getter */
  26460. int QCPPolarAxisRadial::tickLengthOut() const
  26461. {
  26462. return mTickLengthOut;
  26463. }
  26464. /* No documentation as it is a property getter */
  26465. int QCPPolarAxisRadial::subTickLengthIn() const
  26466. {
  26467. return mSubTickLengthIn;
  26468. }
  26469. /* No documentation as it is a property getter */
  26470. int QCPPolarAxisRadial::subTickLengthOut() const
  26471. {
  26472. return mSubTickLengthOut;
  26473. }
  26474. /* No documentation as it is a property getter */
  26475. int QCPPolarAxisRadial::labelPadding() const
  26476. {
  26477. return mLabelPadding;
  26478. }
  26479. void QCPPolarAxisRadial::setRangeDrag(bool enabled)
  26480. {
  26481. mRangeDrag = enabled;
  26482. }
  26483. void QCPPolarAxisRadial::setRangeZoom(bool enabled)
  26484. {
  26485. mRangeZoom = enabled;
  26486. }
  26487. void QCPPolarAxisRadial::setRangeZoomFactor(double factor)
  26488. {
  26489. mRangeZoomFactor = factor;
  26490. }
  26491. /*!
  26492. Sets whether the axis uses a linear scale or a logarithmic scale.
  26493. Note that this method controls the coordinate transformation. For logarithmic scales, you will
  26494. likely also want to use a logarithmic tick spacing and labeling, which can be achieved by setting
  26495. the axis ticker to an instance of \ref QCPAxisTickerLog :
  26496. \snippet documentation/doc-code-snippets/mainwindow.cpp qcpaxisticker-log-creation
  26497. See the documentation of \ref QCPAxisTickerLog about the details of logarithmic axis tick
  26498. creation.
  26499. \ref setNumberPrecision
  26500. */
  26501. void QCPPolarAxisRadial::setScaleType(QCPPolarAxisRadial::ScaleType type)
  26502. {
  26503. if (mScaleType != type)
  26504. {
  26505. mScaleType = type;
  26506. if (mScaleType == ScaleType::stLogarithmic)
  26507. setRange(mRange.sanitizedForLogScale());
  26508. //mCachedMarginValid = false;
  26509. emit scaleTypeChanged(mScaleType);
  26510. }
  26511. }
  26512. /*!
  26513. Sets the range of the axis.
  26514. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  26515. is always synchronized with the other axis range, when it changes.
  26516. To invert the direction of an axis, use \ref setRangeReversed.
  26517. */
  26518. void QCPPolarAxisRadial::setRange(const QCPRange &range)
  26519. {
  26520. if (range.lower == mRange.lower && range.upper == mRange.upper)
  26521. return;
  26522. if (!QCPRange::validRange(range)) return;
  26523. QCPRange oldRange = mRange;
  26524. if (mScaleType == ScaleType::stLogarithmic)
  26525. {
  26526. mRange = range.sanitizedForLogScale();
  26527. } else
  26528. {
  26529. mRange = range.sanitizedForLinScale();
  26530. }
  26531. emit rangeChanged(mRange);
  26532. emit rangeChanged(mRange, oldRange);
  26533. }
  26534. /*!
  26535. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  26536. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  26537. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  26538. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  26539. directly.
  26540. \see SelectablePart, setSelectedParts
  26541. */
  26542. void QCPPolarAxisRadial::setSelectableParts(const SelectableParts &selectable)
  26543. {
  26544. if (mSelectableParts != selectable)
  26545. {
  26546. mSelectableParts = selectable;
  26547. emit selectableChanged(mSelectableParts);
  26548. }
  26549. }
  26550. /*!
  26551. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  26552. is selected, it uses a different pen/font.
  26553. The entire selection mechanism for axes is handled automatically when \ref
  26554. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  26555. wish to change the selection state manually.
  26556. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  26557. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  26558. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  26559. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  26560. */
  26561. void QCPPolarAxisRadial::setSelectedParts(const SelectableParts &selected)
  26562. {
  26563. if (mSelectedParts != selected)
  26564. {
  26565. mSelectedParts = selected;
  26566. emit selectionChanged(mSelectedParts);
  26567. }
  26568. }
  26569. /*!
  26570. \overload
  26571. Sets the lower and upper bound of the axis range.
  26572. To invert the direction of an axis, use \ref setRangeReversed.
  26573. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  26574. */
  26575. void QCPPolarAxisRadial::setRange(double lower, double upper)
  26576. {
  26577. if (lower == mRange.lower && upper == mRange.upper)
  26578. return;
  26579. if (!QCPRange::validRange(lower, upper)) return;
  26580. QCPRange oldRange = mRange;
  26581. mRange.lower = lower;
  26582. mRange.upper = upper;
  26583. if (mScaleType == ScaleType::stLogarithmic)
  26584. {
  26585. mRange = mRange.sanitizedForLogScale();
  26586. } else
  26587. {
  26588. mRange = mRange.sanitizedForLinScale();
  26589. }
  26590. emit rangeChanged(mRange);
  26591. emit rangeChanged(mRange, oldRange);
  26592. }
  26593. /*!
  26594. \overload
  26595. Sets the range of the axis.
  26596. The \a position coordinate indicates together with the \a alignment parameter, where the new
  26597. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  26598. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  26599. or center of the range to be aligned with \a position. Any other values of \a alignment will
  26600. default to Qt::AlignCenter.
  26601. */
  26602. void QCPPolarAxisRadial::setRange(double position, double size, Qt::AlignmentFlag alignment)
  26603. {
  26604. if (alignment == Qt::AlignLeft)
  26605. setRange(position, position+size);
  26606. else if (alignment == Qt::AlignRight)
  26607. setRange(position-size, position);
  26608. else // alignment == Qt::AlignCenter
  26609. setRange(position-size/2.0, position+size/2.0);
  26610. }
  26611. /*!
  26612. Sets the lower bound of the axis range. The upper bound is not changed.
  26613. \see setRange
  26614. */
  26615. void QCPPolarAxisRadial::setRangeLower(double lower)
  26616. {
  26617. if (mRange.lower == lower)
  26618. return;
  26619. QCPRange oldRange = mRange;
  26620. mRange.lower = lower;
  26621. if (mScaleType == ScaleType::stLogarithmic)
  26622. {
  26623. mRange = mRange.sanitizedForLogScale();
  26624. } else
  26625. {
  26626. mRange = mRange.sanitizedForLinScale();
  26627. }
  26628. emit rangeChanged(mRange);
  26629. emit rangeChanged(mRange, oldRange);
  26630. }
  26631. /*!
  26632. Sets the upper bound of the axis range. The lower bound is not changed.
  26633. \see setRange
  26634. */
  26635. void QCPPolarAxisRadial::setRangeUpper(double upper)
  26636. {
  26637. if (mRange.upper == upper)
  26638. return;
  26639. QCPRange oldRange = mRange;
  26640. mRange.upper = upper;
  26641. if (mScaleType == ScaleType::stLogarithmic)
  26642. {
  26643. mRange = mRange.sanitizedForLogScale();
  26644. } else
  26645. {
  26646. mRange = mRange.sanitizedForLinScale();
  26647. }
  26648. emit rangeChanged(mRange);
  26649. emit rangeChanged(mRange, oldRange);
  26650. }
  26651. /*!
  26652. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  26653. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  26654. direction of increasing values is inverted.
  26655. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  26656. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  26657. upper part.
  26658. */
  26659. void QCPPolarAxisRadial::setRangeReversed(bool reversed)
  26660. {
  26661. mRangeReversed = reversed;
  26662. }
  26663. void QCPPolarAxisRadial::setAngle(double degrees)
  26664. {
  26665. mAngle = degrees;
  26666. }
  26667. void QCPPolarAxisRadial::setAngleReference(AngleReference reference)
  26668. {
  26669. mAngleReference = reference;
  26670. }
  26671. /*!
  26672. The axis ticker is responsible for generating the tick positions and tick labels. See the
  26673. documentation of QCPAxisTicker for details on how to work with axis tickers.
  26674. You can change the tick positioning/labeling behaviour of this axis by setting a different
  26675. QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
  26676. ticker, access it via \ref ticker.
  26677. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  26678. ticker simply by passing the same shared pointer to multiple axes.
  26679. \see ticker
  26680. */
  26681. void QCPPolarAxisRadial::setTicker(QSharedPointer<QCPAxisTicker> ticker)
  26682. {
  26683. if (ticker)
  26684. mTicker = ticker;
  26685. else
  26686. qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
  26687. // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
  26688. }
  26689. /*!
  26690. Sets whether tick marks are displayed.
  26691. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  26692. that, see \ref setTickLabels.
  26693. \see setSubTicks
  26694. */
  26695. void QCPPolarAxisRadial::setTicks(bool show)
  26696. {
  26697. if (mTicks != show)
  26698. {
  26699. mTicks = show;
  26700. //mCachedMarginValid = false;
  26701. }
  26702. }
  26703. /*!
  26704. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  26705. */
  26706. void QCPPolarAxisRadial::setTickLabels(bool show)
  26707. {
  26708. if (mTickLabels != show)
  26709. {
  26710. mTickLabels = show;
  26711. //mCachedMarginValid = false;
  26712. if (!mTickLabels)
  26713. mTickVectorLabels.clear();
  26714. }
  26715. }
  26716. /*!
  26717. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  26718. \see setLabelPadding, setPadding
  26719. */
  26720. void QCPPolarAxisRadial::setTickLabelPadding(int padding)
  26721. {
  26722. mLabelPainter.setPadding(padding);
  26723. }
  26724. /*!
  26725. Sets the font of the tick labels.
  26726. \see setTickLabels, setTickLabelColor
  26727. */
  26728. void QCPPolarAxisRadial::setTickLabelFont(const QFont &font)
  26729. {
  26730. if (font != mTickLabelFont)
  26731. {
  26732. mTickLabelFont = font;
  26733. //mCachedMarginValid = false;
  26734. }
  26735. }
  26736. /*!
  26737. Sets the color of the tick labels.
  26738. \see setTickLabels, setTickLabelFont
  26739. */
  26740. void QCPPolarAxisRadial::setTickLabelColor(const QColor &color)
  26741. {
  26742. mTickLabelColor = color;
  26743. }
  26744. /*!
  26745. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  26746. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  26747. from -90 to 90 degrees.
  26748. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  26749. other angles, the label is drawn with an offset such that it seems to point toward or away from
  26750. the tick mark.
  26751. */
  26752. void QCPPolarAxisRadial::setTickLabelRotation(double degrees)
  26753. {
  26754. mLabelPainter.setRotation(degrees);
  26755. }
  26756. void QCPPolarAxisRadial::setTickLabelMode(LabelMode mode)
  26757. {
  26758. switch (mode)
  26759. {
  26760. case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break;
  26761. case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break;
  26762. }
  26763. }
  26764. /*!
  26765. Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
  26766. of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
  26767. that, see the "Argument Formats" section in the detailed description of the QString class.
  26768. \a formatCode is a string of one, two or three characters. The first character is identical to
  26769. the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
  26770. format, 'g'/'G' scientific or fixed, whichever is shorter.
  26771. The second and third characters are optional and specific to QCustomPlot:\n
  26772. If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g.
  26773. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for
  26774. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  26775. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  26776. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  26777. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  26778. cross and 183 (0xB7) for the dot.
  26779. Examples for \a formatCode:
  26780. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  26781. normal scientific format is used
  26782. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  26783. beautifully typeset decimal powers and a dot as multiplication sign
  26784. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  26785. multiplication sign
  26786. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  26787. powers. Format code will be reduced to 'f'.
  26788. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  26789. code will not be changed.
  26790. */
  26791. void QCPPolarAxisRadial::setNumberFormat(const QString &formatCode)
  26792. {
  26793. if (formatCode.isEmpty())
  26794. {
  26795. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  26796. return;
  26797. }
  26798. //mCachedMarginValid = false;
  26799. // interpret first char as number format char:
  26800. QString allowedFormatChars(QLatin1String("eEfgG"));
  26801. if (allowedFormatChars.contains(formatCode.at(0)))
  26802. {
  26803. mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
  26804. } else
  26805. {
  26806. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  26807. return;
  26808. }
  26809. if (formatCode.length() < 2)
  26810. {
  26811. mNumberBeautifulPowers = false;
  26812. mNumberMultiplyCross = false;
  26813. } else
  26814. {
  26815. // interpret second char as indicator for beautiful decimal powers:
  26816. if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
  26817. mNumberBeautifulPowers = true;
  26818. else
  26819. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  26820. if (formatCode.length() < 3)
  26821. {
  26822. mNumberMultiplyCross = false;
  26823. } else
  26824. {
  26825. // interpret third char as indicator for dot or cross multiplication symbol:
  26826. if (formatCode.at(2) == QLatin1Char('c'))
  26827. mNumberMultiplyCross = true;
  26828. else if (formatCode.at(2) == QLatin1Char('d'))
  26829. mNumberMultiplyCross = false;
  26830. else
  26831. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  26832. }
  26833. }
  26834. mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers);
  26835. mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot);
  26836. }
  26837. /*!
  26838. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  26839. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  26840. \ref setNumberFormat
  26841. */
  26842. void QCPPolarAxisRadial::setNumberPrecision(int precision)
  26843. {
  26844. if (mNumberPrecision != precision)
  26845. {
  26846. mNumberPrecision = precision;
  26847. //mCachedMarginValid = false;
  26848. }
  26849. }
  26850. /*!
  26851. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  26852. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  26853. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  26854. they won't collide with the ticks.
  26855. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  26856. */
  26857. void QCPPolarAxisRadial::setTickLength(int inside, int outside)
  26858. {
  26859. setTickLengthIn(inside);
  26860. setTickLengthOut(outside);
  26861. }
  26862. /*!
  26863. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  26864. inside the plot.
  26865. \see setTickLengthOut, setTickLength, setSubTickLength
  26866. */
  26867. void QCPPolarAxisRadial::setTickLengthIn(int inside)
  26868. {
  26869. if (mTickLengthIn != inside)
  26870. {
  26871. mTickLengthIn = inside;
  26872. }
  26873. }
  26874. /*!
  26875. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  26876. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  26877. increase their distance to the axis accordingly, so they won't collide with the ticks.
  26878. \see setTickLengthIn, setTickLength, setSubTickLength
  26879. */
  26880. void QCPPolarAxisRadial::setTickLengthOut(int outside)
  26881. {
  26882. if (mTickLengthOut != outside)
  26883. {
  26884. mTickLengthOut = outside;
  26885. //mCachedMarginValid = false; // only outside tick length can change margin
  26886. }
  26887. }
  26888. /*!
  26889. Sets whether sub tick marks are displayed.
  26890. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
  26891. \see setTicks
  26892. */
  26893. void QCPPolarAxisRadial::setSubTicks(bool show)
  26894. {
  26895. if (mSubTicks != show)
  26896. {
  26897. mSubTicks = show;
  26898. //mCachedMarginValid = false;
  26899. }
  26900. }
  26901. /*!
  26902. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  26903. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  26904. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  26905. so they won't collide with the ticks.
  26906. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  26907. */
  26908. void QCPPolarAxisRadial::setSubTickLength(int inside, int outside)
  26909. {
  26910. setSubTickLengthIn(inside);
  26911. setSubTickLengthOut(outside);
  26912. }
  26913. /*!
  26914. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  26915. the plot.
  26916. \see setSubTickLengthOut, setSubTickLength, setTickLength
  26917. */
  26918. void QCPPolarAxisRadial::setSubTickLengthIn(int inside)
  26919. {
  26920. if (mSubTickLengthIn != inside)
  26921. {
  26922. mSubTickLengthIn = inside;
  26923. }
  26924. }
  26925. /*!
  26926. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  26927. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  26928. distance to the axis accordingly, so they won't collide with the ticks.
  26929. \see setSubTickLengthIn, setSubTickLength, setTickLength
  26930. */
  26931. void QCPPolarAxisRadial::setSubTickLengthOut(int outside)
  26932. {
  26933. if (mSubTickLengthOut != outside)
  26934. {
  26935. mSubTickLengthOut = outside;
  26936. //mCachedMarginValid = false; // only outside tick length can change margin
  26937. }
  26938. }
  26939. /*!
  26940. Sets the pen, the axis base line is drawn with.
  26941. \see setTickPen, setSubTickPen
  26942. */
  26943. void QCPPolarAxisRadial::setBasePen(const QPen &pen)
  26944. {
  26945. mBasePen = pen;
  26946. }
  26947. /*!
  26948. Sets the pen, tick marks will be drawn with.
  26949. \see setTickLength, setBasePen
  26950. */
  26951. void QCPPolarAxisRadial::setTickPen(const QPen &pen)
  26952. {
  26953. mTickPen = pen;
  26954. }
  26955. /*!
  26956. Sets the pen, subtick marks will be drawn with.
  26957. \see setSubTickCount, setSubTickLength, setBasePen
  26958. */
  26959. void QCPPolarAxisRadial::setSubTickPen(const QPen &pen)
  26960. {
  26961. mSubTickPen = pen;
  26962. }
  26963. /*!
  26964. Sets the font of the axis label.
  26965. \see setLabelColor
  26966. */
  26967. void QCPPolarAxisRadial::setLabelFont(const QFont &font)
  26968. {
  26969. if (mLabelFont != font)
  26970. {
  26971. mLabelFont = font;
  26972. //mCachedMarginValid = false;
  26973. }
  26974. }
  26975. /*!
  26976. Sets the color of the axis label.
  26977. \see setLabelFont
  26978. */
  26979. void QCPPolarAxisRadial::setLabelColor(const QColor &color)
  26980. {
  26981. mLabelColor = color;
  26982. }
  26983. /*!
  26984. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  26985. its orientation. To disable axis labels, pass an empty string as \a str.
  26986. */
  26987. void QCPPolarAxisRadial::setLabel(const QString &str)
  26988. {
  26989. if (mLabel != str)
  26990. {
  26991. mLabel = str;
  26992. //mCachedMarginValid = false;
  26993. }
  26994. }
  26995. /*!
  26996. Sets the distance between the tick labels and the axis label.
  26997. \see setTickLabelPadding, setPadding
  26998. */
  26999. void QCPPolarAxisRadial::setLabelPadding(int padding)
  27000. {
  27001. if (mLabelPadding != padding)
  27002. {
  27003. mLabelPadding = padding;
  27004. //mCachedMarginValid = false;
  27005. }
  27006. }
  27007. /*!
  27008. Sets the font that is used for tick labels when they are selected.
  27009. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27010. */
  27011. void QCPPolarAxisRadial::setSelectedTickLabelFont(const QFont &font)
  27012. {
  27013. if (font != mSelectedTickLabelFont)
  27014. {
  27015. mSelectedTickLabelFont = font;
  27016. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  27017. }
  27018. }
  27019. /*!
  27020. Sets the font that is used for the axis label when it is selected.
  27021. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27022. */
  27023. void QCPPolarAxisRadial::setSelectedLabelFont(const QFont &font)
  27024. {
  27025. mSelectedLabelFont = font;
  27026. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  27027. }
  27028. /*!
  27029. Sets the color that is used for tick labels when they are selected.
  27030. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27031. */
  27032. void QCPPolarAxisRadial::setSelectedTickLabelColor(const QColor &color)
  27033. {
  27034. if (color != mSelectedTickLabelColor)
  27035. {
  27036. mSelectedTickLabelColor = color;
  27037. }
  27038. }
  27039. /*!
  27040. Sets the color that is used for the axis label when it is selected.
  27041. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27042. */
  27043. void QCPPolarAxisRadial::setSelectedLabelColor(const QColor &color)
  27044. {
  27045. mSelectedLabelColor = color;
  27046. }
  27047. /*!
  27048. Sets the pen that is used to draw the axis base line when selected.
  27049. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27050. */
  27051. void QCPPolarAxisRadial::setSelectedBasePen(const QPen &pen)
  27052. {
  27053. mSelectedBasePen = pen;
  27054. }
  27055. /*!
  27056. Sets the pen that is used to draw the (major) ticks when selected.
  27057. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27058. */
  27059. void QCPPolarAxisRadial::setSelectedTickPen(const QPen &pen)
  27060. {
  27061. mSelectedTickPen = pen;
  27062. }
  27063. /*!
  27064. Sets the pen that is used to draw the subticks when selected.
  27065. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  27066. */
  27067. void QCPPolarAxisRadial::setSelectedSubTickPen(const QPen &pen)
  27068. {
  27069. mSelectedSubTickPen = pen;
  27070. }
  27071. /*!
  27072. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  27073. bounds of the range. The range is simply moved by \a diff.
  27074. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  27075. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  27076. */
  27077. void QCPPolarAxisRadial::moveRange(double diff)
  27078. {
  27079. QCPRange oldRange = mRange;
  27080. if (mScaleType == ScaleType::stLinear)
  27081. {
  27082. mRange.lower += diff;
  27083. mRange.upper += diff;
  27084. } else // mScaleType == stLogarithmic
  27085. {
  27086. mRange.lower *= diff;
  27087. mRange.upper *= diff;
  27088. }
  27089. emit rangeChanged(mRange);
  27090. emit rangeChanged(mRange, oldRange);
  27091. }
  27092. /*!
  27093. Scales the range of this axis by \a factor around the center of the current axis range. For
  27094. example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
  27095. range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
  27096. the center will have moved symmetrically closer).
  27097. If you wish to scale around a different coordinate than the current axis range center, use the
  27098. overload \ref scaleRange(double factor, double center).
  27099. */
  27100. void QCPPolarAxisRadial::scaleRange(double factor)
  27101. {
  27102. scaleRange(factor, range().center());
  27103. }
  27104. /*! \overload
  27105. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  27106. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  27107. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  27108. around 1.0 will have moved symmetrically closer to 1.0).
  27109. \see scaleRange(double factor)
  27110. */
  27111. void QCPPolarAxisRadial::scaleRange(double factor, double center)
  27112. {
  27113. QCPRange oldRange = mRange;
  27114. if (mScaleType == ScaleType::stLinear)
  27115. {
  27116. QCPRange newRange;
  27117. newRange.lower = (mRange.lower-center)*factor + center;
  27118. newRange.upper = (mRange.upper-center)*factor + center;
  27119. if (QCPRange::validRange(newRange))
  27120. mRange = newRange.sanitizedForLinScale();
  27121. } else // mScaleType == ScaleType::stLogarithmic
  27122. {
  27123. if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range
  27124. {
  27125. QCPRange newRange;
  27126. newRange.lower = qPow(mRange.lower/center, factor)*center;
  27127. newRange.upper = qPow(mRange.upper/center, factor)*center;
  27128. if (QCPRange::validRange(newRange))
  27129. mRange = newRange.sanitizedForLogScale();
  27130. } else
  27131. qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center;
  27132. }
  27133. emit rangeChanged(mRange);
  27134. emit rangeChanged(mRange, oldRange);
  27135. }
  27136. /*!
  27137. Changes the axis range such that all plottables associated with this axis are fully visible in
  27138. that dimension.
  27139. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  27140. */
  27141. void QCPPolarAxisRadial::rescale(bool onlyVisiblePlottables)
  27142. {
  27143. Q_UNUSED(onlyVisiblePlottables)
  27144. /* TODO
  27145. QList<QCPAbstractPlottable*> p = plottables();
  27146. QCPRange newRange;
  27147. bool haveRange = false;
  27148. for (int i=0; i<p.size(); ++i)
  27149. {
  27150. if (!p.at(i)->realVisibility() && onlyVisiblePlottables)
  27151. continue;
  27152. QCPRange plottableRange;
  27153. bool currentFoundRange;
  27154. QCP::SignDomain signDomain = QCP::SignDomain::sdBoth;
  27155. if (mScaleType == ScaleType::stLogarithmic)
  27156. signDomain = (mRange.upper < 0 ? QCP::SignDomain::sdNegative : QCP::sdPositive);
  27157. if (p.at(i)->keyAxis() == this)
  27158. plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain);
  27159. else
  27160. plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain);
  27161. if (currentFoundRange)
  27162. {
  27163. if (!haveRange)
  27164. newRange = plottableRange;
  27165. else
  27166. newRange.expand(plottableRange);
  27167. haveRange = true;
  27168. }
  27169. }
  27170. if (haveRange)
  27171. {
  27172. 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
  27173. {
  27174. 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
  27175. if (mScaleType == stLinear)
  27176. {
  27177. newRange.lower = center-mRange.size()/2.0;
  27178. newRange.upper = center+mRange.size()/2.0;
  27179. } else // mScaleType == ScaleType::stLogarithmic
  27180. {
  27181. newRange.lower = center/qSqrt(mRange.upper/mRange.lower);
  27182. newRange.upper = center*qSqrt(mRange.upper/mRange.lower);
  27183. }
  27184. }
  27185. setRange(newRange);
  27186. }
  27187. */
  27188. }
  27189. /*!
  27190. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  27191. */
  27192. void QCPPolarAxisRadial::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const
  27193. {
  27194. QCPVector2D posVector(pixelPos-mCenter);
  27195. radiusCoord = radiusToCoord(posVector.length());
  27196. angleCoord = mAngularAxis->angleRadToCoord(posVector.angle());
  27197. }
  27198. /*!
  27199. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  27200. */
  27201. QPointF QCPPolarAxisRadial::coordToPixel(double angleCoord, double radiusCoord) const
  27202. {
  27203. const double radiusPixel = coordToRadius(radiusCoord);
  27204. const double angleRad = mAngularAxis->coordToAngleRad(angleCoord);
  27205. return QPointF(mCenter.x()+qCos(angleRad)*radiusPixel, mCenter.y()+qSin(angleRad)*radiusPixel);
  27206. }
  27207. double QCPPolarAxisRadial::coordToRadius(double coord) const
  27208. {
  27209. if (mScaleType == ScaleType::stLinear)
  27210. {
  27211. if (!mRangeReversed)
  27212. return (coord-mRange.lower)/mRange.size()*mRadius;
  27213. else
  27214. return (mRange.upper-coord)/mRange.size()*mRadius;
  27215. } else // mScaleType == ScaleType::stLogarithmic
  27216. {
  27217. 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 if (coord <= 0.0 && mRange.upper >= 0.0) // invalid value for logarithmic scale, just return outside visible range
  27220. return !mRangeReversed ? mRadius-200 :mRadius+200;
  27221. else
  27222. {
  27223. if (!mRangeReversed)
  27224. return qLn(coord/mRange.lower)/qLn(mRange.upper/mRange.lower)*mRadius;
  27225. else
  27226. return qLn(mRange.upper/coord)/qLn(mRange.upper/mRange.lower)*mRadius;
  27227. }
  27228. }
  27229. }
  27230. double QCPPolarAxisRadial::radiusToCoord(double radius) const
  27231. {
  27232. if (mScaleType == ScaleType::stLinear)
  27233. {
  27234. if (!mRangeReversed)
  27235. return (radius)/mRadius*mRange.size()+mRange.lower;
  27236. else
  27237. return -(radius)/mRadius*mRange.size()+mRange.upper;
  27238. } else // mScaleType == ScaleType::stLogarithmic
  27239. {
  27240. if (!mRangeReversed)
  27241. return qPow(mRange.upper/mRange.lower, (radius)/mRadius)*mRange.lower;
  27242. else
  27243. return qPow(mRange.upper/mRange.lower, (-radius)/mRadius)*mRange.upper;
  27244. }
  27245. }
  27246. /*!
  27247. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  27248. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  27249. function does not change the current selection state of the axis.
  27250. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  27251. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  27252. */
  27253. QCPPolarAxisRadial::SelectablePart QCPPolarAxisRadial::getPartAt(const QPointF &pos) const
  27254. {
  27255. Q_UNUSED(pos) // TODO remove later
  27256. if (!mVisible)
  27257. return spNone;
  27258. /*
  27259. TODO:
  27260. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  27261. return spAxis;
  27262. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  27263. return spTickLabels;
  27264. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  27265. return spAxisLabel;
  27266. else */
  27267. return spNone;
  27268. }
  27269. /* inherits documentation from base class */
  27270. double QCPPolarAxisRadial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  27271. {
  27272. if (!mParentPlot) return -1;
  27273. SelectablePart part = getPartAt(pos);
  27274. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  27275. return -1;
  27276. if (details)
  27277. details->setValue(part);
  27278. return mParentPlot->selectionTolerance()*0.99;
  27279. }
  27280. /* inherits documentation from base class */
  27281. void QCPPolarAxisRadial::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  27282. {
  27283. Q_UNUSED(event)
  27284. SelectablePart part = details.value<SelectablePart>();
  27285. if (mSelectableParts.testFlag(part))
  27286. {
  27287. SelectableParts selBefore = mSelectedParts;
  27288. setSelectedParts(additive ? mSelectedParts^part : part);
  27289. if (selectionStateChanged)
  27290. *selectionStateChanged = mSelectedParts != selBefore;
  27291. }
  27292. }
  27293. /* inherits documentation from base class */
  27294. void QCPPolarAxisRadial::deselectEvent(bool *selectionStateChanged)
  27295. {
  27296. SelectableParts selBefore = mSelectedParts;
  27297. setSelectedParts(mSelectedParts & ~mSelectableParts);
  27298. if (selectionStateChanged)
  27299. *selectionStateChanged = mSelectedParts != selBefore;
  27300. }
  27301. /*! \internal
  27302. This mouse event reimplementation provides the functionality to let the user drag individual axes
  27303. exclusively, by startig the drag on top of the axis.
  27304. For the axis to accept this event and perform the single axis drag, the parent \ref QCPAxisRect
  27305. must be configured accordingly, i.e. it must allow range dragging in the orientation of this axis
  27306. (\ref QCPAxisRect::setRangeDrag) and this axis must be a draggable axis (\ref
  27307. QCPAxisRect::setRangeDragAxes)
  27308. \seebaseclassmethod
  27309. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  27310. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  27311. */
  27312. void QCPPolarAxisRadial::mousePressEvent(QMouseEvent *event, const QVariant &details)
  27313. {
  27314. Q_UNUSED(details)
  27315. if (!mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  27316. {
  27317. event->ignore();
  27318. return;
  27319. }
  27320. if (event->buttons() & Qt::LeftButton)
  27321. {
  27322. mDragging = true;
  27323. // initialize antialiasing backup in case we start dragging:
  27324. if (mParentPlot->noAntialiasingOnDrag())
  27325. {
  27326. mAADragBackup = mParentPlot->antialiasedElements();
  27327. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  27328. }
  27329. // Mouse range dragging interaction:
  27330. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  27331. mDragStartRange = mRange;
  27332. }
  27333. }
  27334. /*! \internal
  27335. This mouse event reimplementation provides the functionality to let the user drag individual axes
  27336. exclusively, by startig the drag on top of the axis.
  27337. \seebaseclassmethod
  27338. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  27339. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  27340. \see QCPAxis::mousePressEvent
  27341. */
  27342. void QCPPolarAxisRadial::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  27343. {
  27344. Q_UNUSED(event) // TODO remove later
  27345. Q_UNUSED(startPos) // TODO remove later
  27346. if (mDragging)
  27347. {
  27348. /* TODO
  27349. const double startPixel = orientation() == Qt::Horizontal ? startPos.x() : startPos.y();
  27350. const double currentPixel = orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y();
  27351. if (mScaleType == QCPPolarAxisRadial::stLinear)
  27352. {
  27353. const double diff = pixelToCoord(startPixel) - pixelToCoord(currentPixel);
  27354. setRange(mDragStartRange.lower+diff, mDragStartRange.upper+diff);
  27355. } else if (mScaleType == QCPPolarAxisRadial::stLogarithmic)
  27356. {
  27357. const double diff = pixelToCoord(startPixel) / pixelToCoord(currentPixel);
  27358. setRange(mDragStartRange.lower*diff, mDragStartRange.upper*diff);
  27359. }
  27360. */
  27361. if (mParentPlot->noAntialiasingOnDrag())
  27362. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  27363. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  27364. }
  27365. }
  27366. /*! \internal
  27367. This mouse event reimplementation provides the functionality to let the user drag individual axes
  27368. exclusively, by startig the drag on top of the axis.
  27369. \seebaseclassmethod
  27370. \note The dragging of possibly multiple axes at once by starting the drag anywhere in the axis
  27371. rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::mousePressEvent.
  27372. \see QCPAxis::mousePressEvent
  27373. */
  27374. void QCPPolarAxisRadial::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  27375. {
  27376. Q_UNUSED(event)
  27377. Q_UNUSED(startPos)
  27378. mDragging = false;
  27379. if (mParentPlot->noAntialiasingOnDrag())
  27380. {
  27381. mParentPlot->setAntialiasedElements(mAADragBackup);
  27382. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  27383. }
  27384. }
  27385. /*! \internal
  27386. This mouse event reimplementation provides the functionality to let the user zoom individual axes
  27387. exclusively, by performing the wheel event on top of the axis.
  27388. For the axis to accept this event and perform the single axis zoom, the parent \ref QCPAxisRect
  27389. must be configured accordingly, i.e. it must allow range zooming in the orientation of this axis
  27390. (\ref QCPAxisRect::setRangeZoom) and this axis must be a zoomable axis (\ref
  27391. QCPAxisRect::setRangeZoomAxes)
  27392. \seebaseclassmethod
  27393. \note The zooming of possibly multiple axes at once by performing the wheel event anywhere in the
  27394. axis rect is handled by the axis rect's mouse event, e.g. \ref QCPAxisRect::wheelEvent.
  27395. */
  27396. void QCPPolarAxisRadial::wheelEvent(QWheelEvent *event)
  27397. {
  27398. // Mouse range zooming interaction:
  27399. if (!mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  27400. {
  27401. event->ignore();
  27402. return;
  27403. }
  27404. // TODO:
  27405. //const double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually
  27406. //const double factor = qPow(mRangeZoomFactor, wheelSteps);
  27407. //scaleRange(factor, pixelToCoord(orientation() == Qt::Horizontal ? event->pos().x() : event->pos().y()));
  27408. mParentPlot->replot();
  27409. }
  27410. void QCPPolarAxisRadial::updateGeometry(const QPointF &center, double radius)
  27411. {
  27412. mCenter = center;
  27413. mRadius = radius;
  27414. if (mRadius < 1) mRadius = 1;
  27415. }
  27416. /*! \internal
  27417. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  27418. before drawing axis lines.
  27419. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  27420. This function takes into account the local setting of the antialiasing flag as well as the
  27421. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  27422. QCustomPlot::setNotAntialiasedElements.
  27423. \seebaseclassmethod
  27424. \see setAntialiased
  27425. */
  27426. void QCPPolarAxisRadial::applyDefaultAntialiasingHint(QCPPainter *painter) const
  27427. {
  27428. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  27429. }
  27430. /*! \internal
  27431. Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance.
  27432. \seebaseclassmethod
  27433. */
  27434. void QCPPolarAxisRadial::draw(QCPPainter *painter)
  27435. {
  27436. const double axisAngleRad = (mAngle+(mAngleReference==arAngularAxis ? mAngularAxis->angle() : 0))/180.0*M_PI;
  27437. const QPointF axisVector(qCos(axisAngleRad), qSin(axisAngleRad)); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF
  27438. const QPointF tickNormal = QCPVector2D(axisVector).perpendicular().toPointF(); // semantically should be QCPVector2D, but we save time in loops when we keep it as QPointF
  27439. // draw baseline:
  27440. painter->setPen(getBasePen());
  27441. painter->drawLine(QLineF(mCenter, mCenter+axisVector*(mRadius-0.5)));
  27442. // draw subticks:
  27443. if (!mSubTickVector.isEmpty())
  27444. {
  27445. painter->setPen(getSubTickPen());
  27446. for (int i=0; i<mSubTickVector.size(); ++i)
  27447. {
  27448. const QPointF tickPosition = mCenter+axisVector*coordToRadius(mSubTickVector.at(i));
  27449. painter->drawLine(QLineF(tickPosition-tickNormal*mSubTickLengthIn, tickPosition+tickNormal*mSubTickLengthOut));
  27450. }
  27451. }
  27452. // draw ticks and labels:
  27453. if (!mTickVector.isEmpty())
  27454. {
  27455. mLabelPainter.setAnchorReference(mCenter-axisVector); // subtract (normalized) axisVector, just to prevent degenerate tangents for tick label at exact lower axis range
  27456. mLabelPainter.setFont(getTickLabelFont());
  27457. mLabelPainter.setColor(getTickLabelColor());
  27458. const QPen ticksPen = getTickPen();
  27459. painter->setPen(ticksPen);
  27460. for (int i=0; i<mTickVector.size(); ++i)
  27461. {
  27462. const double r = coordToRadius(mTickVector.at(i));
  27463. const QPointF tickPosition = mCenter+axisVector*r;
  27464. painter->drawLine(QLineF(tickPosition-tickNormal*mTickLengthIn, tickPosition+tickNormal*mTickLengthOut));
  27465. // possibly draw tick labels:
  27466. if (!mTickVectorLabels.isEmpty())
  27467. {
  27468. if ((!mRangeReversed && (i < mTickVectorLabels.count()-1 || mRadius-r > 10)) ||
  27469. (mRangeReversed && (i > 0 || mRadius-r > 10))) // skip last label if it's closer than 10 pixels to angular axis
  27470. mLabelPainter.drawTickLabel(painter, tickPosition+tickNormal*mSubTickLengthOut, mTickVectorLabels.at(i));
  27471. }
  27472. }
  27473. }
  27474. }
  27475. /*! \internal
  27476. Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
  27477. QCPAxisTicker::generate on the currently installed ticker.
  27478. If a change in the label text/count is detected, the cached axis margin is invalidated to make
  27479. sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
  27480. */
  27481. void QCPPolarAxisRadial::setupTickVectors()
  27482. {
  27483. if (!mParentPlot) return;
  27484. if ((!mTicks && !mTickLabels) || mRange.size() <= 0) return;
  27485. mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0);
  27486. }
  27487. /*! \internal
  27488. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  27489. is either mSelectedBasePen or mBasePen.
  27490. */
  27491. QPen QCPPolarAxisRadial::getBasePen() const
  27492. {
  27493. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  27494. }
  27495. /*! \internal
  27496. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  27497. is either mSelectedTickPen or mTickPen.
  27498. */
  27499. QPen QCPPolarAxisRadial::getTickPen() const
  27500. {
  27501. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  27502. }
  27503. /*! \internal
  27504. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  27505. is either mSelectedSubTickPen or mSubTickPen.
  27506. */
  27507. QPen QCPPolarAxisRadial::getSubTickPen() const
  27508. {
  27509. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  27510. }
  27511. /*! \internal
  27512. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  27513. is either mSelectedTickLabelFont or mTickLabelFont.
  27514. */
  27515. QFont QCPPolarAxisRadial::getTickLabelFont() const
  27516. {
  27517. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  27518. }
  27519. /*! \internal
  27520. Returns the font that is used to draw the axis label. Depending on the selection state, this
  27521. is either mSelectedLabelFont or mLabelFont.
  27522. */
  27523. QFont QCPPolarAxisRadial::getLabelFont() const
  27524. {
  27525. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  27526. }
  27527. /*! \internal
  27528. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  27529. is either mSelectedTickLabelColor or mTickLabelColor.
  27530. */
  27531. QColor QCPPolarAxisRadial::getTickLabelColor() const
  27532. {
  27533. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  27534. }
  27535. /*! \internal
  27536. Returns the color that is used to draw the axis label. Depending on the selection state, this
  27537. is either mSelectedLabelColor or mLabelColor.
  27538. */
  27539. QColor QCPPolarAxisRadial::getLabelColor() const
  27540. {
  27541. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  27542. }
  27543. /* inherits documentation from base class */
  27544. QCP::Interaction QCPPolarAxisRadial::selectionCategory() const
  27545. {
  27546. return QCP::iSelectAxes;
  27547. }
  27548. /* end of 'src/polar/radialaxis.cpp' */
  27549. /* including file 'src/polar/layoutelement-angularaxis.cpp' */
  27550. /* modified 2021-03-29T02:30:44, size 57266 */
  27551. ////////////////////////////////////////////////////////////////////////////////////////////////////
  27552. //////////////////// QCPPolarAxisAngular
  27553. ////////////////////////////////////////////////////////////////////////////////////////////////////
  27554. /*! \class QCPPolarAxisAngular
  27555. \brief The main container for polar plots, representing the angular axis as a circle
  27556. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  27557. functionality to be incomplete, as well as changing public interfaces in the future.
  27558. */
  27559. /* start documentation of inline functions */
  27560. /*! \fn QCPLayoutInset *QCPPolarAxisAngular::insetLayout() const
  27561. Returns the inset layout of this axis rect. It can be used to place other layout elements (or
  27562. even layouts with multiple other elements) inside/on top of an axis rect.
  27563. \see QCPLayoutInset
  27564. */
  27565. /*! \fn int QCPPolarAxisAngular::left() const
  27566. Returns the pixel position of the left border of this axis rect. Margins are not taken into
  27567. account here, so the returned value is with respect to the inner \ref rect.
  27568. */
  27569. /*! \fn int QCPPolarAxisAngular::right() const
  27570. Returns the pixel position of the right border of this axis rect. Margins are not taken into
  27571. account here, so the returned value is with respect to the inner \ref rect.
  27572. */
  27573. /*! \fn int QCPPolarAxisAngular::top() const
  27574. Returns the pixel position of the top border of this axis rect. Margins are not taken into
  27575. account here, so the returned value is with respect to the inner \ref rect.
  27576. */
  27577. /*! \fn int QCPPolarAxisAngular::bottom() const
  27578. Returns the pixel position of the bottom border of this axis rect. Margins are not taken into
  27579. account here, so the returned value is with respect to the inner \ref rect.
  27580. */
  27581. /*! \fn int QCPPolarAxisAngular::width() const
  27582. Returns the pixel width of this axis rect. Margins are not taken into account here, so the
  27583. returned value is with respect to the inner \ref rect.
  27584. */
  27585. /*! \fn int QCPPolarAxisAngular::height() const
  27586. Returns the pixel height of this axis rect. Margins are not taken into account here, so the
  27587. returned value is with respect to the inner \ref rect.
  27588. */
  27589. /*! \fn QSize QCPPolarAxisAngular::size() const
  27590. Returns the pixel size of this axis rect. Margins are not taken into account here, so the
  27591. returned value is with respect to the inner \ref rect.
  27592. */
  27593. /*! \fn QPoint QCPPolarAxisAngular::topLeft() const
  27594. Returns the top left corner of this axis rect in pixels. Margins are not taken into account here,
  27595. so the returned value is with respect to the inner \ref rect.
  27596. */
  27597. /*! \fn QPoint QCPPolarAxisAngular::topRight() const
  27598. Returns the top right corner of this axis rect in pixels. Margins are not taken into account
  27599. here, so the returned value is with respect to the inner \ref rect.
  27600. */
  27601. /*! \fn QPoint QCPPolarAxisAngular::bottomLeft() const
  27602. Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account
  27603. here, so the returned value is with respect to the inner \ref rect.
  27604. */
  27605. /*! \fn QPoint QCPPolarAxisAngular::bottomRight() const
  27606. Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account
  27607. here, so the returned value is with respect to the inner \ref rect.
  27608. */
  27609. /*! \fn QPoint QCPPolarAxisAngular::center() const
  27610. Returns the center of this axis rect in pixels. Margins are not taken into account here, so the
  27611. returned value is with respect to the inner \ref rect.
  27612. */
  27613. /* end documentation of inline functions */
  27614. /*!
  27615. Creates a QCPPolarAxis instance and sets default values. An axis is added for each of the four
  27616. sides, the top and right axes are set invisible initially.
  27617. */
  27618. QCPPolarAxisAngular::QCPPolarAxisAngular(QCustomPlot *parentPlot) :
  27619. QCPLayoutElement(parentPlot),
  27620. mBackgroundBrush(Qt::NoBrush),
  27621. mBackgroundScaled(true),
  27622. mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding),
  27623. mInsetLayout(new QCPLayoutInset),
  27624. mRangeDrag(false),
  27625. mRangeZoom(false),
  27626. mRangeZoomFactor(0.85),
  27627. // axis base:
  27628. mAngle(-90),
  27629. mAngleRad(mAngle/180.0*M_PI),
  27630. mSelectableParts(spAxis | spTickLabels | spAxisLabel),
  27631. mSelectedParts(spNone),
  27632. mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  27633. mSelectedBasePen(QPen(Qt::blue, 2)),
  27634. // axis label:
  27635. mLabelPadding(0),
  27636. mLabel(),
  27637. mLabelFont(mParentPlot->font()),
  27638. mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)),
  27639. mLabelColor(Qt::black),
  27640. mSelectedLabelColor(Qt::blue),
  27641. // tick labels:
  27642. //mTickLabelPadding(0), in label painter
  27643. mTickLabels(true),
  27644. //mTickLabelRotation(0), in label painter
  27645. mTickLabelFont(mParentPlot->font()),
  27646. mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)),
  27647. mTickLabelColor(Qt::black),
  27648. mSelectedTickLabelColor(Qt::blue),
  27649. mNumberPrecision(6),
  27650. mNumberFormatChar('g'),
  27651. mNumberBeautifulPowers(true),
  27652. mNumberMultiplyCross(false),
  27653. // ticks and subticks:
  27654. mTicks(true),
  27655. mSubTicks(true),
  27656. mTickLengthIn(5),
  27657. mTickLengthOut(0),
  27658. mSubTickLengthIn(2),
  27659. mSubTickLengthOut(0),
  27660. mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  27661. mSelectedTickPen(QPen(Qt::blue, 2)),
  27662. mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)),
  27663. mSelectedSubTickPen(QPen(Qt::blue, 2)),
  27664. // scale and range:
  27665. mRange(0, 360),
  27666. mRangeReversed(false),
  27667. // internal members:
  27668. mRadius(1), // non-zero initial value, will be overwritten in ::update() according to inner rect
  27669. mGrid(new QCPPolarGrid(this)),
  27670. mTicker(new QCPAxisTickerFixed),
  27671. mDragging(false),
  27672. mLabelPainter(parentPlot)
  27673. {
  27674. // TODO:
  27675. //mInsetLayout->initializeParentPlot(mParentPlot);
  27676. //mInsetLayout->setParentLayerable(this);
  27677. //mInsetLayout->setParent(this);
  27678. if (QCPAxisTickerFixed *fixedTicker = mTicker.dynamicCast<QCPAxisTickerFixed>().data())
  27679. {
  27680. fixedTicker->setTickStep(30);
  27681. }
  27682. setAntialiased(true);
  27683. 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
  27684. setTickLabelPadding(5);
  27685. setTickLabelRotation(0);
  27686. setTickLabelMode(lmUpright);
  27687. mLabelPainter.setAnchorReferenceType(QCPLabelPainterPrivate::AnchorReferenceType::artNormal);
  27688. mLabelPainter.setAbbreviateDecimalPowers(false);
  27689. mLabelPainter.setCacheSize(24); // so we can cache up to 15-degree intervals, polar angular axis uses a bit larger cache than normal axes
  27690. setMinimumSize(50, 50);
  27691. setMinimumMargins(QMargins(30, 30, 30, 30));
  27692. addRadialAxis();
  27693. mGrid->setRadialAxis(radialAxis());
  27694. }
  27695. QCPPolarAxisAngular::~QCPPolarAxisAngular()
  27696. {
  27697. delete mGrid; // delete grid here instead of via parent ~QObject for better defined deletion order
  27698. mGrid = 0;
  27699. delete mInsetLayout;
  27700. mInsetLayout = 0;
  27701. QList<QCPPolarAxisRadial*> radialAxesList = radialAxes();
  27702. for (int i=0; i<radialAxesList.size(); ++i)
  27703. removeRadialAxis(radialAxesList.at(i));
  27704. }
  27705. QCPPolarAxisAngular::LabelMode QCPPolarAxisAngular::tickLabelMode() const
  27706. {
  27707. switch (mLabelPainter.anchorMode())
  27708. {
  27709. case QCPLabelPainterPrivate::amSkewedUpright: return lmUpright;
  27710. case QCPLabelPainterPrivate::amSkewedRotated: return lmRotated;
  27711. default: qDebug() << Q_FUNC_INFO << "invalid mode for polar axis"; break;
  27712. }
  27713. return lmUpright;
  27714. }
  27715. /* No documentation as it is a property getter */
  27716. QString QCPPolarAxisAngular::numberFormat() const
  27717. {
  27718. QString result;
  27719. result.append(mNumberFormatChar);
  27720. if (mNumberBeautifulPowers)
  27721. {
  27722. result.append(QLatin1Char('b'));
  27723. if (mLabelPainter.multiplicationSymbol() == QCPLabelPainterPrivate::SymbolCross)
  27724. result.append(QLatin1Char('c'));
  27725. }
  27726. return result;
  27727. }
  27728. /*!
  27729. Returns the number of axes on the axis rect side specified with \a type.
  27730. \see axis
  27731. */
  27732. int QCPPolarAxisAngular::radialAxisCount() const
  27733. {
  27734. return mRadialAxes.size();
  27735. }
  27736. /*!
  27737. Returns the axis with the given \a index on the axis rect side specified with \a type.
  27738. \see axisCount, axes
  27739. */
  27740. QCPPolarAxisRadial *QCPPolarAxisAngular::radialAxis(int index) const
  27741. {
  27742. if (index >= 0 && index < mRadialAxes.size())
  27743. {
  27744. return mRadialAxes.at(index);
  27745. } else
  27746. {
  27747. qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index;
  27748. return 0;
  27749. }
  27750. }
  27751. /*!
  27752. Returns all axes on the axis rect sides specified with \a types.
  27753. \a types may be a single \ref QCPAxis::AxisType or an <tt>or</tt>-combination, to get the axes of
  27754. multiple sides.
  27755. \see axis
  27756. */
  27757. QList<QCPPolarAxisRadial*> QCPPolarAxisAngular::radialAxes() const
  27758. {
  27759. return mRadialAxes;
  27760. }
  27761. /*!
  27762. Adds a new axis to the axis rect side specified with \a type, and returns it. If \a axis is 0, a
  27763. new QCPAxis instance is created internally. QCustomPlot owns the returned axis, so if you want to
  27764. remove an axis, use \ref removeAxis instead of deleting it manually.
  27765. You may inject QCPAxis instances (or subclasses of QCPAxis) by setting \a axis to an axis that was
  27766. previously created outside QCustomPlot. It is important to note that QCustomPlot takes ownership
  27767. of the axis, so you may not delete it afterwards. Further, the \a axis must have been created
  27768. with this axis rect as parent and with the same axis type as specified in \a type. If this is not
  27769. the case, a debug output is generated, the axis is not added, and the method returns 0.
  27770. This method can not be used to move \a axis between axis rects. The same \a axis instance must
  27771. not be added multiple times to the same or different axis rects.
  27772. If an axis rect side already contains one or more axes, the lower and upper endings of the new
  27773. axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are set to \ref
  27774. QCPLineEnding::esHalfBar.
  27775. \see addAxes, setupFullAxesBox
  27776. */
  27777. QCPPolarAxisRadial *QCPPolarAxisAngular::addRadialAxis(QCPPolarAxisRadial *axis)
  27778. {
  27779. QCPPolarAxisRadial *newAxis = axis;
  27780. if (!newAxis)
  27781. {
  27782. newAxis = new QCPPolarAxisRadial(this);
  27783. } else // user provided existing axis instance, do some sanity checks
  27784. {
  27785. if (newAxis->angularAxis() != this)
  27786. {
  27787. qDebug() << Q_FUNC_INFO << "passed radial axis doesn't have this angular axis as parent angular axis";
  27788. return 0;
  27789. }
  27790. if (radialAxes().contains(newAxis))
  27791. {
  27792. qDebug() << Q_FUNC_INFO << "passed axis is already owned by this angular axis";
  27793. return 0;
  27794. }
  27795. }
  27796. mRadialAxes.append(newAxis);
  27797. return newAxis;
  27798. }
  27799. /*!
  27800. Removes the specified \a axis from the axis rect and deletes it.
  27801. Returns true on success, i.e. if \a axis was a valid axis in this axis rect.
  27802. \see addAxis
  27803. */
  27804. bool QCPPolarAxisAngular::removeRadialAxis(QCPPolarAxisRadial *radialAxis)
  27805. {
  27806. if (mRadialAxes.contains(radialAxis))
  27807. {
  27808. mRadialAxes.removeOne(radialAxis);
  27809. delete radialAxis;
  27810. return true;
  27811. } else
  27812. {
  27813. qDebug() << Q_FUNC_INFO << "Radial axis isn't associated with this angular axis:" << reinterpret_cast<quintptr>(radialAxis);
  27814. return false;
  27815. }
  27816. }
  27817. QRegion QCPPolarAxisAngular::exactClipRegion() const
  27818. {
  27819. return QRegion(mCenter.x()-mRadius, mCenter.y()-mRadius, qRound(2*mRadius), qRound(2*mRadius), QRegion::Ellipse);
  27820. }
  27821. /*!
  27822. If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper
  27823. bounds of the range. The range is simply moved by \a diff.
  27824. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This
  27825. corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff).
  27826. */
  27827. void QCPPolarAxisAngular::moveRange(double diff)
  27828. {
  27829. QCPRange oldRange = mRange;
  27830. mRange.lower += diff;
  27831. mRange.upper += diff;
  27832. emit rangeChanged(mRange);
  27833. emit rangeChanged(mRange, oldRange);
  27834. }
  27835. /*!
  27836. Scales the range of this axis by \a factor around the center of the current axis range. For
  27837. example, if \a factor is 2.0, then the axis range will double its size, and the point at the axis
  27838. range center won't have changed its position in the QCustomPlot widget (i.e. coordinates around
  27839. the center will have moved symmetrically closer).
  27840. If you wish to scale around a different coordinate than the current axis range center, use the
  27841. overload \ref scaleRange(double factor, double center).
  27842. */
  27843. void QCPPolarAxisAngular::scaleRange(double factor)
  27844. {
  27845. scaleRange(factor, range().center());
  27846. }
  27847. /*! \overload
  27848. Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a
  27849. factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at
  27850. coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates
  27851. around 1.0 will have moved symmetrically closer to 1.0).
  27852. \see scaleRange(double factor)
  27853. */
  27854. void QCPPolarAxisAngular::scaleRange(double factor, double center)
  27855. {
  27856. QCPRange oldRange = mRange;
  27857. QCPRange newRange;
  27858. newRange.lower = (mRange.lower-center)*factor + center;
  27859. newRange.upper = (mRange.upper-center)*factor + center;
  27860. if (QCPRange::validRange(newRange))
  27861. mRange = newRange.sanitizedForLinScale();
  27862. emit rangeChanged(mRange);
  27863. emit rangeChanged(mRange, oldRange);
  27864. }
  27865. /*!
  27866. Changes the axis range such that all plottables associated with this axis are fully visible in
  27867. that dimension.
  27868. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes
  27869. */
  27870. void QCPPolarAxisAngular::rescale(bool onlyVisiblePlottables)
  27871. {
  27872. QCPRange newRange;
  27873. bool haveRange = false;
  27874. for (int i=0; i<mGraphs.size(); ++i)
  27875. {
  27876. if (!mGraphs.at(i)->realVisibility() && onlyVisiblePlottables)
  27877. continue;
  27878. QCPRange range;
  27879. bool currentFoundRange;
  27880. if (mGraphs.at(i)->keyAxis() == this)
  27881. range = mGraphs.at(i)->getKeyRange(currentFoundRange, QCP::SignDomain::sdBoth);
  27882. else
  27883. range = mGraphs.at(i)->getValueRange(currentFoundRange, QCP::SignDomain::sdBoth);
  27884. if (currentFoundRange)
  27885. {
  27886. if (!haveRange)
  27887. newRange = range;
  27888. else
  27889. newRange.expand(range);
  27890. haveRange = true;
  27891. }
  27892. }
  27893. if (haveRange)
  27894. {
  27895. 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
  27896. {
  27897. 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
  27898. newRange.lower = center-mRange.size()/2.0;
  27899. newRange.upper = center+mRange.size()/2.0;
  27900. }
  27901. setRange(newRange);
  27902. }
  27903. }
  27904. /*!
  27905. Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates.
  27906. */
  27907. void QCPPolarAxisAngular::pixelToCoord(QPointF pixelPos, double &angleCoord, double &radiusCoord) const
  27908. {
  27909. if (!mRadialAxes.isEmpty())
  27910. mRadialAxes.first()->pixelToCoord(pixelPos, angleCoord, radiusCoord);
  27911. else
  27912. qDebug() << Q_FUNC_INFO << "no radial axis configured";
  27913. }
  27914. /*!
  27915. Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget.
  27916. */
  27917. QPointF QCPPolarAxisAngular::coordToPixel(double angleCoord, double radiusCoord) const
  27918. {
  27919. if (!mRadialAxes.isEmpty())
  27920. {
  27921. return mRadialAxes.first()->coordToPixel(angleCoord, radiusCoord);
  27922. } else
  27923. {
  27924. qDebug() << Q_FUNC_INFO << "no radial axis configured";
  27925. return QPointF();
  27926. }
  27927. }
  27928. /*!
  27929. Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function
  27930. is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this
  27931. function does not change the current selection state of the axis.
  27932. If the axis is not visible (\ref setVisible), this function always returns \ref spNone.
  27933. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions
  27934. */
  27935. QCPPolarAxisAngular::SelectablePart QCPPolarAxisAngular::getPartAt(const QPointF &pos) const
  27936. {
  27937. Q_UNUSED(pos) // TODO remove later
  27938. if (!mVisible)
  27939. return spNone;
  27940. /*
  27941. TODO:
  27942. if (mAxisPainter->axisSelectionBox().contains(pos.toPoint()))
  27943. return spAxis;
  27944. else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint()))
  27945. return spTickLabels;
  27946. else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint()))
  27947. return spAxisLabel;
  27948. else */
  27949. return spNone;
  27950. }
  27951. /* inherits documentation from base class */
  27952. double QCPPolarAxisAngular::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  27953. {
  27954. /*
  27955. if (!mParentPlot) return -1;
  27956. SelectablePart part = getPartAt(pos);
  27957. if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone)
  27958. return -1;
  27959. if (details)
  27960. details->setValue(part);
  27961. return mParentPlot->selectionTolerance()*0.99;
  27962. */
  27963. Q_UNUSED(details)
  27964. if (onlySelectable)
  27965. return -1;
  27966. if (QRectF(mOuterRect).contains(pos))
  27967. {
  27968. if (mParentPlot)
  27969. return mParentPlot->selectionTolerance()*0.99;
  27970. else
  27971. {
  27972. qDebug() << Q_FUNC_INFO << "parent plot not defined";
  27973. return -1;
  27974. }
  27975. } else
  27976. return -1;
  27977. }
  27978. /*!
  27979. This method is called automatically upon replot and doesn't need to be called by users of
  27980. QCPPolarAxisAngular.
  27981. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update),
  27982. and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its
  27983. QCPInsetLayout::update function.
  27984. \seebaseclassmethod
  27985. */
  27986. void QCPPolarAxisAngular::update(UpdatePhase phase)
  27987. {
  27988. QCPLayoutElement::update(phase);
  27989. switch (phase)
  27990. {
  27991. case upPreparation:
  27992. {
  27993. setupTickVectors();
  27994. for (int i=0; i<mRadialAxes.size(); ++i)
  27995. mRadialAxes.at(i)->setupTickVectors();
  27996. break;
  27997. }
  27998. case upLayout:
  27999. {
  28000. mCenter = mRect.center();
  28001. mRadius = 0.5*qMin(qAbs(mRect.width()), qAbs(mRect.height()));
  28002. if (mRadius < 1) mRadius = 1; // prevent cases where radius might become 0 which causes trouble
  28003. for (int i=0; i<mRadialAxes.size(); ++i)
  28004. mRadialAxes.at(i)->updateGeometry(mCenter, mRadius);
  28005. mInsetLayout->setOuterRect(rect());
  28006. break;
  28007. }
  28008. default: break;
  28009. }
  28010. // pass update call on to inset layout (doesn't happen automatically, because QCPPolarAxis doesn't derive from QCPLayout):
  28011. mInsetLayout->update(phase);
  28012. }
  28013. /* inherits documentation from base class */
  28014. QList<QCPLayoutElement*> QCPPolarAxisAngular::elements(bool recursive) const
  28015. {
  28016. QList<QCPLayoutElement*> result;
  28017. if (mInsetLayout)
  28018. {
  28019. result << mInsetLayout;
  28020. if (recursive)
  28021. result << mInsetLayout->elements(recursive);
  28022. }
  28023. return result;
  28024. }
  28025. bool QCPPolarAxisAngular::removeGraph(QCPPolarGraph *graph)
  28026. {
  28027. if (!mGraphs.contains(graph))
  28028. {
  28029. qDebug() << Q_FUNC_INFO << "graph not in list:" << reinterpret_cast<quintptr>(graph);
  28030. return false;
  28031. }
  28032. // remove plottable from legend:
  28033. graph->removeFromLegend();
  28034. // remove plottable:
  28035. delete graph;
  28036. mGraphs.removeOne(graph);
  28037. return true;
  28038. }
  28039. /* inherits documentation from base class */
  28040. void QCPPolarAxisAngular::applyDefaultAntialiasingHint(QCPPainter *painter) const
  28041. {
  28042. applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes);
  28043. }
  28044. /* inherits documentation from base class */
  28045. void QCPPolarAxisAngular::draw(QCPPainter *painter)
  28046. {
  28047. drawBackground(painter, mCenter, mRadius);
  28048. // draw baseline circle:
  28049. painter->setPen(getBasePen());
  28050. painter->drawEllipse(mCenter, mRadius, mRadius);
  28051. // draw subticks:
  28052. if (!mSubTickVector.isEmpty())
  28053. {
  28054. painter->setPen(getSubTickPen());
  28055. for (int i=0; i<mSubTickVector.size(); ++i)
  28056. {
  28057. painter->drawLine(mCenter+mSubTickVectorCosSin.at(i)*(mRadius-mSubTickLengthIn),
  28058. mCenter+mSubTickVectorCosSin.at(i)*(mRadius+mSubTickLengthOut));
  28059. }
  28060. }
  28061. // draw ticks and labels:
  28062. if (!mTickVector.isEmpty())
  28063. {
  28064. mLabelPainter.setAnchorReference(mCenter);
  28065. mLabelPainter.setFont(getTickLabelFont());
  28066. mLabelPainter.setColor(getTickLabelColor());
  28067. const QPen ticksPen = getTickPen();
  28068. painter->setPen(ticksPen);
  28069. for (int i=0; i<mTickVector.size(); ++i)
  28070. {
  28071. const QPointF outerTick = mCenter+mTickVectorCosSin.at(i)*(mRadius+mTickLengthOut);
  28072. painter->drawLine(mCenter+mTickVectorCosSin.at(i)*(mRadius-mTickLengthIn), outerTick);
  28073. // draw tick labels:
  28074. if (!mTickVectorLabels.isEmpty())
  28075. {
  28076. 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
  28077. mLabelPainter.drawTickLabel(painter, outerTick, mTickVectorLabels.at(i));
  28078. }
  28079. }
  28080. }
  28081. }
  28082. /* inherits documentation from base class */
  28083. QCP::Interaction QCPPolarAxisAngular::selectionCategory() const
  28084. {
  28085. return QCP::iSelectAxes;
  28086. }
  28087. /*!
  28088. Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the
  28089. axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect
  28090. backgrounds are usually drawn below everything else.
  28091. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be
  28092. enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio
  28093. is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call,
  28094. consider using the overloaded version of this function.
  28095. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref
  28096. setBackground(const QBrush &brush).
  28097. \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush)
  28098. */
  28099. void QCPPolarAxisAngular::setBackground(const QPixmap &pm)
  28100. {
  28101. mBackgroundPixmap = pm;
  28102. mScaledBackgroundPixmap = QPixmap();
  28103. }
  28104. /*! \overload
  28105. Sets \a brush as the background brush. The axis rect background will be filled with this brush.
  28106. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds
  28107. are usually drawn below everything else.
  28108. The brush will be drawn before (under) any background pixmap, which may be specified with \ref
  28109. setBackground(const QPixmap &pm).
  28110. To disable drawing of a background brush, set \a brush to Qt::NoBrush.
  28111. \see setBackground(const QPixmap &pm)
  28112. */
  28113. void QCPPolarAxisAngular::setBackground(const QBrush &brush)
  28114. {
  28115. mBackgroundBrush = brush;
  28116. }
  28117. /*! \overload
  28118. Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it
  28119. shall be scaled in one call.
  28120. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode
  28121. */
  28122. void QCPPolarAxisAngular::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode)
  28123. {
  28124. mBackgroundPixmap = pm;
  28125. mScaledBackgroundPixmap = QPixmap();
  28126. mBackgroundScaled = scaled;
  28127. mBackgroundScaledMode = mode;
  28128. }
  28129. /*!
  28130. Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled
  28131. is set to true, you may control whether and how the aspect ratio of the original pixmap is
  28132. preserved with \ref setBackgroundScaledMode.
  28133. Note that the scaled version of the original pixmap is buffered, so there is no performance
  28134. penalty on replots. (Except when the axis rect dimensions are changed continuously.)
  28135. \see setBackground, setBackgroundScaledMode
  28136. */
  28137. void QCPPolarAxisAngular::setBackgroundScaled(bool scaled)
  28138. {
  28139. mBackgroundScaled = scaled;
  28140. }
  28141. /*!
  28142. If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to
  28143. define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved.
  28144. \see setBackground, setBackgroundScaled
  28145. */
  28146. void QCPPolarAxisAngular::setBackgroundScaledMode(Qt::AspectRatioMode mode)
  28147. {
  28148. mBackgroundScaledMode = mode;
  28149. }
  28150. void QCPPolarAxisAngular::setRangeDrag(bool enabled)
  28151. {
  28152. mRangeDrag = enabled;
  28153. }
  28154. void QCPPolarAxisAngular::setRangeZoom(bool enabled)
  28155. {
  28156. mRangeZoom = enabled;
  28157. }
  28158. void QCPPolarAxisAngular::setRangeZoomFactor(double factor)
  28159. {
  28160. mRangeZoomFactor = factor;
  28161. }
  28162. /*!
  28163. Sets the range of the axis.
  28164. This slot may be connected with the \ref rangeChanged signal of another axis so this axis
  28165. is always synchronized with the other axis range, when it changes.
  28166. To invert the direction of an axis, use \ref setRangeReversed.
  28167. */
  28168. void QCPPolarAxisAngular::setRange(const QCPRange &range)
  28169. {
  28170. if (range.lower == mRange.lower && range.upper == mRange.upper)
  28171. return;
  28172. if (!QCPRange::validRange(range)) return;
  28173. QCPRange oldRange = mRange;
  28174. mRange = range.sanitizedForLinScale();
  28175. emit rangeChanged(mRange);
  28176. emit rangeChanged(mRange, oldRange);
  28177. }
  28178. /*!
  28179. Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface.
  28180. (When \ref QCustomPlot::setInteractions contains iSelectAxes.)
  28181. However, even when \a selectable is set to a value not allowing the selection of a specific part,
  28182. it is still possible to set the selection of this part manually, by calling \ref setSelectedParts
  28183. directly.
  28184. \see SelectablePart, setSelectedParts
  28185. */
  28186. void QCPPolarAxisAngular::setSelectableParts(const SelectableParts &selectable)
  28187. {
  28188. if (mSelectableParts != selectable)
  28189. {
  28190. mSelectableParts = selectable;
  28191. emit selectableChanged(mSelectableParts);
  28192. }
  28193. }
  28194. /*!
  28195. Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part
  28196. is selected, it uses a different pen/font.
  28197. The entire selection mechanism for axes is handled automatically when \ref
  28198. QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you
  28199. wish to change the selection state manually.
  28200. This function can change the selection state of a part, independent of the \ref setSelectableParts setting.
  28201. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  28202. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen,
  28203. setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor
  28204. */
  28205. void QCPPolarAxisAngular::setSelectedParts(const SelectableParts &selected)
  28206. {
  28207. if (mSelectedParts != selected)
  28208. {
  28209. mSelectedParts = selected;
  28210. emit selectionChanged(mSelectedParts);
  28211. }
  28212. }
  28213. /*!
  28214. \overload
  28215. Sets the lower and upper bound of the axis range.
  28216. To invert the direction of an axis, use \ref setRangeReversed.
  28217. There is also a slot to set a range, see \ref setRange(const QCPRange &range).
  28218. */
  28219. void QCPPolarAxisAngular::setRange(double lower, double upper)
  28220. {
  28221. if (lower == mRange.lower && upper == mRange.upper)
  28222. return;
  28223. if (!QCPRange::validRange(lower, upper)) return;
  28224. QCPRange oldRange = mRange;
  28225. mRange.lower = lower;
  28226. mRange.upper = upper;
  28227. mRange = mRange.sanitizedForLinScale();
  28228. emit rangeChanged(mRange);
  28229. emit rangeChanged(mRange, oldRange);
  28230. }
  28231. /*!
  28232. \overload
  28233. Sets the range of the axis.
  28234. The \a position coordinate indicates together with the \a alignment parameter, where the new
  28235. range will be positioned. \a size defines the size of the new axis range. \a alignment may be
  28236. Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border,
  28237. or center of the range to be aligned with \a position. Any other values of \a alignment will
  28238. default to Qt::AlignCenter.
  28239. */
  28240. void QCPPolarAxisAngular::setRange(double position, double size, Qt::AlignmentFlag alignment)
  28241. {
  28242. if (alignment == Qt::AlignLeft)
  28243. setRange(position, position+size);
  28244. else if (alignment == Qt::AlignRight)
  28245. setRange(position-size, position);
  28246. else // alignment == Qt::AlignCenter
  28247. setRange(position-size/2.0, position+size/2.0);
  28248. }
  28249. /*!
  28250. Sets the lower bound of the axis range. The upper bound is not changed.
  28251. \see setRange
  28252. */
  28253. void QCPPolarAxisAngular::setRangeLower(double lower)
  28254. {
  28255. if (mRange.lower == lower)
  28256. return;
  28257. QCPRange oldRange = mRange;
  28258. mRange.lower = lower;
  28259. mRange = mRange.sanitizedForLinScale();
  28260. emit rangeChanged(mRange);
  28261. emit rangeChanged(mRange, oldRange);
  28262. }
  28263. /*!
  28264. Sets the upper bound of the axis range. The lower bound is not changed.
  28265. \see setRange
  28266. */
  28267. void QCPPolarAxisAngular::setRangeUpper(double upper)
  28268. {
  28269. if (mRange.upper == upper)
  28270. return;
  28271. QCPRange oldRange = mRange;
  28272. mRange.upper = upper;
  28273. mRange = mRange.sanitizedForLinScale();
  28274. emit rangeChanged(mRange);
  28275. emit rangeChanged(mRange, oldRange);
  28276. }
  28277. /*!
  28278. Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal
  28279. axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the
  28280. direction of increasing values is inverted.
  28281. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part
  28282. of the \ref setRange interface will still reference the mathematically smaller number than the \a
  28283. upper part.
  28284. */
  28285. void QCPPolarAxisAngular::setRangeReversed(bool reversed)
  28286. {
  28287. mRangeReversed = reversed;
  28288. }
  28289. void QCPPolarAxisAngular::setAngle(double degrees)
  28290. {
  28291. mAngle = degrees;
  28292. mAngleRad = mAngle/180.0*M_PI;
  28293. }
  28294. /*!
  28295. The axis ticker is responsible for generating the tick positions and tick labels. See the
  28296. documentation of QCPAxisTicker for details on how to work with axis tickers.
  28297. You can change the tick positioning/labeling behaviour of this axis by setting a different
  28298. QCPAxisTicker subclass using this method. If you only wish to modify the currently installed axis
  28299. ticker, access it via \ref ticker.
  28300. Since the ticker is stored in the axis as a shared pointer, multiple axes may share the same axis
  28301. ticker simply by passing the same shared pointer to multiple axes.
  28302. \see ticker
  28303. */
  28304. void QCPPolarAxisAngular::setTicker(QSharedPointer<QCPAxisTicker> ticker)
  28305. {
  28306. if (ticker)
  28307. mTicker = ticker;
  28308. else
  28309. qDebug() << Q_FUNC_INFO << "can not set 0 as axis ticker";
  28310. // no need to invalidate margin cache here because produced tick labels are checked for changes in setupTickVector
  28311. }
  28312. /*!
  28313. Sets whether tick marks are displayed.
  28314. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve
  28315. that, see \ref setTickLabels.
  28316. \see setSubTicks
  28317. */
  28318. void QCPPolarAxisAngular::setTicks(bool show)
  28319. {
  28320. if (mTicks != show)
  28321. {
  28322. mTicks = show;
  28323. //mCachedMarginValid = false;
  28324. }
  28325. }
  28326. /*!
  28327. Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks.
  28328. */
  28329. void QCPPolarAxisAngular::setTickLabels(bool show)
  28330. {
  28331. if (mTickLabels != show)
  28332. {
  28333. mTickLabels = show;
  28334. //mCachedMarginValid = false;
  28335. if (!mTickLabels)
  28336. mTickVectorLabels.clear();
  28337. }
  28338. }
  28339. /*!
  28340. Sets the distance between the axis base line (including any outward ticks) and the tick labels.
  28341. \see setLabelPadding, setPadding
  28342. */
  28343. void QCPPolarAxisAngular::setTickLabelPadding(int padding)
  28344. {
  28345. mLabelPainter.setPadding(padding);
  28346. }
  28347. /*!
  28348. Sets the font of the tick labels.
  28349. \see setTickLabels, setTickLabelColor
  28350. */
  28351. void QCPPolarAxisAngular::setTickLabelFont(const QFont &font)
  28352. {
  28353. mTickLabelFont = font;
  28354. }
  28355. /*!
  28356. Sets the color of the tick labels.
  28357. \see setTickLabels, setTickLabelFont
  28358. */
  28359. void QCPPolarAxisAngular::setTickLabelColor(const QColor &color)
  28360. {
  28361. mTickLabelColor = color;
  28362. }
  28363. /*!
  28364. Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else,
  28365. the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values
  28366. from -90 to 90 degrees.
  28367. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For
  28368. other angles, the label is drawn with an offset such that it seems to point toward or away from
  28369. the tick mark.
  28370. */
  28371. void QCPPolarAxisAngular::setTickLabelRotation(double degrees)
  28372. {
  28373. mLabelPainter.setRotation(degrees);
  28374. }
  28375. void QCPPolarAxisAngular::setTickLabelMode(LabelMode mode)
  28376. {
  28377. switch (mode)
  28378. {
  28379. case lmUpright: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedUpright); break;
  28380. case lmRotated: mLabelPainter.setAnchorMode(QCPLabelPainterPrivate::amSkewedRotated); break;
  28381. }
  28382. }
  28383. /*!
  28384. Sets the number format for the numbers in tick labels. This \a formatCode is an extended version
  28385. of the format code used e.g. by QString::number() and QLocale::toString(). For reference about
  28386. that, see the "Argument Formats" section in the detailed description of the QString class.
  28387. \a formatCode is a string of one, two or three characters. The first character is identical to
  28388. the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed
  28389. format, 'g'/'G' scientific or fixed, whichever is shorter.
  28390. The second and third characters are optional and specific to QCustomPlot:\n If the first char was
  28391. 'e' or 'g', numbers are/might be displayed in the scientific format, e.g. "5.5e9", which might be
  28392. visually unappealing in a plot. So when the second char of \a formatCode is set to 'b' (for
  28393. "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5
  28394. [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot.
  28395. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can
  28396. be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the
  28397. cross and 183 (0xB7) for the dot.
  28398. Examples for \a formatCode:
  28399. \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large,
  28400. normal scientific format is used
  28401. \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with
  28402. beautifully typeset decimal powers and a dot as multiplication sign
  28403. \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as
  28404. multiplication sign
  28405. \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal
  28406. powers. Format code will be reduced to 'f'.
  28407. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format
  28408. code will not be changed.
  28409. */
  28410. void QCPPolarAxisAngular::setNumberFormat(const QString &formatCode)
  28411. {
  28412. if (formatCode.isEmpty())
  28413. {
  28414. qDebug() << Q_FUNC_INFO << "Passed formatCode is empty";
  28415. return;
  28416. }
  28417. //mCachedMarginValid = false;
  28418. // interpret first char as number format char:
  28419. QString allowedFormatChars(QLatin1String("eEfgG"));
  28420. if (allowedFormatChars.contains(formatCode.at(0)))
  28421. {
  28422. mNumberFormatChar = QLatin1Char(formatCode.at(0).toLatin1());
  28423. } else
  28424. {
  28425. qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode;
  28426. return;
  28427. }
  28428. if (formatCode.length() < 2)
  28429. {
  28430. mNumberBeautifulPowers = false;
  28431. mNumberMultiplyCross = false;
  28432. } else
  28433. {
  28434. // interpret second char as indicator for beautiful decimal powers:
  28435. if (formatCode.at(1) == QLatin1Char('b') && (mNumberFormatChar == QLatin1Char('e') || mNumberFormatChar == QLatin1Char('g')))
  28436. mNumberBeautifulPowers = true;
  28437. else
  28438. qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode;
  28439. if (formatCode.length() < 3)
  28440. {
  28441. mNumberMultiplyCross = false;
  28442. } else
  28443. {
  28444. // interpret third char as indicator for dot or cross multiplication symbol:
  28445. if (formatCode.at(2) == QLatin1Char('c'))
  28446. mNumberMultiplyCross = true;
  28447. else if (formatCode.at(2) == QLatin1Char('d'))
  28448. mNumberMultiplyCross = false;
  28449. else
  28450. qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode;
  28451. }
  28452. }
  28453. mLabelPainter.setSubstituteExponent(mNumberBeautifulPowers);
  28454. mLabelPainter.setMultiplicationSymbol(mNumberMultiplyCross ? QCPLabelPainterPrivate::SymbolCross : QCPLabelPainterPrivate::SymbolDot);
  28455. }
  28456. /*!
  28457. Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec)
  28458. for details. The effect of precisions are most notably for number Formats starting with 'e', see
  28459. \ref setNumberFormat
  28460. */
  28461. void QCPPolarAxisAngular::setNumberPrecision(int precision)
  28462. {
  28463. if (mNumberPrecision != precision)
  28464. {
  28465. mNumberPrecision = precision;
  28466. //mCachedMarginValid = false;
  28467. }
  28468. }
  28469. /*!
  28470. Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the
  28471. plot and \a outside is the length they will reach outside the plot. If \a outside is greater than
  28472. zero, the tick labels and axis label will increase their distance to the axis accordingly, so
  28473. they won't collide with the ticks.
  28474. \see setSubTickLength, setTickLengthIn, setTickLengthOut
  28475. */
  28476. void QCPPolarAxisAngular::setTickLength(int inside, int outside)
  28477. {
  28478. setTickLengthIn(inside);
  28479. setTickLengthOut(outside);
  28480. }
  28481. /*!
  28482. Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach
  28483. inside the plot.
  28484. \see setTickLengthOut, setTickLength, setSubTickLength
  28485. */
  28486. void QCPPolarAxisAngular::setTickLengthIn(int inside)
  28487. {
  28488. if (mTickLengthIn != inside)
  28489. {
  28490. mTickLengthIn = inside;
  28491. }
  28492. }
  28493. /*!
  28494. Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach
  28495. outside the plot. If \a outside is greater than zero, the tick labels and axis label will
  28496. increase their distance to the axis accordingly, so they won't collide with the ticks.
  28497. \see setTickLengthIn, setTickLength, setSubTickLength
  28498. */
  28499. void QCPPolarAxisAngular::setTickLengthOut(int outside)
  28500. {
  28501. if (mTickLengthOut != outside)
  28502. {
  28503. mTickLengthOut = outside;
  28504. //mCachedMarginValid = false; // only outside tick length can change margin
  28505. }
  28506. }
  28507. /*!
  28508. Sets whether sub tick marks are displayed.
  28509. Sub ticks are only potentially visible if (major) ticks are also visible (see \ref setTicks)
  28510. \see setTicks
  28511. */
  28512. void QCPPolarAxisAngular::setSubTicks(bool show)
  28513. {
  28514. if (mSubTicks != show)
  28515. {
  28516. mSubTicks = show;
  28517. //mCachedMarginValid = false;
  28518. }
  28519. }
  28520. /*!
  28521. Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside
  28522. the plot and \a outside is the length they will reach outside the plot. If \a outside is greater
  28523. than zero, the tick labels and axis label will increase their distance to the axis accordingly,
  28524. so they won't collide with the ticks.
  28525. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut
  28526. */
  28527. void QCPPolarAxisAngular::setSubTickLength(int inside, int outside)
  28528. {
  28529. setSubTickLengthIn(inside);
  28530. setSubTickLengthOut(outside);
  28531. }
  28532. /*!
  28533. Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside
  28534. the plot.
  28535. \see setSubTickLengthOut, setSubTickLength, setTickLength
  28536. */
  28537. void QCPPolarAxisAngular::setSubTickLengthIn(int inside)
  28538. {
  28539. if (mSubTickLengthIn != inside)
  28540. {
  28541. mSubTickLengthIn = inside;
  28542. }
  28543. }
  28544. /*!
  28545. Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach
  28546. outside the plot. If \a outside is greater than zero, the tick labels will increase their
  28547. distance to the axis accordingly, so they won't collide with the ticks.
  28548. \see setSubTickLengthIn, setSubTickLength, setTickLength
  28549. */
  28550. void QCPPolarAxisAngular::setSubTickLengthOut(int outside)
  28551. {
  28552. if (mSubTickLengthOut != outside)
  28553. {
  28554. mSubTickLengthOut = outside;
  28555. //mCachedMarginValid = false; // only outside tick length can change margin
  28556. }
  28557. }
  28558. /*!
  28559. Sets the pen, the axis base line is drawn with.
  28560. \see setTickPen, setSubTickPen
  28561. */
  28562. void QCPPolarAxisAngular::setBasePen(const QPen &pen)
  28563. {
  28564. mBasePen = pen;
  28565. }
  28566. /*!
  28567. Sets the pen, tick marks will be drawn with.
  28568. \see setTickLength, setBasePen
  28569. */
  28570. void QCPPolarAxisAngular::setTickPen(const QPen &pen)
  28571. {
  28572. mTickPen = pen;
  28573. }
  28574. /*!
  28575. Sets the pen, subtick marks will be drawn with.
  28576. \see setSubTickCount, setSubTickLength, setBasePen
  28577. */
  28578. void QCPPolarAxisAngular::setSubTickPen(const QPen &pen)
  28579. {
  28580. mSubTickPen = pen;
  28581. }
  28582. /*!
  28583. Sets the font of the axis label.
  28584. \see setLabelColor
  28585. */
  28586. void QCPPolarAxisAngular::setLabelFont(const QFont &font)
  28587. {
  28588. if (mLabelFont != font)
  28589. {
  28590. mLabelFont = font;
  28591. //mCachedMarginValid = false;
  28592. }
  28593. }
  28594. /*!
  28595. Sets the color of the axis label.
  28596. \see setLabelFont
  28597. */
  28598. void QCPPolarAxisAngular::setLabelColor(const QColor &color)
  28599. {
  28600. mLabelColor = color;
  28601. }
  28602. /*!
  28603. Sets the text of the axis label that will be shown below/above or next to the axis, depending on
  28604. its orientation. To disable axis labels, pass an empty string as \a str.
  28605. */
  28606. void QCPPolarAxisAngular::setLabel(const QString &str)
  28607. {
  28608. if (mLabel != str)
  28609. {
  28610. mLabel = str;
  28611. //mCachedMarginValid = false;
  28612. }
  28613. }
  28614. /*!
  28615. Sets the distance between the tick labels and the axis label.
  28616. \see setTickLabelPadding, setPadding
  28617. */
  28618. void QCPPolarAxisAngular::setLabelPadding(int padding)
  28619. {
  28620. if (mLabelPadding != padding)
  28621. {
  28622. mLabelPadding = padding;
  28623. //mCachedMarginValid = false;
  28624. }
  28625. }
  28626. /*!
  28627. Sets the font that is used for tick labels when they are selected.
  28628. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28629. */
  28630. void QCPPolarAxisAngular::setSelectedTickLabelFont(const QFont &font)
  28631. {
  28632. if (font != mSelectedTickLabelFont)
  28633. {
  28634. mSelectedTickLabelFont = font;
  28635. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  28636. }
  28637. }
  28638. /*!
  28639. Sets the font that is used for the axis label when it is selected.
  28640. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28641. */
  28642. void QCPPolarAxisAngular::setSelectedLabelFont(const QFont &font)
  28643. {
  28644. mSelectedLabelFont = font;
  28645. // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts
  28646. }
  28647. /*!
  28648. Sets the color that is used for tick labels when they are selected.
  28649. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28650. */
  28651. void QCPPolarAxisAngular::setSelectedTickLabelColor(const QColor &color)
  28652. {
  28653. if (color != mSelectedTickLabelColor)
  28654. {
  28655. mSelectedTickLabelColor = color;
  28656. }
  28657. }
  28658. /*!
  28659. Sets the color that is used for the axis label when it is selected.
  28660. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28661. */
  28662. void QCPPolarAxisAngular::setSelectedLabelColor(const QColor &color)
  28663. {
  28664. mSelectedLabelColor = color;
  28665. }
  28666. /*!
  28667. Sets the pen that is used to draw the axis base line when selected.
  28668. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28669. */
  28670. void QCPPolarAxisAngular::setSelectedBasePen(const QPen &pen)
  28671. {
  28672. mSelectedBasePen = pen;
  28673. }
  28674. /*!
  28675. Sets the pen that is used to draw the (major) ticks when selected.
  28676. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28677. */
  28678. void QCPPolarAxisAngular::setSelectedTickPen(const QPen &pen)
  28679. {
  28680. mSelectedTickPen = pen;
  28681. }
  28682. /*!
  28683. Sets the pen that is used to draw the subticks when selected.
  28684. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions
  28685. */
  28686. void QCPPolarAxisAngular::setSelectedSubTickPen(const QPen &pen)
  28687. {
  28688. mSelectedSubTickPen = pen;
  28689. }
  28690. /*! \internal
  28691. Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a
  28692. pixmap.
  28693. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an
  28694. according filling inside the axis rect with the provided \a painter.
  28695. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version
  28696. depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside
  28697. the axis rect with the provided \a painter. The scaled version is buffered in
  28698. mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when
  28699. the axis rect has changed in a way that requires a rescale of the background pixmap (this is
  28700. dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was
  28701. set.
  28702. \see setBackground, setBackgroundScaled, setBackgroundScaledMode
  28703. */
  28704. void QCPPolarAxisAngular::drawBackground(QCPPainter *painter, const QPointF &center, double radius)
  28705. {
  28706. // draw background fill (don't use circular clip, looks bad):
  28707. if (mBackgroundBrush != Qt::NoBrush)
  28708. {
  28709. QPainterPath ellipsePath;
  28710. ellipsePath.addEllipse(center, radius, radius);
  28711. painter->fillPath(ellipsePath, mBackgroundBrush);
  28712. }
  28713. // draw background pixmap (on top of fill, if brush specified):
  28714. if (!mBackgroundPixmap.isNull())
  28715. {
  28716. QRegion clipCircle(center.x()-radius, center.y()-radius, qRound(2*radius), qRound(2*radius), QRegion::Ellipse);
  28717. QRegion originalClip = painter->clipRegion();
  28718. painter->setClipRegion(clipCircle);
  28719. if (mBackgroundScaled)
  28720. {
  28721. // check whether mScaledBackground needs to be updated:
  28722. QSize scaledSize(mBackgroundPixmap.size());
  28723. scaledSize.scale(mRect.size(), mBackgroundScaledMode);
  28724. if (mScaledBackgroundPixmap.size() != scaledSize)
  28725. mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation);
  28726. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect());
  28727. } else
  28728. {
  28729. painter->drawPixmap(mRect.topLeft()+QPoint(0, -1), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()));
  28730. }
  28731. painter->setClipRegion(originalClip);
  28732. }
  28733. }
  28734. /*! \internal
  28735. Prepares the internal tick vector, sub tick vector and tick label vector. This is done by calling
  28736. QCPAxisTicker::generate on the currently installed ticker.
  28737. If a change in the label text/count is detected, the cached axis margin is invalidated to make
  28738. sure the next margin calculation recalculates the label sizes and returns an up-to-date value.
  28739. */
  28740. void QCPPolarAxisAngular::setupTickVectors()
  28741. {
  28742. if (!mParentPlot) return;
  28743. if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return;
  28744. mSubTickVector.clear(); // since we might not pass it to mTicker->generate(), and we don't want old data in there
  28745. mTicker->generate(mRange, mParentPlot->locale(), mNumberFormatChar, mNumberPrecision, mTickVector, mSubTicks ? &mSubTickVector : 0, mTickLabels ? &mTickVectorLabels : 0);
  28746. // fill cos/sin buffers which will be used by draw() and QCPPolarGrid::draw(), so we don't have to calculate it twice:
  28747. mTickVectorCosSin.resize(mTickVector.size());
  28748. for (int i=0; i<mTickVector.size(); ++i)
  28749. {
  28750. const double theta = coordToAngleRad(mTickVector.at(i));
  28751. mTickVectorCosSin[i] = QPointF(qCos(theta), qSin(theta));
  28752. }
  28753. mSubTickVectorCosSin.resize(mSubTickVector.size());
  28754. for (int i=0; i<mSubTickVector.size(); ++i)
  28755. {
  28756. const double theta = coordToAngleRad(mSubTickVector.at(i));
  28757. mSubTickVectorCosSin[i] = QPointF(qCos(theta), qSin(theta));
  28758. }
  28759. }
  28760. /*! \internal
  28761. Returns the pen that is used to draw the axis base line. Depending on the selection state, this
  28762. is either mSelectedBasePen or mBasePen.
  28763. */
  28764. QPen QCPPolarAxisAngular::getBasePen() const
  28765. {
  28766. return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen;
  28767. }
  28768. /*! \internal
  28769. Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this
  28770. is either mSelectedTickPen or mTickPen.
  28771. */
  28772. QPen QCPPolarAxisAngular::getTickPen() const
  28773. {
  28774. return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen;
  28775. }
  28776. /*! \internal
  28777. Returns the pen that is used to draw the subticks. Depending on the selection state, this
  28778. is either mSelectedSubTickPen or mSubTickPen.
  28779. */
  28780. QPen QCPPolarAxisAngular::getSubTickPen() const
  28781. {
  28782. return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen;
  28783. }
  28784. /*! \internal
  28785. Returns the font that is used to draw the tick labels. Depending on the selection state, this
  28786. is either mSelectedTickLabelFont or mTickLabelFont.
  28787. */
  28788. QFont QCPPolarAxisAngular::getTickLabelFont() const
  28789. {
  28790. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont;
  28791. }
  28792. /*! \internal
  28793. Returns the font that is used to draw the axis label. Depending on the selection state, this
  28794. is either mSelectedLabelFont or mLabelFont.
  28795. */
  28796. QFont QCPPolarAxisAngular::getLabelFont() const
  28797. {
  28798. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont;
  28799. }
  28800. /*! \internal
  28801. Returns the color that is used to draw the tick labels. Depending on the selection state, this
  28802. is either mSelectedTickLabelColor or mTickLabelColor.
  28803. */
  28804. QColor QCPPolarAxisAngular::getTickLabelColor() const
  28805. {
  28806. return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor;
  28807. }
  28808. /*! \internal
  28809. Returns the color that is used to draw the axis label. Depending on the selection state, this
  28810. is either mSelectedLabelColor or mLabelColor.
  28811. */
  28812. QColor QCPPolarAxisAngular::getLabelColor() const
  28813. {
  28814. return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor;
  28815. }
  28816. /*! \internal
  28817. Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is
  28818. pressed, the range dragging interaction is initialized (the actual range manipulation happens in
  28819. the \ref mouseMoveEvent).
  28820. The mDragging flag is set to true and some anchor points are set that are needed to determine the
  28821. distance the mouse was dragged in the mouse move/release events later.
  28822. \see mouseMoveEvent, mouseReleaseEvent
  28823. */
  28824. void QCPPolarAxisAngular::mousePressEvent(QMouseEvent *event, const QVariant &details)
  28825. {
  28826. Q_UNUSED(details)
  28827. if (event->buttons() & Qt::LeftButton)
  28828. {
  28829. mDragging = true;
  28830. // initialize antialiasing backup in case we start dragging:
  28831. if (mParentPlot->noAntialiasingOnDrag())
  28832. {
  28833. mAADragBackup = mParentPlot->antialiasedElements();
  28834. mNotAADragBackup = mParentPlot->notAntialiasedElements();
  28835. }
  28836. // Mouse range dragging interaction:
  28837. if (mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  28838. {
  28839. mDragAngularStart = range();
  28840. mDragRadialStart.clear();
  28841. for (int i=0; i<mRadialAxes.size(); ++i)
  28842. mDragRadialStart.append(mRadialAxes.at(i)->range());
  28843. }
  28844. }
  28845. }
  28846. /*! \internal
  28847. Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a
  28848. preceding \ref mousePressEvent, the range is moved accordingly.
  28849. \see mousePressEvent, mouseReleaseEvent
  28850. */
  28851. void QCPPolarAxisAngular::mouseMoveEvent(QMouseEvent *event, const QPointF &startPos)
  28852. {
  28853. Q_UNUSED(startPos)
  28854. bool doReplot = false;
  28855. // Mouse range dragging interaction:
  28856. if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag))
  28857. {
  28858. if (mRangeDrag)
  28859. {
  28860. doReplot = true;
  28861. double angleCoordStart, radiusCoordStart;
  28862. double angleCoord, radiusCoord;
  28863. pixelToCoord(startPos, angleCoordStart, radiusCoordStart);
  28864. pixelToCoord(event->pos(), angleCoord, radiusCoord);
  28865. double diff = angleCoordStart - angleCoord;
  28866. setRange(mDragAngularStart.lower+diff, mDragAngularStart.upper+diff);
  28867. }
  28868. for (int i=0; i<mRadialAxes.size(); ++i)
  28869. {
  28870. QCPPolarAxisRadial *ax = mRadialAxes.at(i);
  28871. if (!ax->rangeDrag())
  28872. continue;
  28873. doReplot = true;
  28874. double angleCoordStart, radiusCoordStart;
  28875. double angleCoord, radiusCoord;
  28876. ax->pixelToCoord(startPos, angleCoordStart, radiusCoordStart);
  28877. ax->pixelToCoord(event->pos(), angleCoord, radiusCoord);
  28878. if (ax->scaleType() == QCPPolarAxisRadial::ScaleType::stLinear)
  28879. {
  28880. double diff = radiusCoordStart - radiusCoord;
  28881. ax->setRange(mDragRadialStart.at(i).lower+diff, mDragRadialStart.at(i).upper+diff);
  28882. } else if (ax->scaleType() == QCPPolarAxisRadial::ScaleType::stLogarithmic)
  28883. {
  28884. if (radiusCoord != 0)
  28885. {
  28886. double diff = radiusCoordStart/radiusCoord;
  28887. ax->setRange(mDragRadialStart.at(i).lower*diff, mDragRadialStart.at(i).upper*diff);
  28888. }
  28889. }
  28890. }
  28891. if (doReplot) // if either vertical or horizontal drag was enabled, do a replot
  28892. {
  28893. if (mParentPlot->noAntialiasingOnDrag())
  28894. mParentPlot->setNotAntialiasedElements(QCP::aeAll);
  28895. mParentPlot->replot(QCustomPlot::rpQueuedReplot);
  28896. }
  28897. }
  28898. }
  28899. /* inherits documentation from base class */
  28900. void QCPPolarAxisAngular::mouseReleaseEvent(QMouseEvent *event, const QPointF &startPos)
  28901. {
  28902. Q_UNUSED(event)
  28903. Q_UNUSED(startPos)
  28904. mDragging = false;
  28905. if (mParentPlot->noAntialiasingOnDrag())
  28906. {
  28907. mParentPlot->setAntialiasedElements(mAADragBackup);
  28908. mParentPlot->setNotAntialiasedElements(mNotAADragBackup);
  28909. }
  28910. }
  28911. /*! \internal
  28912. Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the
  28913. ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of
  28914. the scaling operation is the current cursor position inside the axis rect. The scaling factor is
  28915. dependent on the mouse wheel delta (which direction the wheel was rotated) to provide a natural
  28916. zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor.
  28917. Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse
  28918. wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be
  28919. multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as
  28920. exponent of the range zoom factor. This takes care of the wheel direction automatically, by
  28921. inverting the factor, when the wheel step is negative (f^-1 = 1/f).
  28922. */
  28923. void QCPPolarAxisAngular::wheelEvent(QWheelEvent *event)
  28924. {
  28925. bool doReplot = false;
  28926. // Mouse range zooming interaction:
  28927. if (mParentPlot->interactions().testFlag(QCP::iRangeZoom))
  28928. {
  28929. #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
  28930. const double delta = event->delta();
  28931. #else
  28932. const double delta = event->angleDelta().y();
  28933. #endif
  28934. #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
  28935. const QPointF pos = event->pos();
  28936. #else
  28937. const QPointF pos = event->position();
  28938. #endif
  28939. const double wheelSteps = delta/120.0; // a single step delta is +/-120 usually
  28940. if (mRangeZoom)
  28941. {
  28942. double angleCoord, radiusCoord;
  28943. pixelToCoord(pos, angleCoord, radiusCoord);
  28944. scaleRange(qPow(mRangeZoomFactor, wheelSteps), angleCoord);
  28945. }
  28946. for (int i=0; i<mRadialAxes.size(); ++i)
  28947. {
  28948. QCPPolarAxisRadial *ax = mRadialAxes.at(i);
  28949. if (!ax->rangeZoom())
  28950. continue;
  28951. doReplot = true;
  28952. double angleCoord, radiusCoord;
  28953. ax->pixelToCoord(pos, angleCoord, radiusCoord);
  28954. ax->scaleRange(qPow(ax->rangeZoomFactor(), wheelSteps), radiusCoord);
  28955. }
  28956. }
  28957. if (doReplot)
  28958. mParentPlot->replot();
  28959. }
  28960. bool QCPPolarAxisAngular::registerPolarGraph(QCPPolarGraph *graph)
  28961. {
  28962. if (mGraphs.contains(graph))
  28963. {
  28964. qDebug() << Q_FUNC_INFO << "plottable already added:" << reinterpret_cast<quintptr>(graph);
  28965. return false;
  28966. }
  28967. if (graph->keyAxis() != this)
  28968. {
  28969. qDebug() << Q_FUNC_INFO << "plottable not created with this as axis:" << reinterpret_cast<quintptr>(graph);
  28970. return false;
  28971. }
  28972. mGraphs.append(graph);
  28973. // possibly add plottable to legend:
  28974. if (mParentPlot->autoAddPlottableToLegend())
  28975. graph->addToLegend();
  28976. if (!graph->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor)
  28977. graph->setLayer(mParentPlot->currentLayer());
  28978. return true;
  28979. }
  28980. /* end of 'src/polar/layoutelement-angularaxis.cpp' */
  28981. /* including file 'src/polar/polargrid.cpp' */
  28982. /* modified 2021-03-29T02:30:44, size 7493 */
  28983. ////////////////////////////////////////////////////////////////////////////////////////////////////
  28984. //////////////////// QCPPolarGrid
  28985. ////////////////////////////////////////////////////////////////////////////////////////////////////
  28986. /*! \class QCPPolarGrid
  28987. \brief The grid in both angular and radial dimensions for polar plots
  28988. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  28989. functionality to be incomplete, as well as changing public interfaces in the future.
  28990. */
  28991. /*!
  28992. Creates a QCPPolarGrid instance and sets default values.
  28993. You shouldn't instantiate grids on their own, since every axis brings its own grid.
  28994. */
  28995. QCPPolarGrid::QCPPolarGrid(QCPPolarAxisAngular *parentAxis) :
  28996. QCPLayerable(parentAxis->parentPlot(), QString(), parentAxis),
  28997. mType(gtNone),
  28998. mSubGridType(gtNone),
  28999. mAntialiasedSubGrid(true),
  29000. mAntialiasedZeroLine(true),
  29001. mParentAxis(parentAxis)
  29002. {
  29003. // warning: this is called in QCPPolarAxisAngular constructor, so parentAxis members should not be accessed/called
  29004. setParent(parentAxis);
  29005. setType(gtAll);
  29006. setSubGridType(gtNone);
  29007. setAngularPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  29008. setAngularSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  29009. setRadialPen(QPen(QColor(200,200,200), 0, Qt::DotLine));
  29010. setRadialSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine));
  29011. setRadialZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine));
  29012. setAntialiased(true);
  29013. }
  29014. void QCPPolarGrid::setRadialAxis(QCPPolarAxisRadial *axis)
  29015. {
  29016. mRadialAxis = axis;
  29017. }
  29018. void QCPPolarGrid::setType(GridTypes type)
  29019. {
  29020. mType = type;
  29021. }
  29022. void QCPPolarGrid::setSubGridType(GridTypes type)
  29023. {
  29024. mSubGridType = type;
  29025. }
  29026. /*!
  29027. Sets whether sub grid lines are drawn antialiased.
  29028. */
  29029. void QCPPolarGrid::setAntialiasedSubGrid(bool enabled)
  29030. {
  29031. mAntialiasedSubGrid = enabled;
  29032. }
  29033. /*!
  29034. Sets whether zero lines are drawn antialiased.
  29035. */
  29036. void QCPPolarGrid::setAntialiasedZeroLine(bool enabled)
  29037. {
  29038. mAntialiasedZeroLine = enabled;
  29039. }
  29040. /*!
  29041. Sets the pen with which (major) grid lines are drawn.
  29042. */
  29043. void QCPPolarGrid::setAngularPen(const QPen &pen)
  29044. {
  29045. mAngularPen = pen;
  29046. }
  29047. /*!
  29048. Sets the pen with which sub grid lines are drawn.
  29049. */
  29050. void QCPPolarGrid::setAngularSubGridPen(const QPen &pen)
  29051. {
  29052. mAngularSubGridPen = pen;
  29053. }
  29054. void QCPPolarGrid::setRadialPen(const QPen &pen)
  29055. {
  29056. mRadialPen = pen;
  29057. }
  29058. void QCPPolarGrid::setRadialSubGridPen(const QPen &pen)
  29059. {
  29060. mRadialSubGridPen = pen;
  29061. }
  29062. void QCPPolarGrid::setRadialZeroLinePen(const QPen &pen)
  29063. {
  29064. mRadialZeroLinePen = pen;
  29065. }
  29066. /*! \internal
  29067. A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter
  29068. before drawing the major grid lines.
  29069. This is the antialiasing state the painter passed to the \ref draw method is in by default.
  29070. This function takes into account the local setting of the antialiasing flag as well as the
  29071. overrides set with \ref QCustomPlot::setAntialiasedElements and \ref
  29072. QCustomPlot::setNotAntialiasedElements.
  29073. \see setAntialiased
  29074. */
  29075. void QCPPolarGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const
  29076. {
  29077. applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid);
  29078. }
  29079. /*! \internal
  29080. Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning
  29081. over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen).
  29082. */
  29083. void QCPPolarGrid::draw(QCPPainter *painter)
  29084. {
  29085. if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; }
  29086. const QPointF center = mParentAxis->mCenter;
  29087. const double radius = mParentAxis->mRadius;
  29088. painter->setBrush(Qt::NoBrush);
  29089. // draw main angular grid:
  29090. if (mType.testFlag(gtAngular))
  29091. drawAngularGrid(painter, center, radius, mParentAxis->mTickVectorCosSin, mAngularPen);
  29092. // draw main radial grid:
  29093. if (mType.testFlag(gtRadial) && mRadialAxis)
  29094. drawRadialGrid(painter, center, mRadialAxis->tickVector(), mRadialPen, mRadialZeroLinePen);
  29095. applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeGrid);
  29096. // draw sub angular grid:
  29097. if (mSubGridType.testFlag(gtAngular))
  29098. drawAngularGrid(painter, center, radius, mParentAxis->mSubTickVectorCosSin, mAngularSubGridPen);
  29099. // draw sub radial grid:
  29100. if (mSubGridType.testFlag(gtRadial) && mRadialAxis)
  29101. drawRadialGrid(painter, center, mRadialAxis->subTickVector(), mRadialSubGridPen);
  29102. }
  29103. void QCPPolarGrid::drawRadialGrid(QCPPainter *painter, const QPointF &center, const QVector<double> &coords, const QPen &pen, const QPen &zeroPen)
  29104. {
  29105. if (!mRadialAxis) return;
  29106. if (coords.isEmpty()) return;
  29107. const bool drawZeroLine = zeroPen != Qt::NoPen;
  29108. const double zeroLineEpsilon = qAbs(coords.last()-coords.first())*1e-6;
  29109. painter->setPen(pen);
  29110. for (int i=0; i<coords.size(); ++i)
  29111. {
  29112. const double r = mRadialAxis->coordToRadius(coords.at(i));
  29113. if (drawZeroLine && qAbs(coords.at(i)) < zeroLineEpsilon)
  29114. {
  29115. applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine);
  29116. painter->setPen(zeroPen);
  29117. painter->drawEllipse(center, r, r);
  29118. painter->setPen(pen);
  29119. applyDefaultAntialiasingHint(painter);
  29120. } else
  29121. {
  29122. painter->drawEllipse(center, r, r);
  29123. }
  29124. }
  29125. }
  29126. void QCPPolarGrid::drawAngularGrid(QCPPainter *painter, const QPointF &center, double radius, const QVector<QPointF> &ticksCosSin, const QPen &pen)
  29127. {
  29128. if (ticksCosSin.isEmpty()) return;
  29129. painter->setPen(pen);
  29130. for (int i=0; i<ticksCosSin.size(); ++i)
  29131. painter->drawLine(center, center+ticksCosSin.at(i)*radius);
  29132. }
  29133. /* end of 'src/polar/polargrid.cpp' */
  29134. /* including file 'src/polar/polargraph.cpp' */
  29135. /* modified 2021-03-29T02:30:44, size 44035 */
  29136. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29137. //////////////////// QCPPolarLegendItem
  29138. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29139. /*! \class QCPPolarLegendItem
  29140. \brief A legend item for polar plots
  29141. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  29142. functionality to be incomplete, as well as changing public interfaces in the future.
  29143. */
  29144. QCPPolarLegendItem::QCPPolarLegendItem(QCPLegend *parent, QCPPolarGraph *graph) :
  29145. QCPAbstractLegendItem(parent),
  29146. mPolarGraph(graph)
  29147. {
  29148. setAntialiased(false);
  29149. }
  29150. void QCPPolarLegendItem::draw(QCPPainter *painter)
  29151. {
  29152. if (!mPolarGraph) return;
  29153. painter->setFont(getFont());
  29154. painter->setPen(QPen(getTextColor()));
  29155. QSizeF iconSize = mParentLegend->iconSize();
  29156. QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name());
  29157. QRectF iconRect(mRect.topLeft(), iconSize);
  29158. int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops
  29159. painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPolarGraph->name());
  29160. // draw icon:
  29161. painter->save();
  29162. painter->setClipRect(iconRect, Qt::IntersectClip);
  29163. mPolarGraph->drawLegendIcon(painter, iconRect);
  29164. painter->restore();
  29165. // draw icon border:
  29166. if (getIconBorderPen().style() != Qt::NoPen)
  29167. {
  29168. painter->setPen(getIconBorderPen());
  29169. painter->setBrush(Qt::NoBrush);
  29170. int halfPen = qCeil(painter->pen().widthF()*0.5)+1;
  29171. painter->setClipRect(mOuterRect.adjusted(-halfPen, -halfPen, halfPen, halfPen)); // extend default clip rect so thicker pens (especially during selection) are not clipped
  29172. painter->drawRect(iconRect);
  29173. }
  29174. }
  29175. QSize QCPPolarLegendItem::minimumOuterSizeHint() const
  29176. {
  29177. if (!mPolarGraph) return QSize();
  29178. QSize result(0, 0);
  29179. QRect textRect;
  29180. QFontMetrics fontMetrics(getFont());
  29181. QSize iconSize = mParentLegend->iconSize();
  29182. textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPolarGraph->name());
  29183. result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width());
  29184. result.setHeight(qMax(textRect.height(), iconSize.height()));
  29185. result.rwidth() += mMargins.left()+mMargins.right();
  29186. result.rheight() += mMargins.top()+mMargins.bottom();
  29187. return result;
  29188. }
  29189. QPen QCPPolarLegendItem::getIconBorderPen() const
  29190. {
  29191. return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen();
  29192. }
  29193. QColor QCPPolarLegendItem::getTextColor() const
  29194. {
  29195. return mSelected ? mSelectedTextColor : mTextColor;
  29196. }
  29197. QFont QCPPolarLegendItem::getFont() const
  29198. {
  29199. return mSelected ? mSelectedFont : mFont;
  29200. }
  29201. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29202. //////////////////// QCPPolarGraph
  29203. ////////////////////////////////////////////////////////////////////////////////////////////////////
  29204. /*! \class QCPPolarGraph
  29205. \brief A radial graph used to display data in polar plots
  29206. \warning In this QCustomPlot version, polar plots are a tech preview. Expect documentation and
  29207. functionality to be incomplete, as well as changing public interfaces in the future.
  29208. */
  29209. /* start of documentation of inline functions */
  29210. // TODO
  29211. /* end of documentation of inline functions */
  29212. /*!
  29213. Constructs a graph which uses \a keyAxis as its angular and \a valueAxis as its radial axis. \a
  29214. keyAxis and \a valueAxis must reside in the same QCustomPlot, and the radial axis must be
  29215. associated with the angular axis. If either of these restrictions is violated, a corresponding
  29216. message is printed to the debug output (qDebug), the construction is not aborted, though.
  29217. The created QCPPolarGraph is automatically registered with the QCustomPlot instance inferred from
  29218. \a keyAxis. This QCustomPlot instance takes ownership of the QCPPolarGraph, so do not delete it
  29219. manually but use QCPPolarAxisAngular::removeGraph() instead.
  29220. To directly create a QCPPolarGraph inside a plot, you shoud use the QCPPolarAxisAngular::addGraph
  29221. method.
  29222. */
  29223. QCPPolarGraph::QCPPolarGraph(QCPPolarAxisAngular *keyAxis, QCPPolarAxisRadial *valueAxis) :
  29224. QCPLayerable(keyAxis->parentPlot(), QString(), keyAxis),
  29225. mDataContainer(new QCPGraphDataContainer),
  29226. mName(),
  29227. mAntialiasedFill(true),
  29228. mAntialiasedScatters(true),
  29229. mPen(Qt::black),
  29230. mBrush(Qt::NoBrush),
  29231. mPeriodic(true),
  29232. mKeyAxis(keyAxis),
  29233. mValueAxis(valueAxis),
  29234. mSelectable(QCP::stWhole)
  29235. //mSelectionDecorator(0) // TODO
  29236. {
  29237. if (keyAxis->parentPlot() != valueAxis->parentPlot())
  29238. qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis.";
  29239. mKeyAxis->registerPolarGraph(this);
  29240. //setSelectionDecorator(new QCPSelectionDecorator); // TODO
  29241. setPen(QPen(Qt::blue, 0));
  29242. setBrush(Qt::NoBrush);
  29243. setLineStyle(lsLine);
  29244. }
  29245. QCPPolarGraph::~QCPPolarGraph()
  29246. {
  29247. /* TODO
  29248. if (mSelectionDecorator)
  29249. {
  29250. delete mSelectionDecorator;
  29251. mSelectionDecorator = 0;
  29252. }
  29253. */
  29254. }
  29255. /*!
  29256. The name is the textual representation of this plottable as it is displayed in the legend
  29257. (\ref QCPLegend). It may contain any UTF-8 characters, including newlines.
  29258. */
  29259. void QCPPolarGraph::setName(const QString &name)
  29260. {
  29261. mName = name;
  29262. }
  29263. /*!
  29264. Sets whether fills of this plottable are drawn antialiased or not.
  29265. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  29266. QCustomPlot::setNotAntialiasedElements.
  29267. */
  29268. void QCPPolarGraph::setAntialiasedFill(bool enabled)
  29269. {
  29270. mAntialiasedFill = enabled;
  29271. }
  29272. /*!
  29273. Sets whether the scatter symbols of this plottable are drawn antialiased or not.
  29274. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref
  29275. QCustomPlot::setNotAntialiasedElements.
  29276. */
  29277. void QCPPolarGraph::setAntialiasedScatters(bool enabled)
  29278. {
  29279. mAntialiasedScatters = enabled;
  29280. }
  29281. /*!
  29282. The pen is used to draw basic lines that make up the plottable representation in the
  29283. plot.
  29284. For example, the \ref QCPGraph subclass draws its graph lines with this pen.
  29285. \see setBrush
  29286. */
  29287. void QCPPolarGraph::setPen(const QPen &pen)
  29288. {
  29289. mPen = pen;
  29290. }
  29291. /*!
  29292. The brush is used to draw basic fills of the plottable representation in the
  29293. plot. The Fill can be a color, gradient or texture, see the usage of QBrush.
  29294. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when
  29295. it's not set to Qt::NoBrush.
  29296. \see setPen
  29297. */
  29298. void QCPPolarGraph::setBrush(const QBrush &brush)
  29299. {
  29300. mBrush = brush;
  29301. }
  29302. void QCPPolarGraph::setPeriodic(bool enabled)
  29303. {
  29304. mPeriodic = enabled;
  29305. }
  29306. /*!
  29307. The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal
  29308. to the plottable's value axis. This function performs no checks to make sure this is the case.
  29309. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the
  29310. y-axis (QCustomPlot::yAxis) as value axis.
  29311. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  29312. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  29313. \see setValueAxis
  29314. */
  29315. void QCPPolarGraph::setKeyAxis(QCPPolarAxisAngular *axis)
  29316. {
  29317. mKeyAxis = axis;
  29318. }
  29319. /*!
  29320. The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is
  29321. orthogonal to the plottable's key axis. This function performs no checks to make sure this is the
  29322. case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and
  29323. the y-axis (QCustomPlot::yAxis) as value axis.
  29324. Normally, the key and value axes are set in the constructor of the plottable (or \ref
  29325. QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface).
  29326. \see setKeyAxis
  29327. */
  29328. void QCPPolarGraph::setValueAxis(QCPPolarAxisRadial *axis)
  29329. {
  29330. mValueAxis = axis;
  29331. }
  29332. /*!
  29333. Sets whether and to which granularity this plottable can be selected.
  29334. A selection can happen by clicking on the QCustomPlot surface (When \ref
  29335. QCustomPlot::setInteractions contains \ref QCP::iSelectPlottables), by dragging a selection rect
  29336. (When \ref QCustomPlot::setSelectionRectMode is \ref QCP::srmSelect), or programmatically by
  29337. calling \ref setSelection.
  29338. \see setSelection, QCP::SelectionType
  29339. */
  29340. void QCPPolarGraph::setSelectable(QCP::SelectionType selectable)
  29341. {
  29342. if (mSelectable != selectable)
  29343. {
  29344. mSelectable = selectable;
  29345. QCPDataSelection oldSelection = mSelection;
  29346. mSelection.enforceType(mSelectable);
  29347. emit selectableChanged(mSelectable);
  29348. if (mSelection != oldSelection)
  29349. {
  29350. emit selectionChanged(selected());
  29351. emit selectionChanged(mSelection);
  29352. }
  29353. }
  29354. }
  29355. /*!
  29356. Sets which data ranges of this plottable are selected. Selected data ranges are drawn differently
  29357. (e.g. color) in the plot. This can be controlled via the selection decorator (see \ref
  29358. selectionDecorator).
  29359. The entire selection mechanism for plottables is handled automatically when \ref
  29360. QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when
  29361. you wish to change the selection state programmatically.
  29362. Using \ref setSelectable you can further specify for each plottable whether and to which
  29363. granularity it is selectable. If \a selection is not compatible with the current \ref
  29364. QCP::SelectionType set via \ref setSelectable, the resulting selection will be adjusted
  29365. accordingly (see \ref QCPDataSelection::enforceType).
  29366. emits the \ref selectionChanged signal when \a selected is different from the previous selection state.
  29367. \see setSelectable, selectTest
  29368. */
  29369. void QCPPolarGraph::setSelection(QCPDataSelection selection)
  29370. {
  29371. selection.enforceType(mSelectable);
  29372. if (mSelection != selection)
  29373. {
  29374. mSelection = selection;
  29375. emit selectionChanged(selected());
  29376. emit selectionChanged(mSelection);
  29377. }
  29378. }
  29379. /*! \overload
  29380. Replaces the current data container with the provided \a data container.
  29381. Since a QSharedPointer is used, multiple QCPPolarGraphs may share the same data container safely.
  29382. Modifying the data in the container will then affect all graphs that share the container. Sharing
  29383. can be achieved by simply exchanging the data containers wrapped in shared pointers:
  29384. \snippet documentation/doc-code-snippets/mainwindow.cpp QCPPolarGraph-datasharing-1
  29385. If you do not wish to share containers, but create a copy from an existing container, rather use
  29386. the \ref QCPDataContainer<DataType>::set method on the graph's data container directly:
  29387. \snippet documentation/doc-code-snippets/mainwindow.cpp QCPPolarGraph-datasharing-2
  29388. \see addData
  29389. */
  29390. void QCPPolarGraph::setData(QSharedPointer<QCPGraphDataContainer> data)
  29391. {
  29392. mDataContainer = data;
  29393. }
  29394. /*! \overload
  29395. Replaces the current data with the provided points in \a keys and \a values. The provided
  29396. vectors should have equal length. Else, the number of added points will be the size of the
  29397. smallest vector.
  29398. If you can guarantee that the passed data points are sorted by \a keys in ascending order, you
  29399. can set \a alreadySorted to true, to improve performance by saving a sorting run.
  29400. \see addData
  29401. */
  29402. void QCPPolarGraph::setData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  29403. {
  29404. mDataContainer->clear();
  29405. addData(keys, values, alreadySorted);
  29406. }
  29407. /*!
  29408. Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to
  29409. \ref lsNone and \ref setScatterStyle to the desired scatter style.
  29410. \see setScatterStyle
  29411. */
  29412. void QCPPolarGraph::setLineStyle(LineStyle ls)
  29413. {
  29414. mLineStyle = ls;
  29415. }
  29416. /*!
  29417. Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points
  29418. are drawn (e.g. for line-only-plots with appropriate line style).
  29419. \see QCPScatterStyle, setLineStyle
  29420. */
  29421. void QCPPolarGraph::setScatterStyle(const QCPScatterStyle &style)
  29422. {
  29423. mScatterStyle = style;
  29424. }
  29425. void QCPPolarGraph::addData(const QVector<double> &keys, const QVector<double> &values, bool alreadySorted)
  29426. {
  29427. if (keys.size() != values.size())
  29428. qDebug() << Q_FUNC_INFO << "keys and values have different sizes:" << keys.size() << values.size();
  29429. const int n = qMin(keys.size(), values.size());
  29430. QVector<QCPGraphData> tempData(n);
  29431. QVector<QCPGraphData>::iterator it = tempData.begin();
  29432. const QVector<QCPGraphData>::iterator itEnd = tempData.end();
  29433. int i = 0;
  29434. while (it != itEnd)
  29435. {
  29436. it->key = keys[i];
  29437. it->value = values[i];
  29438. ++it;
  29439. ++i;
  29440. }
  29441. mDataContainer->add(tempData, alreadySorted); // don't modify tempData beyond this to prevent copy on write
  29442. }
  29443. void QCPPolarGraph::addData(double key, double value)
  29444. {
  29445. mDataContainer->add(QCPGraphData(key, value));
  29446. }
  29447. /*!
  29448. Use this method to set an own QCPSelectionDecorator (subclass) instance. This allows you to
  29449. customize the visual representation of selected data ranges further than by using the default
  29450. QCPSelectionDecorator.
  29451. The plottable takes ownership of the \a decorator.
  29452. The currently set decorator can be accessed via \ref selectionDecorator.
  29453. */
  29454. /*
  29455. void QCPPolarGraph::setSelectionDecorator(QCPSelectionDecorator *decorator)
  29456. {
  29457. if (decorator)
  29458. {
  29459. if (decorator->registerWithPlottable(this))
  29460. {
  29461. if (mSelectionDecorator) // delete old decorator if necessary
  29462. delete mSelectionDecorator;
  29463. mSelectionDecorator = decorator;
  29464. }
  29465. } else if (mSelectionDecorator) // just clear decorator
  29466. {
  29467. delete mSelectionDecorator;
  29468. mSelectionDecorator = 0;
  29469. }
  29470. }
  29471. */
  29472. void QCPPolarGraph::coordsToPixels(double key, double value, double &x, double &y) const
  29473. {
  29474. if (mValueAxis)
  29475. {
  29476. const QPointF point = mValueAxis->coordToPixel(key, value);
  29477. x = point.x();
  29478. y = point.y();
  29479. } else
  29480. {
  29481. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29482. }
  29483. }
  29484. const QPointF QCPPolarGraph::coordsToPixels(double key, double value) const
  29485. {
  29486. if (mValueAxis)
  29487. {
  29488. return mValueAxis->coordToPixel(key, value);
  29489. } else
  29490. {
  29491. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29492. return QPointF();
  29493. }
  29494. }
  29495. void QCPPolarGraph::pixelsToCoords(double x, double y, double &key, double &value) const
  29496. {
  29497. if (mValueAxis)
  29498. {
  29499. mValueAxis->pixelToCoord(QPointF(x, y), key, value);
  29500. } else
  29501. {
  29502. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29503. }
  29504. }
  29505. void QCPPolarGraph::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const
  29506. {
  29507. if (mValueAxis)
  29508. {
  29509. mValueAxis->pixelToCoord(pixelPos, key, value);
  29510. } else
  29511. {
  29512. qDebug() << Q_FUNC_INFO << "invalid key or value axis";
  29513. }
  29514. }
  29515. void QCPPolarGraph::rescaleAxes(bool onlyEnlarge) const
  29516. {
  29517. rescaleKeyAxis(onlyEnlarge);
  29518. rescaleValueAxis(onlyEnlarge);
  29519. }
  29520. void QCPPolarGraph::rescaleKeyAxis(bool onlyEnlarge) const
  29521. {
  29522. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  29523. if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; }
  29524. bool foundRange;
  29525. QCPRange newRange = getKeyRange(foundRange, QCP::SignDomain::sdBoth);
  29526. if (foundRange)
  29527. {
  29528. if (onlyEnlarge)
  29529. newRange.expand(keyAxis->range());
  29530. 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
  29531. {
  29532. 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
  29533. newRange.lower = center-keyAxis->range().size()/2.0;
  29534. newRange.upper = center+keyAxis->range().size()/2.0;
  29535. }
  29536. keyAxis->setRange(newRange);
  29537. }
  29538. }
  29539. void QCPPolarGraph::rescaleValueAxis(bool onlyEnlarge, bool inKeyRange) const
  29540. {
  29541. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  29542. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  29543. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  29544. QCP::SignDomain signDomain = QCP::SignDomain::sdBoth;
  29545. if (valueAxis->scaleType() == QCPPolarAxisRadial::ScaleType::stLogarithmic)
  29546. signDomain = (valueAxis->range().upper < 0 ? QCP::SignDomain::sdNegative : QCP::SignDomain:: sdPositive);
  29547. bool foundRange;
  29548. QCPRange newRange = getValueRange(foundRange, signDomain, inKeyRange ? keyAxis->range() : QCPRange());
  29549. if (foundRange)
  29550. {
  29551. if (onlyEnlarge)
  29552. newRange.expand(valueAxis->range());
  29553. 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
  29554. {
  29555. 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
  29556. if (valueAxis->scaleType() == QCPPolarAxisRadial::ScaleType::stLinear)
  29557. {
  29558. newRange.lower = center-valueAxis->range().size()/2.0;
  29559. newRange.upper = center+valueAxis->range().size()/2.0;
  29560. } else // scaleType() == ScaleType::stLogarithmic
  29561. {
  29562. newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  29563. newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower);
  29564. }
  29565. }
  29566. valueAxis->setRange(newRange);
  29567. }
  29568. }
  29569. bool QCPPolarGraph::addToLegend(QCPLegend *legend)
  29570. {
  29571. if (!legend)
  29572. {
  29573. qDebug() << Q_FUNC_INFO << "passed legend is null";
  29574. return false;
  29575. }
  29576. if (legend->parentPlot() != mParentPlot)
  29577. {
  29578. qDebug() << Q_FUNC_INFO << "passed legend isn't in the same QCustomPlot as this plottable";
  29579. return false;
  29580. }
  29581. //if (!legend->hasItemWithPlottable(this)) // TODO
  29582. //{
  29583. legend->addItem(new QCPPolarLegendItem(legend, this));
  29584. return true;
  29585. //} else
  29586. // return false;
  29587. }
  29588. bool QCPPolarGraph::addToLegend()
  29589. {
  29590. if (!mParentPlot || !mParentPlot->legend)
  29591. return false;
  29592. else
  29593. return addToLegend(mParentPlot->legend);
  29594. }
  29595. bool QCPPolarGraph::removeFromLegend(QCPLegend *legend) const
  29596. {
  29597. if (!legend)
  29598. {
  29599. qDebug() << Q_FUNC_INFO << "passed legend is null";
  29600. return false;
  29601. }
  29602. QCPPolarLegendItem *removableItem = 0;
  29603. for (int i=0; i<legend->itemCount(); ++i) // TODO: reduce this to code in QCPAbstractPlottable::removeFromLegend once unified
  29604. {
  29605. if (QCPPolarLegendItem *pli = qobject_cast<QCPPolarLegendItem*>(legend->item(i)))
  29606. {
  29607. if (pli->polarGraph() == this)
  29608. {
  29609. removableItem = pli;
  29610. break;
  29611. }
  29612. }
  29613. }
  29614. if (removableItem)
  29615. return legend->removeItem(removableItem);
  29616. else
  29617. return false;
  29618. }
  29619. bool QCPPolarGraph::removeFromLegend() const
  29620. {
  29621. if (!mParentPlot || !mParentPlot->legend)
  29622. return false;
  29623. else
  29624. return removeFromLegend(mParentPlot->legend);
  29625. }
  29626. double QCPPolarGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const
  29627. {
  29628. if ((onlySelectable && mSelectable == QCP::stNone) || mDataContainer->isEmpty())
  29629. return -1;
  29630. if (!mKeyAxis || !mValueAxis)
  29631. return -1;
  29632. if (mKeyAxis->rect().contains(pos.toPoint()))
  29633. {
  29634. QCPGraphDataContainer::const_iterator closestDataPoint = mDataContainer->constEnd();
  29635. double result = pointDistance(pos, closestDataPoint);
  29636. if (details)
  29637. {
  29638. int pointIndex = closestDataPoint-mDataContainer->constBegin();
  29639. details->setValue(QCPDataSelection(QCPDataRange(pointIndex, pointIndex+1)));
  29640. }
  29641. return result;
  29642. } else
  29643. return -1;
  29644. }
  29645. /* inherits documentation from base class */
  29646. QCPRange QCPPolarGraph::getKeyRange(bool &foundRange, QCP::SignDomain inSignDomain) const
  29647. {
  29648. return mDataContainer->keyRange(foundRange, inSignDomain);
  29649. }
  29650. /* inherits documentation from base class */
  29651. QCPRange QCPPolarGraph::getValueRange(bool &foundRange, QCP::SignDomain inSignDomain, const QCPRange &inKeyRange) const
  29652. {
  29653. return mDataContainer->valueRange(foundRange, inSignDomain, inKeyRange);
  29654. }
  29655. /* inherits documentation from base class */
  29656. QRect QCPPolarGraph::clipRect() const
  29657. {
  29658. if (mKeyAxis)
  29659. return mKeyAxis.data()->rect();
  29660. else
  29661. return QRect();
  29662. }
  29663. void QCPPolarGraph::draw(QCPPainter *painter)
  29664. {
  29665. if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  29666. if (mKeyAxis.data()->range().size() <= 0 || mDataContainer->isEmpty()) return;
  29667. if (mLineStyle == lsNone && mScatterStyle.isNone()) return;
  29668. painter->setClipRegion(mKeyAxis->exactClipRegion());
  29669. QVector<QPointF> lines, scatters; // line and (if necessary) scatter pixel coordinates will be stored here while iterating over segments
  29670. // loop over and draw segments of unselected/selected data:
  29671. QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
  29672. getDataSegments(selectedSegments, unselectedSegments);
  29673. allSegments << unselectedSegments << selectedSegments;
  29674. for (int i=0; i<allSegments.size(); ++i)
  29675. {
  29676. bool isSelectedSegment = i >= unselectedSegments.size();
  29677. // get line pixel points appropriate to line style:
  29678. 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)
  29679. getLines(&lines, lineDataRange);
  29680. // check data validity if flag set:
  29681. #ifdef QCUSTOMPLOT_CHECK_DATA
  29682. QCPGraphDataContainer::const_iterator it;
  29683. for (it = mDataContainer->constBegin(); it != mDataContainer->constEnd(); ++it)
  29684. {
  29685. if (QCP::isInvalidData(it->key, it->value))
  29686. qDebug() << Q_FUNC_INFO << "Data point at" << it->key << "invalid." << "Plottable name:" << name();
  29687. }
  29688. #endif
  29689. // draw fill of graph:
  29690. //if (isSelectedSegment && mSelectionDecorator)
  29691. // mSelectionDecorator->applyBrush(painter);
  29692. //else
  29693. painter->setBrush(mBrush);
  29694. painter->setPen(Qt::NoPen);
  29695. drawFill(painter, &lines);
  29696. // draw line:
  29697. if (mLineStyle != lsNone)
  29698. {
  29699. //if (isSelectedSegment && mSelectionDecorator)
  29700. // mSelectionDecorator->applyPen(painter);
  29701. //else
  29702. painter->setPen(mPen);
  29703. painter->setBrush(Qt::NoBrush);
  29704. drawLinePlot(painter, lines);
  29705. }
  29706. // draw scatters:
  29707. QCPScatterStyle finalScatterStyle = mScatterStyle;
  29708. //if (isSelectedSegment && mSelectionDecorator)
  29709. // finalScatterStyle = mSelectionDecorator->getFinalScatterStyle(mScatterStyle);
  29710. if (!finalScatterStyle.isNone())
  29711. {
  29712. getScatters(&scatters, allSegments.at(i));
  29713. drawScatterPlot(painter, scatters, finalScatterStyle);
  29714. }
  29715. }
  29716. // draw other selection decoration that isn't just line/scatter pens and brushes:
  29717. //if (mSelectionDecorator)
  29718. // mSelectionDecorator->drawDecoration(painter, selection());
  29719. }
  29720. QCP::Interaction QCPPolarGraph::selectionCategory() const
  29721. {
  29722. return QCP::iSelectPlottables;
  29723. }
  29724. void QCPPolarGraph::applyDefaultAntialiasingHint(QCPPainter *painter) const
  29725. {
  29726. applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables);
  29727. }
  29728. /* inherits documentation from base class */
  29729. void QCPPolarGraph::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged)
  29730. {
  29731. Q_UNUSED(event)
  29732. if (mSelectable != QCP::stNone)
  29733. {
  29734. QCPDataSelection newSelection = details.value<QCPDataSelection>();
  29735. QCPDataSelection selectionBefore = mSelection;
  29736. if (additive)
  29737. {
  29738. if (mSelectable == QCP::stWhole) // in whole selection mode, we toggle to no selection even if currently unselected point was hit
  29739. {
  29740. if (selected())
  29741. setSelection(QCPDataSelection());
  29742. else
  29743. setSelection(newSelection);
  29744. } else // in all other selection modes we toggle selections of homogeneously selected/unselected segments
  29745. {
  29746. if (mSelection.contains(newSelection)) // if entire newSelection is already selected, toggle selection
  29747. setSelection(mSelection-newSelection);
  29748. else
  29749. setSelection(mSelection+newSelection);
  29750. }
  29751. } else
  29752. setSelection(newSelection);
  29753. if (selectionStateChanged)
  29754. *selectionStateChanged = mSelection != selectionBefore;
  29755. }
  29756. }
  29757. /* inherits documentation from base class */
  29758. void QCPPolarGraph::deselectEvent(bool *selectionStateChanged)
  29759. {
  29760. if (mSelectable != QCP::stNone)
  29761. {
  29762. QCPDataSelection selectionBefore = mSelection;
  29763. setSelection(QCPDataSelection());
  29764. if (selectionStateChanged)
  29765. *selectionStateChanged = mSelection != selectionBefore;
  29766. }
  29767. }
  29768. /*! \internal
  29769. Draws lines between the points in \a lines, given in pixel coordinates.
  29770. \see drawScatterPlot, drawImpulsePlot, QCPAbstractPlottable1D::drawPolyline
  29771. */
  29772. void QCPPolarGraph::drawLinePlot(QCPPainter *painter, const QVector<QPointF> &lines) const
  29773. {
  29774. if (painter->pen().style() != Qt::NoPen && painter->pen().color().alpha() != 0)
  29775. {
  29776. applyDefaultAntialiasingHint(painter);
  29777. drawPolyline(painter, lines);
  29778. }
  29779. }
  29780. /*! \internal
  29781. Draws the fill of the graph using the specified \a painter, with the currently set brush.
  29782. Depending on whether a normal fill or a channel fill (\ref setChannelFillGraph) is needed, \ref
  29783. getFillPolygon or \ref getChannelFillPolygon are used to find the according fill polygons.
  29784. In order to handle NaN Data points correctly (the fill needs to be split into disjoint areas),
  29785. this method first determines a list of non-NaN segments with \ref getNonNanSegments, on which to
  29786. operate. In the channel fill case, \ref getOverlappingSegments is used to consolidate the non-NaN
  29787. segments of the two involved graphs, before passing the overlapping pairs to \ref
  29788. getChannelFillPolygon.
  29789. Pass the points of this graph's line as \a lines, in pixel coordinates.
  29790. \see drawLinePlot, drawImpulsePlot, drawScatterPlot
  29791. */
  29792. void QCPPolarGraph::drawFill(QCPPainter *painter, QVector<QPointF> *lines) const
  29793. {
  29794. applyFillAntialiasingHint(painter);
  29795. if (painter->brush().style() != Qt::NoBrush && painter->brush().color().alpha() != 0)
  29796. painter->drawPolygon(QPolygonF(*lines));
  29797. }
  29798. /*! \internal
  29799. Draws scatter symbols at every point passed in \a scatters, given in pixel coordinates. The
  29800. scatters will be drawn with \a painter and have the appearance as specified in \a style.
  29801. \see drawLinePlot, drawImpulsePlot
  29802. */
  29803. void QCPPolarGraph::drawScatterPlot(QCPPainter *painter, const QVector<QPointF> &scatters, const QCPScatterStyle &style) const
  29804. {
  29805. applyScattersAntialiasingHint(painter);
  29806. style.applyTo(painter, mPen);
  29807. for (int i=0; i<scatters.size(); ++i)
  29808. style.drawShape(painter, scatters.at(i).x(), scatters.at(i).y());
  29809. }
  29810. void QCPPolarGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const
  29811. {
  29812. // draw fill:
  29813. if (mBrush.style() != Qt::NoBrush)
  29814. {
  29815. applyFillAntialiasingHint(painter);
  29816. painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush);
  29817. }
  29818. // draw line vertically centered:
  29819. if (mLineStyle != lsNone)
  29820. {
  29821. applyDefaultAntialiasingHint(painter);
  29822. painter->setPen(mPen);
  29823. 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
  29824. }
  29825. // draw scatter symbol:
  29826. if (!mScatterStyle.isNone())
  29827. {
  29828. applyScattersAntialiasingHint(painter);
  29829. // scale scatter pixmap if it's too large to fit in legend icon rect:
  29830. if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height()))
  29831. {
  29832. QCPScatterStyle scaledStyle(mScatterStyle);
  29833. scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
  29834. scaledStyle.applyTo(painter, mPen);
  29835. scaledStyle.drawShape(painter, QRectF(rect).center());
  29836. } else
  29837. {
  29838. mScatterStyle.applyTo(painter, mPen);
  29839. mScatterStyle.drawShape(painter, QRectF(rect).center());
  29840. }
  29841. }
  29842. }
  29843. void QCPPolarGraph::applyFillAntialiasingHint(QCPPainter *painter) const
  29844. {
  29845. applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills);
  29846. }
  29847. void QCPPolarGraph::applyScattersAntialiasingHint(QCPPainter *painter) const
  29848. {
  29849. applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters);
  29850. }
  29851. double QCPPolarGraph::pointDistance(const QPointF &pixelPoint, QCPGraphDataContainer::const_iterator &closestData) const
  29852. {
  29853. closestData = mDataContainer->constEnd();
  29854. if (mDataContainer->isEmpty())
  29855. return -1.0;
  29856. if (mLineStyle == lsNone && mScatterStyle.isNone())
  29857. return -1.0;
  29858. // calculate minimum distances to graph data points and find closestData iterator:
  29859. double minDistSqr = (std::numeric_limits<double>::max)();
  29860. // determine which key range comes into question, taking selection tolerance around pos into account:
  29861. double posKeyMin, posKeyMax, dummy;
  29862. pixelsToCoords(pixelPoint-QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMin, dummy);
  29863. pixelsToCoords(pixelPoint+QPointF(mParentPlot->selectionTolerance(), mParentPlot->selectionTolerance()), posKeyMax, dummy);
  29864. if (posKeyMin > posKeyMax)
  29865. qSwap(posKeyMin, posKeyMax);
  29866. // iterate over found data points and then choose the one with the shortest distance to pos:
  29867. QCPGraphDataContainer::const_iterator begin = mDataContainer->findBegin(posKeyMin, true);
  29868. QCPGraphDataContainer::const_iterator end = mDataContainer->findEnd(posKeyMax, true);
  29869. for (QCPGraphDataContainer::const_iterator it=begin; it!=end; ++it)
  29870. {
  29871. const double currentDistSqr = QCPVector2D(coordsToPixels(it->key, it->value)-pixelPoint).lengthSquared();
  29872. if (currentDistSqr < minDistSqr)
  29873. {
  29874. minDistSqr = currentDistSqr;
  29875. closestData = it;
  29876. }
  29877. }
  29878. // calculate distance to graph line if there is one (if so, will probably be smaller than distance to closest data point):
  29879. if (mLineStyle != lsNone)
  29880. {
  29881. // line displayed, calculate distance to line segments:
  29882. QVector<QPointF> lineData;
  29883. getLines(&lineData, QCPDataRange(0, dataCount()));
  29884. QCPVector2D p(pixelPoint);
  29885. for (int i=0; i<lineData.size()-1; ++i)
  29886. {
  29887. const double currentDistSqr = p.distanceSquaredToLine(lineData.at(i), lineData.at(i+1));
  29888. if (currentDistSqr < minDistSqr)
  29889. minDistSqr = currentDistSqr;
  29890. }
  29891. }
  29892. return qSqrt(minDistSqr);
  29893. }
  29894. int QCPPolarGraph::dataCount() const
  29895. {
  29896. return mDataContainer->size();
  29897. }
  29898. void QCPPolarGraph::getDataSegments(QList<QCPDataRange> &selectedSegments, QList<QCPDataRange> &unselectedSegments) const
  29899. {
  29900. selectedSegments.clear();
  29901. unselectedSegments.clear();
  29902. if (mSelectable == QCP::stWhole) // stWhole selection type draws the entire plottable with selected style if mSelection isn't empty
  29903. {
  29904. if (selected())
  29905. selectedSegments << QCPDataRange(0, dataCount());
  29906. else
  29907. unselectedSegments << QCPDataRange(0, dataCount());
  29908. } else
  29909. {
  29910. QCPDataSelection sel(selection());
  29911. sel.simplify();
  29912. selectedSegments = sel.dataRanges();
  29913. unselectedSegments = sel.inverse(QCPDataRange(0, dataCount())).dataRanges();
  29914. }
  29915. }
  29916. void QCPPolarGraph::drawPolyline(QCPPainter *painter, const QVector<QPointF> &lineData) const
  29917. {
  29918. // if drawing solid line and not in PDF, use much faster line drawing instead of polyline:
  29919. if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) &&
  29920. painter->pen().style() == Qt::SolidLine &&
  29921. !painter->modes().testFlag(QCPPainter::pmVectorized) &&
  29922. !painter->modes().testFlag(QCPPainter::pmNoCaching))
  29923. {
  29924. int i = 0;
  29925. bool lastIsNan = false;
  29926. const int lineDataSize = lineData.size();
  29927. while (i < lineDataSize && (qIsNaN(lineData.at(i).y()) || qIsNaN(lineData.at(i).x()))) // make sure first point is not NaN
  29928. ++i;
  29929. ++i; // because drawing works in 1 point retrospect
  29930. while (i < lineDataSize)
  29931. {
  29932. if (!qIsNaN(lineData.at(i).y()) && !qIsNaN(lineData.at(i).x())) // NaNs create a gap in the line
  29933. {
  29934. if (!lastIsNan)
  29935. painter->drawLine(lineData.at(i-1), lineData.at(i));
  29936. else
  29937. lastIsNan = false;
  29938. } else
  29939. lastIsNan = true;
  29940. ++i;
  29941. }
  29942. } else
  29943. {
  29944. int segmentStart = 0;
  29945. int i = 0;
  29946. const int lineDataSize = lineData.size();
  29947. while (i < lineDataSize)
  29948. {
  29949. 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
  29950. {
  29951. painter->drawPolyline(lineData.constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point
  29952. segmentStart = i+1;
  29953. }
  29954. ++i;
  29955. }
  29956. // draw last segment:
  29957. painter->drawPolyline(lineData.constData()+segmentStart, lineDataSize-segmentStart);
  29958. }
  29959. }
  29960. void QCPPolarGraph::getVisibleDataBounds(QCPGraphDataContainer::const_iterator &begin, QCPGraphDataContainer::const_iterator &end, const QCPDataRange &rangeRestriction) const
  29961. {
  29962. if (rangeRestriction.isEmpty())
  29963. {
  29964. end = mDataContainer->constEnd();
  29965. begin = end;
  29966. } else
  29967. {
  29968. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  29969. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  29970. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  29971. // get visible data range:
  29972. if (mPeriodic)
  29973. {
  29974. begin = mDataContainer->constBegin();
  29975. end = mDataContainer->constEnd();
  29976. } else
  29977. {
  29978. begin = mDataContainer->findBegin(keyAxis->range().lower);
  29979. end = mDataContainer->findEnd(keyAxis->range().upper);
  29980. }
  29981. // limit lower/upperEnd to rangeRestriction:
  29982. mDataContainer->limitIteratorsToDataRange(begin, end, rangeRestriction); // this also ensures rangeRestriction outside data bounds doesn't break anything
  29983. }
  29984. }
  29985. /*! \internal
  29986. This method retrieves an optimized set of data points via \ref getOptimizedLineData, an branches
  29987. out to the line style specific functions such as \ref dataToLines, \ref dataToStepLeftLines, etc.
  29988. according to the line style of the graph.
  29989. \a lines will be filled with points in pixel coordinates, that can be drawn with the according
  29990. draw functions like \ref drawLinePlot and \ref drawImpulsePlot. The points returned in \a lines
  29991. aren't necessarily the original data points. For example, step line styles require additional
  29992. points to form the steps when drawn. If the line style of the graph is \ref lsNone, the \a
  29993. lines vector will be empty.
  29994. \a dataRange specifies the beginning and ending data indices that will be taken into account for
  29995. conversion. In this function, the specified range may exceed the total data bounds without harm:
  29996. a correspondingly trimmed data range will be used. This takes the burden off the user of this
  29997. function to check for valid indices in \a dataRange, e.g. when extending ranges coming from \ref
  29998. getDataSegments.
  29999. \see getScatters
  30000. */
  30001. void QCPPolarGraph::getLines(QVector<QPointF> *lines, const QCPDataRange &dataRange) const
  30002. {
  30003. if (!lines) return;
  30004. QCPGraphDataContainer::const_iterator begin, end;
  30005. getVisibleDataBounds(begin, end, dataRange);
  30006. if (begin == end)
  30007. {
  30008. lines->clear();
  30009. return;
  30010. }
  30011. QVector<QCPGraphData> lineData;
  30012. if (mLineStyle != lsNone)
  30013. getOptimizedLineData(&lineData, begin, end);
  30014. switch (mLineStyle)
  30015. {
  30016. case lsNone: lines->clear(); break;
  30017. case lsLine: *lines = dataToLines(lineData); break;
  30018. }
  30019. }
  30020. void QCPPolarGraph::getScatters(QVector<QPointF> *scatters, const QCPDataRange &dataRange) const
  30021. {
  30022. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  30023. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  30024. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
  30025. if (!scatters) return;
  30026. QCPGraphDataContainer::const_iterator begin, end;
  30027. getVisibleDataBounds(begin, end, dataRange);
  30028. if (begin == end)
  30029. {
  30030. scatters->clear();
  30031. return;
  30032. }
  30033. QVector<QCPGraphData> data;
  30034. getOptimizedScatterData(&data, begin, end);
  30035. scatters->resize(data.size());
  30036. for (int i=0; i<data.size(); ++i)
  30037. {
  30038. if (!qIsNaN(data.at(i).value))
  30039. (*scatters)[i] = valueAxis->coordToPixel(data.at(i).key, data.at(i).value);
  30040. }
  30041. }
  30042. void QCPPolarGraph::getOptimizedLineData(QVector<QCPGraphData> *lineData, const QCPGraphDataContainer::const_iterator &begin, const QCPGraphDataContainer::const_iterator &end) const
  30043. {
  30044. lineData->clear();
  30045. // TODO: fix for log axes and thick line style
  30046. const QCPRange range = mValueAxis->range();
  30047. bool reversed = mValueAxis->rangeReversed();
  30048. 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
  30049. 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
  30050. 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
  30051. 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)
  30052. double skipBegin = 0;
  30053. bool belowRange = false;
  30054. bool aboveRange = false;
  30055. QCPGraphDataContainer::const_iterator it = begin;
  30056. while (it != end)
  30057. {
  30058. if (it->value < lowerClipValue)
  30059. {
  30060. if (aboveRange) // jumped directly from above to below visible range, draw previous point so entry angle is correct
  30061. {
  30062. aboveRange = false;
  30063. if (!reversed) // TODO: with inner radius, we'll need else case here with projected border point
  30064. lineData->append(*(it-1));
  30065. }
  30066. if (!belowRange)
  30067. {
  30068. skipBegin = it->key;
  30069. lineData->append(QCPGraphData(it->key, lowerClipValue));
  30070. belowRange = true;
  30071. }
  30072. if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle)
  30073. {
  30074. skipBegin += maxKeySkip;
  30075. lineData->append(QCPGraphData(skipBegin, lowerClipValue));
  30076. }
  30077. } else if (it->value > upperClipValue)
  30078. {
  30079. 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)
  30080. {
  30081. belowRange = false;
  30082. if (reversed)
  30083. lineData->append(*(it-1));
  30084. }
  30085. if (!aboveRange)
  30086. {
  30087. skipBegin = it->key;
  30088. lineData->append(QCPGraphData(it->key, upperClipValue));
  30089. aboveRange = true;
  30090. }
  30091. if (it->key-skipBegin > maxKeySkip) // add dummy point if we're exceeding the maximum skippable angle (to prevent unintentional intersections with visible circle)
  30092. {
  30093. skipBegin += maxKeySkip;
  30094. lineData->append(QCPGraphData(skipBegin, upperClipValue));
  30095. }
  30096. } else // value within bounds where we don't optimize away points
  30097. {
  30098. if (aboveRange)
  30099. {
  30100. aboveRange = false;
  30101. if (!reversed)
  30102. 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)
  30103. }
  30104. if (belowRange)
  30105. {
  30106. belowRange = false;
  30107. if (reversed)
  30108. lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis)
  30109. }
  30110. lineData->append(*it); // inside visible circle, add point normally
  30111. }
  30112. ++it;
  30113. }
  30114. // to make fill not erratic, add last point normally if it was outside visible circle:
  30115. if (aboveRange)
  30116. {
  30117. aboveRange = false;
  30118. if (!reversed)
  30119. 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)
  30120. }
  30121. if (belowRange)
  30122. {
  30123. belowRange = false;
  30124. if (reversed)
  30125. lineData->append(*(it-1)); // just entered from below, draw previous point so entry angle is correct (if below means outer, so if reversed axis)
  30126. }
  30127. }
  30128. void QCPPolarGraph::getOptimizedScatterData(QVector<QCPGraphData> *scatterData, QCPGraphDataContainer::const_iterator begin, QCPGraphDataContainer::const_iterator end) const
  30129. {
  30130. scatterData->clear();
  30131. const QCPRange range = mValueAxis->range();
  30132. bool reversed = mValueAxis->rangeReversed();
  30133. const double clipMargin = range.size()*0.05;
  30134. const double upperClipValue = range.upper + (reversed ? 0 : clipMargin); // clip slightly outside of actual range to avoid scatter size to peek into visible circle
  30135. const double lowerClipValue = range.lower - (reversed ? clipMargin : 0); // clip slightly outside of actual range to avoid scatter size to peek into visible circle
  30136. QCPGraphDataContainer::const_iterator it = begin;
  30137. while (it != end)
  30138. {
  30139. if (it->value > lowerClipValue && it->value < upperClipValue)
  30140. scatterData->append(*it);
  30141. ++it;
  30142. }
  30143. }
  30144. /*! \internal
  30145. Takes raw data points in plot coordinates as \a data, and returns a vector containing pixel
  30146. coordinate points which are suitable for drawing the line style \ref lsLine.
  30147. The source of \a data is usually \ref getOptimizedLineData, and this method is called in \a
  30148. getLines if the line style is set accordingly.
  30149. \see dataToStepLeftLines, dataToStepRightLines, dataToStepCenterLines, dataToImpulseLines, getLines, drawLinePlot
  30150. */
  30151. QVector<QPointF> QCPPolarGraph::dataToLines(const QVector<QCPGraphData> &data) const
  30152. {
  30153. QVector<QPointF> result;
  30154. QCPPolarAxisAngular *keyAxis = mKeyAxis.data();
  30155. QCPPolarAxisRadial *valueAxis = mValueAxis.data();
  30156. if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return result; }
  30157. // transform data points to pixels:
  30158. result.resize(data.size());
  30159. for (int i=0; i<data.size(); ++i)
  30160. result[i] = mValueAxis->coordToPixel(data.at(i).key, data.at(i).value);
  30161. return result;
  30162. }
  30163. /* end of 'src/polar/polargraph.cpp' */